如何用Python从web服务器发送带有ZIP附件的电子邮件

2024-09-28 16:49:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个关于用Python发送带有ZIP附件的电子邮件的问题。我是这样做的:

def send_mail(send_from, send_to, subject, text, files=[], server="localhost"):
assert type(send_to)==list
assert type(files)==list

msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = COMMASPACE.join(send_to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject

msg.attach( MIMEText(text) )



for f in files:
    remotezip = urllib2.urlopen(f)
    #zipinmemory = io.BytesIO(remotezip.read())
    #zip = zipfile.ZipFile(zipinmemory)
    part = MIMEBase('application', 'octet-stream')



    part.set_payload( remotezip.read())
    Encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
    msg.attach(part)


smtp = smtplib.SMTP('smtp.gmail.com:587')
smtp.starttls()
smtp.login('username','password')
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.close()

由于我的ZIP文件托管在我的web服务器上,所以我使用URLOpen读取它。在

此代码成功地发送了带有附件的电子邮件。但是ZIP文件总是0KB。我确信在读取文件时出现了一些问题。在

请告诉我。谢谢你的帮助!在


Tags: 文件totextfromsend附件电子邮件msg