gpt4 book ai didi

python - 通过 python 电子邮件发送电子邮件时 HTML 无法正确呈现

转载 作者:太空宇宙 更新时间:2023-11-04 10:22:01 25 4
gpt4 key购买 nike

我正在使用我公司的 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['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()

我应该怎么做?

最佳答案

只是想告诉大家使用 yagmail 发送带附件的电子邮件是多么容易(完全披露:我是开发人员)。我的理念是只需要弄清楚如何处理 MIME 内容,然后就再也不会回头了。

您可以使用以下 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 代码、图像(内联)、文本和任何其他文件。是的,我为此感到非常自豪。

我鼓励您阅读 github documentation查看其他不错的功能,例如,您不必使用 key 环在脚本中输入密码/用户名(额外的安全性)。设置一次,您会很高兴....

哦,是的,要安装,您可以使用:

pip install yagmail  # python 2
pip3 install yagmail # python 3

关于python - 通过 python 电子邮件发送电子邮件时 HTML 无法正确呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31734506/

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