0

I'm trying to send inline image in email using the below function:

def create_message_without_attachment (sender, to, subject, message_text_html, message_text_plain,image):

message = MIMEMultipart()
message['Subject'] = subject
message['From'] = sender
message['To'] = to

img = MIMEImage(image.read())
img.add_header('Content-Id', '<image1>')
message.attach(img)

message.attach(MIMEText('<p><img src="cid:image1" /></p>'+message_text_html, 'html'))

raw_message_no_attachment = base64.urlsafe_b64encode(message.as_bytes())
raw_message_no_attachment = raw_message_no_attachment.decode()
body  = {'raw': raw_message_no_attachment}
return body

But when I receive the email I just get

<p> <img> </p>

Any help is appreciated.

saeedar
  • 305
  • 2
  • 19
  • Is the image in the MIME package? (e.g. if you do "show original" in Gmail, do you see the image content section in the email?) – payne Oct 10 '18 at 19:20
  • And, possible duplicate: https://stackoverflow.com/questions/920910/sending-multipart-html-emails-which-contain-embedded-images – payne Oct 10 '18 at 19:21
  • @payne Yes, there was img content. Not a duplicate.., the code worked outside of spyder.. – saeedar Oct 11 '18 at 06:13

1 Answers1

0
def create_message_without_attachment (sender, to, subject, message_text_html, message_text_plain,image):

message = MIMEMultipart()
message['Subject'] = subject
message['From'] = sender
message['To'] = to

message.attach(MIMEText('<p><img src="cid:image1" /></p>'+message_text_html, 'html'))

image.seek(0)
img = MIMEImage(image.read(), 'png')
img.add_header('Content-Id', '<image1>')
img.add_header("Content-Disposition", "inline", filename="image1")
message.attach(img)

raw_message_no_attachment = base64.urlsafe_b64encode(message.as_bytes())
raw_message_no_attachment = raw_message_no_attachment.decode()
body  = {'raw': raw_message_no_attachment}
return body

Also this function was in another file. So, when I was importing and calling this function in "Spyder", it didn't work, because Spyder was using the old/cached version of the imported file...

saeedar
  • 305
  • 2
  • 19