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

  • Have you tried attaching the image, i.e. `msg.add_header('Content-Disposition', 'attachment', filename='image_name.jpg')` and/or ` msg.add_attachment(*args, content_manager=None, **kw)¶`? Your html render the page, but you to have access to the image? The other option is to use a remote url if your email service allows it. I would also look at a working example and see how your email compares. – Allan Wind Sep 01 '21 at 23:04
  • I have access to image. msg.add_header(...) attaches the image. But not in the body of the email. – Jack Sullivan Sep 02 '21 at 00:11

2 Answers2

0

In order to link to an attached image in an email, you have to use a special URL that starts with "cid:". Check here:

Embedding attached images in HTML emails

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • This is not the best way forward. Not all email applications support this method which uses base64 encoding, see https://www.caniemail.com/features/image-base64/ – Nathan Sep 02 '21 at 00:03
  • That's not what I'm talking about. I'm talking about an image attached as a separate MIME section, and an image tag with `src="cid:myimage.png"`. That's in RFC 1813 and support is nearly universal. – Tim Roberts Sep 02 '21 at 03:21
  • Ok, it appears CID doesn't necessarily base64 encode. However, it is correct to say not all email applications support this method - particularly webmail. As reported by SendGrid https://sendgrid.com/blog/embedding-images-emails-facts/ and MailTrap https://mailtrap.io/blog/embedding-images-in-html-email-have-the-rules-changed/ – Nathan Sep 03 '21 at 01:14
0

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"

Nathan
  • 4,358
  • 2
  • 10
  • 26