send HTMLbody from file using python(使用PYTHON从文件发送HTMLBody)
问题描述
我可以发送纯文本,但无法发送html格式的html文本。
import email, smtplib, ssl
import os
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
body = """
this is first mail by using python
"""
port_email = 587
smtp_server = "smtp.gmail.com"
password = "your password"
subject = "An email with attachment from Python"
sender_email = "sender@gmail.example.com"
receiver_email = "receiver@example.net"
# Create a multipart message and set headers
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
message["Bcc"] = receiver_email # Recommended for mass emails
# Add body to email
message.attach(MIMEText(body, "plain"))
filename = "file name" # In same directory as script
with open(filename.html, 'r', encoding="utf-8") as attachment:
part1 = attachment.read()
part2 = MIMEText(part1, "html")
message.attach(part2)
text = message.as_string()
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, 465 , context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, text)
这将发送附件文件,但我希望看到电子邮件正文中的html文本。 FileName是内容html表,因此代码应发送html文本,该文本将自动在html正文中随html表一起可用。
推荐答案
如果这不是您想要的,为什么要通过一个虚假的身体?
您的代码似乎是为Python3.5或更早版本编写的。email
库在3.6中进行了全面检查,现在它的通用性和逻辑性要强得多。可能会扔掉你所拥有的,重新开始examples from the email
documentation.
这是一个简短的尝试。
from email.message import EmailMessage
...
message = EmailMessage()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
# No point in using Bcc if the recipient is already in To:
with open(filename) as fp:
message.set_content(fp.read(), 'html')
# no need for a context if you are just using the default SSL
with smtplib.SMTP_SSL(smtp_server, 465) as server:
server.login(sender_email, password)
# Prefer the modern send_message method
server.send_message(message)
如果要同时以纯文本和HTML格式发送消息,链接的示例将向您展示如何调整代码以实现此目的,但实际上,text/plain
正文部分应该包含有用的消息,而不仅仅是占位符。
To:
头中指定了收件人,则没有理由使用Bcc:
。如果要使用Bcc:
,则必须在To:
头中添加其他内容,通常是您自己的地址或类似:undisclosed-recipients;
的地址列表
另外,在打开文件时,Python(或者实际上是操作系统)会检查用户的当前工作目录,而不是从中加载Python脚本的目录。也可以参阅What exactly is current working directory?
这篇关于使用PYTHON从文件发送HTMLBody的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!