Python -- 通过电子邮件发送的 Zip 存档显示不正确

Python -- Emailed Zip Archieve not displaying correctly

我有一个程序可以每天向我自己和其他一些人发送自动报告。这些报告被写入我的 /tmp/ 目录中的一个文件夹,然后压缩成 Zip 存档并作为附件通过电子邮件发送。我期望的结果是所有用户都将附件视为 Reports_2017-06-20.zip(或当天的任何日期)。在我的电子邮件客户端上,我看到附件为 _tmp_Engineering_Reports_2017-06-20.zip。报告的一位收件人声称附件仅出现在他的电子邮件客户端中 2。在所有情况下,文件都通过电子邮件成功传输,但 zip 文件通常必须由最终用户手动重命名以提取文件并查看它们。下面是我的电子邮件 class。字典 passed_values 是在 class 之外创建的。传递的 filename/tmp/Reports_2017-06-20

import smtplib
from email import encoders
from email.MIMEBase import MIMEBase
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText


class EmailHandler(object):
    def __init__(self, passed_values):
        self._filename = passed_values.get('filename')
        self._subject = passed_values.get('subject')
        self._from_address = passed_values.get('from_address')
        self._to_addresses = passed_values.get('to_addresses')
        self._email_password = passed_values.get('email_password')
        self._body = passed_values.get('body')

    @property
    def filename(self):
        return self._filename

    @filename.setter
    def filename(self, value):
        self._filename = value

    @property
    def from_address(self):
        return self._from_address

    @from_address.setter
    def from_address(self, value):
        self._from_address = value

    @property
    def to_addresses(self):
        return self._to_addresses

    @to_addresses.setter
    def to_addresses(self, value):
        self._to_addresses = value

    @property
    def body(self):
        return self._body

    @body.setter
    def body(self, value):
        self._body = value

    @property
    def subject(self):
        return self._body

    @body.setter
    def body(self, value):
        self._body = value

    def send_email_with_attachment(self):
        msg = MIMEMultipart()
        msg['From'] = self._from_address
        msg['To'] = ', '.join(self._to_addresses)
        msg['Subject'] = self._subject
        msg.attach(MIMEText(self._body, 'plain'))
        attachment = open (self._filename + '.zip', "rb")
        part = MIMEBase('application', 'octet-stream')
        part.set_payload(attachment.read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition', "attachment; filename= %s" % self._filename + '.zip')
        msg.attach(part)
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()
        server.login(self._from_address, self._email_password)
        text = msg.as_string()
        server.sendmail(self._from_address, self._to_addresses, text)
        server.quit()

谁能告诉我我做错了什么?

使用 os.path.basename 这样您就可以只在 Content-Disposition header 中发送文件名(而不是完整路径)。电子邮件客户端似乎不确定如何处理包含斜杠的 "filename"。