带有HTML的Python电子邮件包

2024-10-03 04:33:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找解决这个问题的方法:通过SMTP发送包含HTML的电子邮件。我正在跟踪文档here https://docs.python.org/3/library/email.html和here https://docs.python.org/3/library/email.examples.html,但找不到一个解决方法来集成HTML以添加图像部分:

asparagus_cid = make_msgid()
msg.add_alternative("""\
<html>
  <head></head>
  <body>
   <p>Salut!</p>
   <p>Cela ressemble à un excellent
     <a href="http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718">
        recipie
    </a> déjeuner.
</p>
<img src="cid:{asparagus_cid}" />
</body>
</html>
""".format(asparagus_cid=asparagus_cid[1:-1]), subtype='html')

with open("roasted-asparagus.jpg", 'rb') as img:
     msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg',
                                 cid=asparagus_cid)

Tags: 方法httpsorgadddocsimghereemail
1条回答
网友
1楼 · 发布于 2024-10-03 04:33:45

编辑:
要插入python object,可以使用f-strings。它们不笨重,并且平滑地自附着到任何字符串对象

from email.message import EmailMessage

object_to_be_inserted = "love"

message = EmailMessage()
message.add_alternative(f"""<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>

    {object_to_be_inserted}

  </body>
</html>
""", subtype="html")
print(message)
[output]: Content-Type: multipart/alternative;
 boundary="===============1697891563109361365=="

 ===============1697891563109361365==
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: 7bit
MIME-Version: 1.0

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    love
  </body>
</html>
 ===============1697891563109361365== 

================================================================
旧答案:
可以使用EmailMessage类的实例发送带有html的电子邮件。subtype参数允许您将消息的格式从纯文本更改为html等格式

import smtplib
from email.message import EmailMessage #This class has all you need to constitute an email message

#Initiate an instance of EmailMessage
message = EmailMessage()

message['subject'] = "The email subject"
message['From'] = 'your@address.com'
message['To'] = 'recipient@address.com'

#Now for the message body
message.set_content('A plain text fallback')
message.add_alternative("""<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    
  </body>
</html>
""", subtype='html')

#Then on with your endeavour as you must've seen in the documentation.
with smtplib.SMTP_SSL('server_address', <port_no>) as smtp:
    smtp.login('address', 'password')
    smtp.send_message(message)

现在,请看图片。您可以将其添加到html正文中,就像在静态网页中一样

相关问题 更多 >