将pdf文件附加到EmailMessage吗? [英] Attaching pdf file to an EmailMessage?

查看:128
本文介绍了将pdf文件附加到EmailMessage吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置自动电子邮件发送脚本。我正在使用电子邮件模块和 email.message 模块中的 EmailMessage 对象,并使用 smtplib 模块。我希望能够将.pdf文件附加到电子邮件,但是 EmailMessage() add_attachment()方法的文档c $ c>并不是很有帮助,我甚至不确定我应该使用它。

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()

如何附加pdf文件?我搜索了一下,发现一个答案是使用MIMEText对象添加附件,但它似乎无法使用pdf。

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.

推荐答案

Late for答案...但这是我的工作:

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', subtype='pdf', filename='example.pdf')

s.send_message(email)

顺便说一句,这不是一个重复的问题,在这个问题中,他使用EmailMessage而不使用MIMEText / MIMEPart等。

By the way, this isnt a duplicate question, in this question, he use EmailMessage and don't use MIMEText / MIMEPart, etc.

这篇关于将pdf文件附加到EmailMessage吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆