我可以发送纯文本,但无法发送 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 = "[email protected] /cdn-cgi/l/email-protection"
receiver_email = "[email protected] /cdn-cgi/l/email-protection"
# 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 文本。
文件名是内容 html 表,因此代码应该发送 html 文本,该文本将自动在带有 html 表的 html 正文中可用。
如果这不是你想要的,你为什么要传递一个假尸体?
您的代码似乎是为 Python 3.5 或更早版本编写的。这email
库在 3.6 中进行了彻底修改,现在更加通用和逻辑化。可能会扔掉你拥有的并重新开始的例子来自email文档。 https://docs.python.org/3/library/email.examples.html
这是一个简短的尝试。
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
正文部分实际上应该包含有用的消息,而不仅仅是占位符。
正如代码中注释的那样,没有理由使用Bcc:
如果您已经在邮件中指定了收件人To:
标头。如果你想使用Bcc:
你必须在其中放入其他东西To:
标头,通常是您自己的地址或地址列表,例如:undisclosed-recipients;
顺便说一句,打开文件时,Python(或者实际上是操作系统)会检查用户当前的工作目录,而不是加载 Python 脚本的目录。也许还可以看到当前工作目录到底是什么? https://stackoverflow.com/questions/45591428/what-exactly-is-current-working-directory
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)