使用 Python 发送带有富文本和嵌入图像的电子邮件

时间:2021-07-04 01:58:14

标签: python html email mime-types mime

我正在学习如何使用 Python 来自动化电子邮件,并且在创建“干净”的电子邮件时遇到了问题。

问题:我有一个 Google 文档,它有一个特定的文本,然后是一个图像,然后是一些文本。我希望将其用作电子邮件的内容,希望使用 Python 发送

方法:根据我在 SO 和博客上阅读的内容,我使用了 MIMEMultipart 并将我的原始文档分成 3 部分:textimage、{{3}我下载了两个文本文件的 html 版本。此后,我使用了以下代码:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage

from string import Template

me = "myemail@gmail.com"
you = "youremail@gmail.com"

msg = MIMEMultipart()
msg['From'] = me
msg['To'] = you
msg['Subject'] = 'This is a test'

html1 = open('test_doc_part1.html')
part1 = MIMEText(html1.read(), 'html')
msg.attach(part1)
html1.close()

image_text = MIMEText('<img src="cid:image1">', 'html')
msg.attach(image_text)
fp = open('test_image.jpg', 'rb')
image = MIMEImage(fp.read())
fp.close()
image.add_header('Content-ID', '<image1>') # Define the image's ID as referenced in the HTML body above
msg.attach(image)

html2 = open('test_doc_part2.html')
part2 = MIMEText(html2.read(), 'html')
msg.attach(part2)
html2.close()


server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(me, "password")

text = msg.as_string()
# Do text substitutions here
server.sendmail(from_addr= me, to_addrs= you, msg=text)
server.quit()

问题:根据文本来源,我的电子邮件文本要么隐藏在图像下方,要么全部/部分带有下划线/乱码。我正在使用 gmail 并在 Google Chrome 中查看此电子邮件。可以查看收到的电子邮件的原始内容text。有人能指出我哪里不正确吗?

0 个答案:

没有答案
相关问题