如何使用Python在邮箱中发送HTML内容?我可以发送简单的文本.

推荐答案

Python v2.7.14 documentation - 18.1.11. email: Examples:

以下是如何使用替代纯文本版本创建HTML消息的示例:

#! /usr/bin/python

import smtplib

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

# me == my email address
# you == recipient's email address
me = "my@email.com"
you = "your@email.com"

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you

# Create the body of the message (a plain-text and an HTML version).
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html = """\
<html>
  <head></head>
  <body>
    <p>Hi!<br>
       How are you?<br>
       Here is the <a href="http://www.python.org">link</a> you wanted.
    </p>
  </body>
</html>
"""

# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)

# Send the message via local SMTP server.
s = smtplib.SMTP('localhost')
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail(me, you, msg.as_string())
s.quit()

Python相关问答推荐

如何过滤包含2个指定子字符串的收件箱列名?

基于字符串匹配条件合并两个帧

如何使用表达式将字符串解压缩到Polars DataFrame中的多个列中?

如果值发生变化,则列上的极性累积和

梯度下降:简化要素集的运行时间比原始要素集长

为什么NumPy的向量化计算在将向量存储为类属性时较慢?'

如果初始groupby找不到满足掩码条件的第一行,我如何更改groupby列,以找到它?

在Python中调用变量(特别是Tkinter)

matplotlib + python foor loop

为什么'if x is None:pass'比'x is None'单独使用更快?

Python避免mypy在相互引用中从另一个类重定义类时失败

30个非DATETIME天内的累计金额

如何在Python Pandas中填充外部连接后的列中填充DDL值

如何在Airflow执行日期中保留日期并将时间转换为00:00

我如何处理超类和子类的情况

EST格式的Azure数据库笔记本中的当前时间戳

有没有一种方法可以根据不同索引集的数组从2D数组的对称子矩阵高效地构造3D数组?

如何让PYTHON上的Selify连接到现有的Firefox实例-我无法连接到Marionette端口

GEKKO中若干参数的线性插值动态优化

通过PyTorch中的MIN函数传递渐变