0

So, I have a program which sends emails for me. The goal of this program is to have it run on a schedule, and send emails out every 24hrs, but first I need to figure out how to attach an image to the emails being sent. Here is what I have so far:

import os
from email.message import EmailMessage
import ssl
import smtplib
email_sender = 'Example@gmail.com'
Password = 'app password'
email_receiver = 'Example@gmail.com'
subject = 'Message subject'
body = 'message body'
em = EmailMessage()
em['From'] = email_sender
em['To'] = email_receiver
em['Subject'] = subject
em.set_content(body)
context = ssl.create_default_context()
with smtplib.SMTP_SSL('smtp.gmail.com', 465, context=context) as smtp:
        smtp.login(email_sender, Password)
        em.add_attachment('path to desired .jpg file', subtype = ".jpg", filename = ".jpg file name")
        smtp.sendmail(email_sender, email_receiver, em.as_string())

So, the problem that I am having is that, it will send the email with the attachment, but when the attachment is opened, it is just a printout of the path of that the image had from my computer, and not the image itself. So, how do I actually link a picture to the email, and not just the path? Thank you for any help that you can provide.

1 Answers1

1

If you want the contents, then pass the contents:

        em.add_attachment(open('path to desired .jpg file', 'rb').read(), subtype = ".jpg", filename = ".jpg file name")

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30