Python邮件发送HTML为纯文本

3
我有以下脚本,旨在发送电子邮件; 然而,电子邮件以纯文本形式发送而非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()

我正在使用在Ubuntu 18.04上的Python 3.9。谢谢大家!
2个回答

8

我通常使用smtplib

除了将文本设置为纯文本之外,您还需要设置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!")


我的代码基本上和你的一样,除了在HTML中的“DOCTYPE”。我已经添加了它,但它仍然以纯文本发送HTML。 - Elcid_91
我在Windows上使用Python 3.8,它运行得非常顺畅! - Mokhless
@Elcid_91 你可能在看旧的电子邮件。我刚刚尝试了这个例子,使用 Gmail 的应用程序密码,内容确实是 HTML 格式的。 - Niloct
看起来问题出在图片上。我删除了添加的图片,然后它就正常了。所以现在我无法弄清楚嵌入式图片添加有什么问题。 - Elcid_91
你在 HTML 源代码中使用过 <img src="cid:{msg_image}" /> 吗?另外,你的原始代码在 msg.get_payload()[1]add_related 之间缺少一个 . - Niloct
显示剩余2条评论

-1

来自Real Python

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# Create the plain-text and HTML version of your message
text = """\
Hi,
How are you?
Real Python has many great tutorials:
www.realpython.com"""
html = """\
<html>
  <body>
    <p>Hi,<br>
       How are you?<br>
       <a href="http://www.realpython.com">Real Python</a> 
       has many great tutorials.
    </p>
  </body>
</html>
"""

# Turn these into plain/html MIMEText objects
part1 = MIMEText(text, "plain")
part2 = MIMEText(html, "html")

# Add HTML/plain-text parts to MIMEMultipart message
# The email client will try to render the last part first
message.attach(part1)
message.attach(part2)

看起来你可以使用MIMEText函数和html参数。如果你能够导入这些库。


1
emailMessage 不是建议在 Python 3.4 及以上版本中使用吗? - Elcid_91
看起来您的email代码是为旧版本Python编写的。在Python 3.6中,标准库中的email模块进行了全面改进,以变得更加逻辑、多功能和简洁;新代码应该针对(不再很新的)新的EmailMessage API。可能需要放弃此代码,并从Python“电子邮件”示例文档中开始使用现代代码。 - tripleee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接