问题
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.
回答1:
Late for the answer... but this is what I do:
email = EmailMessage()
email['Subject'] = 'subject'
email['From'] = FROM
email['To'] = 'to email'
with open('example.pdf', 'rb') as content_file:
content = content_file.read()
email.add_attachment(content, maintype='application/pdf', subtype='pdf', filename='example.pdf')
s.send_message(email)
By the way, this isnt a duplicate question, in this question, he use EmailMessage and don't use MIMEText / MIMEPart, etc.
来源:https://stackoverflow.com/questions/44528466/attaching-pdf-file-to-an-emailmessage