1

I have written a program which sends emails with python, it works for sending standard emails but I am having trouble attaching a file to it. I have watched several videos, and read a bunch of posts on this, but everything that I can find seems to be outdated and so doesn't work. Here is what I have so far:

import os
from email.message import EmailMessage
import ssl
import smtplib
email_sender = 'Example@gmail.com'
Password = 'gmail app password'
email_receiver = 'Example@gmail.com'
subject = 'message subject'
body = 'message body text'
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)
        smtp.sendmail(email_sender, email_receiver, em.as_string())

Thank you for any help that you can give, it is greatly appreciated.

1 Answers1

1

you need .add_attachment():

em.add_attachment(<the file to attach>, subtype=".pdf", filename="spam.pdf")
Jason Baker
  • 3,170
  • 2
  • 12
  • 15