将PDF附加到电子邮件时出现奇怪错误

时间:2015-02-27 01:21:17

标签: python pdf

我试图将PDF文件附加到这样的电子邮件中:

def send_email(gmail, password, post_description, 
               reply_email, attachment_path, email_body_path):
    msg = MIMEMultipart()

    with open(email_body_path) as f:
        msg.attach(MIMEText(f.read()))

    if attachment_path != None:
        with open(attachment_path, 'rb') as f:
            msg.attach(MIMEApplication(
                f.read(),
                Content_Disposition='attachment, filename="%s"' % basename(f)))
    smtp = smtplib.SMTP('smtp.gmail.com',587)
    smtp.login(gmail, password)
    smtp.sendmail(gmail, 'address@gmail.com', msg.as_string()

附有PDF并且标题正确,但内容始终是" ECO"没有别的。

1 个答案:

答案 0 :(得分:0)

有关如何正确制作附件的信息,请参阅email examples

outer = MIMEMultipart()
<...>
fp = open(path, 'rb')

msg = MIMEAplication(fp.read(), _subtype=subtype) #or another appropriate subclass
                                                  #some subclasses have additional parameters
<or>
msg = MIMEBase(maintype, subtype)
msg.set_payload(fp.read())
encoders.encode_base64(msg)

msg.add_header('Content-Disposition', 'attachment', filename=filename)
outer.attach(msg)

要在邮件中添加文字,您需要根据multipart/alternative example附加MIMEText以及PDF(如果不符合RFC规定,请不要忘记指定编码默认,iso-8859-1):

part = MIMEText(<text>, _charset='<charset>')
outer.attach(part)

所以,除了形成MIMEApplication之外,你正在做所有事情。 MIMEBase.__init__源代码显示构造函数调用上的额外参数都进入Content-Type标题。