1

i try to send multiple images in a roundcube webmail with python but when i try my program, it's give me an email but it only have 1 picture:like this (other images aren't displayed but they are in attachments with weird name (courriel html).

This is my code for the mail (first part work well):

# Send an HTML email with an embedded image and a plain text message for
# email clients that don't want to display the HTML.

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
import os

# Define these once; use them twice!
strFrom = 'x@x.com'
strTo = 'x@x.com'

# Create the root message and fill in the from, to, and subject headers
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'test message'
msgRoot['From'] = strFrom
msgRoot['To'] = strTo
msgRoot.preamble = 'This is a multi-part message in MIME format.'

# Encapsulate the plain and HTML versions of the message body in an
# 'alternative' part, so message agents can decide which they want to display.
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)

msgText = MIMEText('This is the alternative plain text message.')
msgAlternative.attach(msgText)

dest="/home/user/Bureau/photos/"
dirmail=os.listdir(dest)
os.chdir(dest)
FilesOs=os.listdir(os.curdir)
print('(mail.py): ',len(dirmail))

I think that the problem is about the <img src="cid:image" >:

if len(dirmail)!=0:
   for f in FilesOs: 
      # We reference the image in the IMG SRC attribute by the ID we give it below
      msgText = MIMEText('<img src="cid:image"><br>', 'html')
      msgAlternative.attach(msgText)

      # This example assumes the image is in the current directory
      fp = open(dest+f, 'rb')
      msgImage = MIMEImage(fp.read(),_subtype='jpg')
      fp.close()

      # Define the image's ID as referenced above
      msgImage.add_header('Content-ID', '<image>')
      msgRoot.attach(msgImage)
      os.remove(dest+f)
      print("remove ",f)

The last part work well:

 # Send the email (this example assumes SMTP authentication is required)
    import smtplib

session = smtplib.SMTP('x', x) 
session.starttls() #enable security
session.login("x", "x") #login with mail_id and password
session.sendmail(strFrom, strTo, msgRoot.as_string())
session.quit()
print('Mail Sent')

If you have any solution because i block here, thank's in advance.

Diego
  • 11
  • 2

0 Answers0