I am trying to set up an automated email sending script. I am using the email module and the EmailMessage
object from the email.message
module and am sending the email using the smtplib
module. I would like to be able to attach a .pdf file to an email but the documentation for the add_attachment()
method for EmailMessage()
is not very helpful and I'm not even sure I should be using it.
Here is what I have so far with irrelevant information removed:
import time
import smtplib
from email.message import EmailMessage
FROM = 'my email'
s = smtplib.SMTP('smtp.gmail.com', 587)
s.ehlo()
s.starttls()
s.login('my email', 'password')
for line in open('to.csv'):
line = line.strip()
fields = line.split(',')
subject = 'subject'
email = EmailMessage()
email['Subject'] = 'subject'
email['From'] = FROM
email['To'] = 'to email'
s.send_message(email)
print('Sent to {0}'.format(fields[TO]))
time.sleep(5)
s.quit()
How do I go about attaching the pdf file? I searched and saw one answer was using the MIMEText object to add attachments but it did not appear to work pdf.