Search code examples
pythonimageemailhtml-email

I'm not able to add an image in email body using email.message in python


import smtplib
import email.message

def sent_email(From,email,passw):  
    body = f"""
    <p>Text blabla </p>
    <img src="image_name.jpg" alt="loading problem" width=400 height=560>
    """

    msg = email.message.Message()
    msg['Subject'] = "subject"
    msg['From'] = From
    msg['To'] = email
    password = passw
    msg.add_header('Content-Type', 'text/html')
    msg.set_payload(body )

    s = smtplib.SMTP('smtp.gmail.com: 587')
    s.starttls()
    # Login Credentials for sending the mail
    s.login(msg['From'], password)
    s.sendmail(msg['From'], [msg['To']], msg.as_string().encode('utf-8'))
    print('Email sent')

The email is sent, but the image does not appear. The message "loading problem" appears.

Just found how to attach. I want it in the body of the email.


Solution

  • It may be as simple as uploading the image to a publicly accessible webserver, and using the full path to it, i.e. not src="image_name.jpg" but rather src="https://www.imageserver.com/folder/image_name.jpg"