您正在经历巨大的痛苦来构建有效的 MIME 消息msg
,然后放弃它并发送一个简单的字符串email_message
反而。
您可能应该首先了解正确的 MIME 结构是什么样的。多部分消息本身没有任何内容,如果您想要文本部分,则必须添加文本部分。
以下是对脚本的编辑,添加了缺失的部分。我没有尝试发送结果消息。However,请参阅下面的现代化版本。
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText # Added
from email.mime.image import MIMEImage
attachment = 'bob.jpg'
msg = MIMEMultipart()
msg["To"] = to_addr
msg["From"] = from_addr
msg["Subject"] = subject
msgText = MIMEText('<b>%s</b><br/><img src="cid:%s"/><br/>' % (body, attachment), 'html')
msg.attach(msgText) # Added, and edited the previous line
with open(attachment, 'rb') as fp:
img = MIMEImage(fp.read())
img.add_header('Content-ID', '<{}>'.format(attachment))
msg.attach(img)
print(msg.as_string()) # or go ahead and send it
(我还稍微清理了 HTML。)
从 Python 3.6 开始,Python 的email
库已升级为更加模块化、逻辑化和正交(从技术上讲,从 3.3 开始就已经如此,但在 3.6 中,新版本成为首选)。新代码应该避免像上面的代码那样显式创建单独的 MIME 部分,并且可能看起来更像是
from email.message import EmailMessage
from email.utils import make_msgid
attachment = 'bob.jpg'
msg = EmailMessage()
msg["To"] = to_addr
msg["From"] = from_addr
msg["Subject"] = subject
attachment_cid = make_msgid()
msg.set_content(
'<b>%s</b><br/><img src="cid:%s"/><br/>' % (
body, attachment_cid[1:-1]), 'html')
with open(attachment, 'rb') as fp:
msg.add_related(
fp.read(), 'image', 'jpeg', cid=attachment_cid)
# print(msg.as_string()), or go ahead and send
您会注意到这与“芦笋”示例非常相似emailPython 标准库中的示例文档。 https://docs.python.org/3/library/email.examples.html