Search code examples
python-3.6gmail-apimime

Adding inline image in gmail api results in empty image


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.


Solution

  • 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...