Python通过电子邮件发送PDF没有名称

时间:2017-06-19 14:58:51

标签: python python-3.x email pdf

我找到并扩展了一个脚本,该脚本将扫描目录,然后通过电子邮件发送内部的pdf。收到电子邮件时会出现问题。 PDF是以'noname'文件形式到达的,没有扩展名。我必须下载它们并手动添加扩展以显示它们。这里有什么我想念的吗?

import sys
import os
import smtplib
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart

COMMASPACE = ', '

def main():
    sender = 'jp@voice.com'
    password = 'pword'
    recipients = 'j@gmail.com'

    # Create enclosing (outer) message
    outer = MIMEMultipart()
    outer['Subject'] = 'TEST EMAIL'
    outer['To'] = COMMASPACE.join(recipients)
    outer['From'] = sender
    outer.preamble = 'You will not see this in a MIMIE aware reader'

    # list of attachments
    attachments = r'C:/Users/Ace/Desktop/PDFTST/'
    attach = os.listdir(attachments)
    for file in attach:
        try:
            with open(attachments + file, 'rb') as fp:
                msg = MIMEBase('application', "octet-stream")
                msg.set_payload(fp.read())
            encoders.encode_base64(msg)
            outer.attach(msg)
        except:
            print("unable to open the attach. Error: ", sys.exc_info()[0])
            raise

        composed = outer.as_string()

    try:
        with smtplib.SMTP('smtp.gmail.com', 587) as s:
            s.ehlo()
            s.starttls()
            s.ehlo()
            s.login(sender, password)
            s.sendmail(sender, recipients, composed)
            s.close()
        print("email sent!!!!")
    except:
        print("Unable to send email. Error: ", sys.exc_info()[0])
        raise

if __name__ == '__main__':
    main()

2 个答案:

答案 0 :(得分:0)

我认为您应该将MIME类型设置为application / pdf,而不是application / octet-stream。

指定如下文件名:

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

答案 1 :(得分:0)

乔的评论修正了我在文本文件中遇到的类似情况。对于您的示例,键入:

msg = MIMEBase('application',“ pdf”,Name = file)