对于 2021 年的 Python3,我建议使用以下方法来构建消息:
from email.message import EmailMessage
from email.utils import formataddr
msg = EmailMessage()
msg['Subject'] = "Message Subject"
msg['From'] = formataddr(("Sender's Name", "email@gmail.com"))
msg['Reply-To'] = formataddr(("Name of Reply2", "email2@domain2.com"))
msg['To'] = formataddr(("John Smith", "john.smith@gmail.com"))
msg.set_content("""\
<html>
<head></head>
<body>
<p>A simple test email</p>
</body>
</html>
""", subtype='html')
然后为了发送消息,我将以下内容用于在端口 587 上使用 StartTLS 的邮件服务器:
from smtplib import SMTP
from ssl import create_default_context as context
with SMTP('smtp.domain.com', 587) as server:
server.starttls(context=context())
server.login('email@domain.com', password)
server.send_message(msg)