Attaching pdf file to an EmailMessage?

老子叫甜甜 提交于 2020-01-03 04:58:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!