我有一个程序可以向我自己和其他一些人发送每日自动报告。这些报告将写入我/tmp/
目录中的文件夹,然后压缩为Zip存档并作为附件通过电子邮件发送。我期望的结果是所有用户都可以将附件看作Reports_2017-06-20.zip
(或当天的任何日期)。在我的电子邮件客户端上,我将附件视为_tmp_Engineering_Reports_2017-06-20.zip
。该报告的一位收件人声称该附件仅显示在其电子邮件客户端2
中。在所有情况下,文件都通过电子邮件成功传输,但通常必须由最终用户手动重命名zip文件以提取文件并查看它们。以下是我的电子邮件课程。字典passed_values
是在此类之外创建的。传递的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()
有人可以告诉我我做错了吗?
答案 0 :(得分:1)
使用os.path.basename
,这样您只需在Content-Disposition
标题中发送文件名(而不是完整路径)。似乎电子邮件客户端不确定如何处理包含斜杠的“文件名”。