我有一个将图片发送到邮箱的功能
要求是,我只有两个图像,第一个我需要发送作为附件,另一个在身体.
在MIMEMultiPart中使用Alternative,它将两个图像作为一个文档发送,我try 使用两个MultiPart,这也没有帮助.让我知道如何处理这个问题,也让我知道这是否可能
任何 idea 都将不胜感激
我有一个将图片发送到邮箱的功能
要求是,我只有两个图像,第一个我需要发送作为附件,另一个在身体.
在MIMEMultiPart中使用Alternative,它将两个图像作为一个文档发送,我try 使用两个MultiPart,这也没有帮助.让我知道如何处理这个问题,也让我知道这是否可能
任何 idea 都将不胜感激
根据HTML-Email with inline attachments and non-inline attachments,MIME的方法是构建一个内部MIME/相关消息,其中包含HTML文本和内联图像,而外部消息则包含MIME/相关消息和其他附件.
您的代码可能会变成
...
message_body = """<html>
<body><p>Please keep in touch and reach out to us for any help needed.</p>
<image src="cid:image"/></body></html>"""
msg = MIMEMultipart("mixed")
message_body = """<html>
<body><p>Please keep in touch and reach out to us for any help needed.</p>
<image src="cid:image"/></body></html>"""
msg = MIMEMultipart("mixed")
msg['From'] = username
msg['To'] = ','.join(to)
msg['Subject'] = subject
body = MIMEText(message_body, \
'html', 'utf-8')
inner = MIMEMultipart("related")
inner.attach(body)
msg.attach(inner)
...
image = MIMEImage(img_data, name=os.path.basename(x))
image.add_header('Content-Id', 'image')
inner.attach(image)
image_1 = MIMEImage(img_data_1, name=os.path.basename(y))
msg.attach(image_1)
...
在@triplee的 comments 之后,我try 了一下EmailMessage
API.它附带了更多的black magic,所以事情要简单得多,尽管不那么明确:
from email.message import EmailMessage
from imghdr import what
...
message_body = """<html>
<body><p>Please keep in touch and reach out to us for any help needed.</p>
<image src="cid:image"/></body></html>"""
msg = EmailMessage()
message_body = """<html>
<body><p>Please keep in touch and reach out to us for any help needed.</p>
<image src="cid:image"/></body></html>"""
msg = MIMEMultipart("mixed")
msg['From'] = username
msg['To'] = ','.join(to)
msg['Subject'] = subject
msg.set_content(message_body, subtype='html')
...
msg.add_related(img_data, 'image', what(x), cid='image')
msg.add_attachment(img_data_1, 'image', what(y),
filename=os.path.basename(y))
...