gpt4 book ai didi

python - 在 html 中嵌入图像以自动发送 Outlook365 电子邮件

转载 作者:太空宇宙 更新时间:2023-11-03 14:14:29 25 4
gpt4 key购买 nike

我正在尝试使用 python 中的 smtp 和电子邮件在我的 html 代码中嵌入图像。套餐有:导入smtplib从 email.mime.multipart 导入 MIMEMultipart从 email.mime.text 导入 MIMEText

这是 html 中的片段

<img border=0 width=231 height=67 src="Hello_files/image001.png">

这是我在实际发送的电子邮件中看到的 enter image description here

我觉得我正在做一些非常错误的事情,这对大多数人来说可能是显而易见的。

最佳答案

根据您的 HTML 片段,我将对此进行尝试。

您的 HTML

<img border=0 width=231 height=67 src="Hello_files/image001.png">

您正在引用本地文件系统中显示的图像,但在收件人计算机中的电子邮件上下文中,该目录和文件名将不存在。

HTML 示例

<img src='cid:image1' alt='image' style="display: block;margin: auto;width: 100%;">

这里我们将图像引用为cid:image1。在我们的 python 代码中,我们加载图像并对其进行编码以与我们的 html 匹配。在下面的示例中,图像 test.png 与我们的 python 脚本位于同一目录中。

MIME 图像编码示例

s = smtplib.SMTP(host='smtp.gmail.com', port=587)
s.starttls()
s.login('email','password')

msg = MIMEMultipart() # create a message

email_body = "<img src='cid:image1' alt='image' style="display: block;margin: auto;width: 100%;">"

# Read and encode the image
img_data = open('./test.png', 'rb').read()
image = MIMEImage(img_data)
image.add_header('Content-ID', '<image1>')
msg.attach(image)

# Construct the email
msg['From']='swetjen@someplace.com'
msg['To']='swetjen@someplace.com'
msg['Subject']='My email with an embedded image.'

msg.attach(MIMEText(email_body, _subtype='html'))

s.send_message(msg)

关于python - 在 html 中嵌入图像以自动发送 Outlook365 电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48272100/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com