假设您要附加的 zip 文件是 '/home/local/user/project/zip_module/csv.zip',
和to、sender、subject 和text 分别包含您的收件人地址、发件人地址、主题和邮件文本。
那么,
import smtplib, MimeWriter, mimetools, base64
message = StringIO.StringIO()
email_msg = MimeWriter.MimeWriter(message)
email_msg.addheader('To', to)
email_msg.addheader('From', sender)
email_msg.addheader('Subject', subject)
email_msg.addheader('MIME-Version', '1.0')
email_msg.startmultipartbody('mixed')
part = email_msg.nextpart()
body = part.startbody('text/plain')
part.flushheaders()
body.write(text)
file_to_attach = '/home/local/user/project/zip_module/csv.zip'
filename = os.path.basename(file_to_attach)
ftype, encoding = 'application/zip', None
part = email_msg.nextpart()
part.addheader('Content-Transfer-Encoding', encoding)
body = part.startbody("%s; name=%s" % (ftype, filename))
mimetools.encode(open(file_to_attach, 'rb'), body, encoding)
email_msg.lastpart()
email_text = message.getvalue()
现在像使用smtplib 一样发送电子邮件,将email_text 用作msg
例如
smtp = smtplib.SMTP(SERVER, PORT)
smtp.login(USER, PASSWORD)
smtp.sendmail(sender, to, email_text)
smtp.quit()