我一直在使用python中的电子邮件模块,但我希望能够知道如何嵌入包含在html中的图像.
所以,例如,如果身体是这样的
<img src="../path/image.png"></img>
Run Code Online (Sandbox Code Playgroud)
我想将image.png嵌入到电子邮件中,该src属性应该替换为content-id.有人知道怎么做这个吗?
下面给出了使用python发送图像嵌入式电子邮件的代码.
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
# Define these once; use them twice!
strFrom = 'from@sender.com'
strTo = 'to@example.com'
# Create the root message and fill in the from, to, and subject headers
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'test message'
msgRoot['From'] = strFrom
msgRoot['To'] = strTo
msgRoot.preamble = 'This is a multi-part message in MIME format.'
# Encapsulate the plain and HTML versions of the message body in an
# 'alternative' part, so …Run Code Online (Sandbox Code Playgroud) 我看过其他几篇文章,包括:
创建带有图像的MIME电子邮件模板以使用python / django发送
这些以及smtplib和电子邮件的python文档使我离我很近。我正在使用下面的代码来创建嵌入了简单jpg的电子邮件。如果我将电子邮件发送给gmail,它将很好地显示嵌入的图像,但Outlook 2013无法显示。
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
From = ''
To = ''
msg = MIMEMultipart()
msg['Subject'] = 'image test message'
msg['From'] = From
msg['To'] = To
text = 'This is sample text from me'
html = '''
<html>
<head>
<title> this is a test title </title>
</head>
<body>
<p> Test me <br>
Another line <br>
This is the image you were looking for <img …Run Code Online (Sandbox Code Playgroud) 我正在尝试在电子邮件中嵌入图像。我遵循了此处、此处和此处以及其他示例,但是我无法显示图像。
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', …Run Code Online (Sandbox Code Playgroud) email ×4
python ×3
html-email ×2
mime ×2
attachment ×1
image ×1
multipart ×1
outlook ×1
python-3.x ×1
sendmail ×1
smtplib ×1
spam ×1