equ*_*mer 5 email mime image html-email python-3.x
我正在尝试在电子邮件中嵌入图像。我遵循了此处、此处和此处以及其他示例,但是我无法显示图像。
import smtplib
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
logo = 'mylogo.png'
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = 'sender@email.com'
msg['To'] = 'recipient@email.com'
html = """\
<html>
<head></head>
<body>
<p>GREETING<br><br>
SOME TEXT<br>
MORE TEXT<br><br>
FAREWELL <br><br>
DISCLAIMER
</p>
<img src="cid:image1" alt="Logo" \>
</body>
</html> """
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html', 'utf-8')
msg.attach(part1)
msg.attach(part2)
fp = open(logo, 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID', '<image1>')
msgImage.add_header('Content-Disposition', 'inline', filename=os.path.basename(logo))
msgImage.add_header("Content-Transfer-Encoding", "base64")
msg.attach(msgImage)
s = smtplib.SMTP(smtp_server,25)
s.sendmail(sender, recipient, msg.as_string())
s.quit()
Run Code Online (Sandbox Code Playgroud)
当我执行此操作时,我得到一个空的主体,里面有一个红十字,没有图像。如何使图像与电子邮件正文一起显示?
我正在使用 Outlook 2016。我知道我可以在使用 Outlook 本身时插入图片,并且我收到了“正常”电子邮件,其中其他人在文本中插入了图像,所以这肯定意味着我必须能够查看从 python 脚本生成的图像?
编辑:我已经查看了此处给出的解决方案,建议作为可能的重复,但这也没有解决我的问题。
我还尝试将相同的电子邮件发送到 Gmail 和 hotmail 帐户,但仍然出现相同的问题,因此问题显然与代码有关。
我在 Outlook 2013 中找到了解决方案:
Outlook 似乎会寻找 span 标签以及一些图像信息,例如高度和宽度(现在硬编码)和 id 等。(见下文)我将图像包装在这个 html 文本中,然后还将图像添加为附件使用与我用于 cid 和 id 相同的号码。然后图像在 Outlook 中显示为嵌入文件。
# loop through all uploaded files and add as attachments
for index, file in enumerate(attachment):
with open(file, "rb") as fp:
data = fp.read()
fileType = os.path.splitext(file)[-1].strip(".")
ctype, _ = mimetypes.guess_type(file)
if embedImages and "image/" in ctype:
image = Image.open(data)
# Build out the html for the email
message += '<span style = "mso-no-proof:yes"><img width = 1280 height = 1920 id = "%s" src = "cid:%s"></span>' % (index, index)
# Define the image's ID
msgImage = MIMEImage(data, _subtype=fileType)
msgImage.add_header('Content-ID', '<%s>' % index)
msg.attach(msgImage)
att = MIMEApplication(data, _subtype=fileType)
att.add_header("Content-Disposition", "attachment", filename="%s" % index)
msg.attach(att)
else:
att = MIMEApplication(data, _subtype=fileType)
att.add_header("Content-Disposition", "attachment", filename=fileName)
msg.attach(att)
fp.close()
# Attach html text
if message:
if embedImages or "mimeType" in kwargs:
msg.attach(MIMEText(message, kwargs["mimeType"], 'utf-8'))
else:
msg.attach(MIMEText(message, "plain", 'utf-8'))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8768 次 |
最近记录: |