我有以下应该发送电子邮件的脚本;但是,电子邮件是以纯文本而不是 HTML 形式发送的。我错过了一段代码吗?
import smtplib, ssl, mimetypes
from email.message import EmailMessage
from email.utils import make_msgid
def send_email():
server = connect_server()
if server:
html = """\
<html>
<body>
<div style="width:60%;background-color:#193048;border:4px solid #3c71aa;padding:5px 10px">
Putting My Email Text Here!
</div>
</body>
</html>
"""
msg = EmailMessage()
msg["Subject"] = "Subject"
msg["From"] = "Support <support@example.xyz>"
msg["To"] = "{} <{}>".format("Test Human","<test.human@somewhere.xyz>")
msg.set_content('Plain Text Here!')
msg_image = make_msgid(domain="example.xyz")
msg.add_alternative(html.format(msg_image=msg_image[1:-1],subtype="html"))
with open("./resources/email-logo.png","rb") as fp:
maintype,subtype = mimetypes.guess_type(fp.name)[0].split('/')
msg.get_payload()[1]add_related(fp.read(),maintype=maintype,subtype=subtype,cid=msg_image)
server.sendmail("Support <support@example.xyz","{} <{}>".format(Test Human,test.human@somewhere.xyz),msg.as_string())
server.quit()
Run Code Online (Sandbox Code Playgroud)
我在 Ubuntu 18.04 上使用 Python3.9。谢谢大家!
我通常使用smtplib
除了将文本设置为 之外simple text,您还需要设置html内容!
import smtplib
from email.message import EmailMessage
html = """<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Your HTML Title</title>
<body>
<h1>The best html email content!!!</h1>
</body>
</html>
"""
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
smtp.login('my_email', 'my_password')
try:
msg = EmailMessage()
msg.set_content('simple text would go here - This is a fallback for html content')
msg.add_alternative(html, subtype='html')
msg['Subject'] = 'Subject of your email would go here!'
msg['From'] = 'my_email'
msg['To'] = 'my_contact@mail.com'
msg['Cc'] = ''
msg['Bcc'] = ''
smtp.send_message(msg)
except:
print("Something went wrong!!!")
print("DONE!")
Run Code Online (Sandbox Code Playgroud)