通过python电子邮件发送电子邮件时HTML呈现不正确
我正在使用我公司的smtp服务器使用python的电子邮件模块发送电子邮件。当我这样做时,我的电子邮件html没有正确呈现。这就是我得到的:通过python电子邮件发送电子邮件时HTML呈现不正确,python,html,python-2.7,email,smtp,Python,Html,Python 2.7,Email,Smtp,我正在使用我公司的smtp服务器使用python的电子邮件模块发送电子邮件。当我这样做时,我的电子邮件html没有正确呈现。这就是我得到的: sender = 'abc@abc.com' # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('multipart') msg['Subject'] = "My Report" msg['Fr
sender = 'abc@abc.com'
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('multipart')
msg['Subject'] = "My Report"
msg['From'] = sender
msg['To'] = ", ".join(recipients)
# Create the body of the message using html in msg_body
h = unicode(msg_body).encode("utf-8", "ignore")
# Record the MIME type
part = MIMEText(h, 'html')
# Attach parts into message container.
msg.attach(part)
pngfiles = ['image.png']
for file in pngfiles:
# Open the files in binary mode.
fp = open(file, 'rb')
img = MIMEImage(fp.read())
fp.close()
msg.attach(img)
# Send the message via local SMTP server.
s = smtplib.SMTP('send.abc.com')
s.sendmail(msg.get("From"), recipients, msg.as_string())
s.quit()
我应该做些什么不同呢?只是想告诉大家使用(完全公开:我是开发人员)发送带有附件的电子邮件是多么容易。我的人生哲学是,只需一次想出如何处理哑剧,然后再也不回头 您可以使用以下三行发送电子邮件:
import yagmail
yag = yagmail.SMTP(sender, your_password)
# assuming your undefined "msg_body" is just some message (string)
yag.send(recipients, 'My report', contents = [msg_body, '/local/path/to/image.png'])
你可以用内容做各种各样的事情:如果你有一个东西的列表,它会很好地结合起来。例如,一个文件名列表将使其能够附加所有文件名。把它和一些信息混合在一起,它就会有一条信息
将附加任何有效文件的字符串,其他字符串仅为文本
它可以很好地处理HTML代码、图像(内联)、文本和任何其他文件。是的,我很自豪
我鼓励您阅读以查看其他优秀功能,例如,您不必使用钥匙圈在脚本中输入密码/用户名(额外安全)。设置一次,你就会很高兴
哦,是的,要安装,您可以使用:
pip install yagmail # python 2
pip3 install yagmail # python 3
我只是想告诉大家使用(完全公开:我是开发人员)发送带有附件的电子邮件是多么容易。我的人生哲学是,只需一次想出如何处理哑剧,然后再也不回头 您可以使用以下三行发送电子邮件:
import yagmail
yag = yagmail.SMTP(sender, your_password)
# assuming your undefined "msg_body" is just some message (string)
yag.send(recipients, 'My report', contents = [msg_body, '/local/path/to/image.png'])
你可以用内容做各种各样的事情:如果你有一个东西的列表,它会很好地结合起来。例如,一个文件名列表将使其能够附加所有文件名。把它和一些信息混合在一起,它就会有一条信息
将附加任何有效文件的字符串,其他字符串仅为文本
它可以很好地处理HTML代码、图像(内联)、文本和任何其他文件。是的,我很自豪
我鼓励您阅读以查看其他优秀功能,例如,您不必使用钥匙圈在脚本中输入密码/用户名(额外安全)。设置一次,你就会很高兴
哦,是的,要安装,您可以使用:
pip install yagmail # python 2
pip3 install yagmail # python 3
可能与?如您所见,我的子类型已经是“html”。问题是我必须将字符集设置为“utf-8”。从文档中:如果_文本(第一个参数)是unicode,则使用_字符集的输出字符集对其进行编码,否则按原样使用。默认值为us ascii。在我的例子中,第一个参数是unicode。part=MIMEText(h,'html,'utf-8')可能与?如您所见,我的子类型已经是'html'。问题是我必须将字符集设置为'utf-8'。从文档中:如果_文本(第一个参数)是unicode,则使用_字符集的输出字符集对其进行编码,否则按原样使用。默认值为us ascii。在我的例子中,第一个参数是unicode。part=MIMEText(h,'html','utf-8')