Python3多部分电子邮件(文本,电子邮件和附件)

时间:2013-07-15 07:45:32

标签: python smtp

我正在用Python创建一些电子邮件,我想要HTML,文本和附件。我的代码是“工作”,虽然它的输出由Outlook显示为HTML或文本,同时将另一个“部分”(email或txt)显示为附件。我希望电子邮件和文本版本以及文件附件具有健壮性。

是否存在基本限制,或者我犯了错误?

#!/usr/bin/env python3
import smtplib,email,email.encoders,email.mime.text,email.mime.base
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# me == my email address
# you == recipient's email address
me = "me@me.com"
you = "you@you.com"

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('mixed')
msg['Subject'] = "msg"
msg['From'] = me
msg['To'] = you

# Create the body of the message (a plain-text and an HTML version).
text = "Hi\nThis is text-only"
html = """\
<html> This is email</html>
"""

part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
#attach an excel file:
fp = open('excelfile.xlsx', 'rb')
file1=email.mime.base.MIMEBase('application','vnd.ms-excel')
file1.set_payload(fp.read())
fp.close()
email.encoders.encode_base64(file1)
file1.add_header('Content-Disposition','attachment;filename=anExcelFile.xlsx')

# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part2)
msg.attach(part1)
msg.attach(file1)

composed = msg.as_string()

fp = open('msgtest.eml', 'w')
fp.write(composed)
fp.close()

1 个答案:

答案 0 :(得分:0)

我发现事实已经得到了解答。奇怪的是,搜索功能的效果不如“相关”框。

Sending Multipart html emails which contain embedded images