使用Python发送HTML电子邮件


260

如何使用Python在电子邮件中发送HTML内容?我可以发送简单的文字。


只是一个很大的警告。如果要使用Python <3.0 发送非ASCII电子邮件,请考虑在Django中使用该电子邮件。它可以正确包装UTF-8字符串,并且使用起来也简单得多。您已被警告:-)
安德斯·鲁恩·詹森

1
如果要发送带有Unicode的HTML,请参见此处:stackoverflow.com/questions/36397827/…–
guettli

Answers:


419

来自Python v2.7.14文档-18.1.11。电子邮件:示例

这是一个如何使用替代纯文本版本创建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()

1
是否可以附加第三部分和第四部分,两者均为附件(一个ASCII,一个二进制)?那怎么办?谢谢。
Hamish Grubijan 2010年

1
嗨,我注意到您最终还是quit这个s对象。如果我想发送多条消息怎么办?我是否应该在每次发送消息或全部发送消息时(在for循环中)退出,然后一劳永逸地退出?
xpanta 2012年

确保最后附加html,因为preferred(showing)部分将是最后附加的部分。 # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. 我希望我2个小时前读过
dwkd 2015年

1
警告:如果文本中包含非ASCII字符,则此操作将失败。
guettli '16

2
嗯,我收到了msg.as_string()的错误消息:列表对象没有属性编码
JohnAndrews

61

您可以尝试使用我的邮件程序模块。

from mailer import Mailer
from mailer import Message

message = Message(From="me@example.com",
                  To="you@example.com")
message.Subject = "An HTML Email"
message.Html = """<p>Hi!<br>
   How are you?<br>
   Here is the <a href="http://www.python.org">link</a> you wanted.</p>"""

sender = Mailer('smtp.example.com')
sender.send(message)

Mailer模块很棒,但是它声称可以与Gmail一起使用,但是不能使用,也没有文档。
MFB

1
@MFB-您是否尝试过Bitbucket回购?bitbucket.org/ginstrom/mailer
瑞安·金斯特罗姆

2
对于gmail,应该提供use_tls=Trueusr='email'并且pwd='password'在初始化Mailer时可以使用。
ToonAlfrink 2014年

我建议在message.Html行之后立即在您的代码中添加以下行:message.Body = """Some text to show when the client cannot show HTML emails"""
IvanD

很棒,但是如何将变量值添加到链接中,我的意思是创建这样的链接<a href=" python.org/somevalues"> link </a>,以便我可以从其访问的路由中访问该值。谢谢
TaraGurung

49

这是已接受答案的Gmail实现:

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.
mail = smtplib.SMTP('smtp.gmail.com', 587)

mail.ehlo()

mail.starttls()

mail.login('userName', 'password')
mail.sendmail(me, you, msg.as_string())
mail.quit()

2
很棒的代码,如果我在Google中
有用

15
我在python smtplib上使用了Google 应用程序专用密码,在无需降低安全性的情况下完成了此操作。
yoyo

2
对于阅读以上评论的任何人:如果您先前已在Gmail帐户中启用了两步验证,则仅需要“应用密码”。
Mugen

有没有一种方法可以在邮件的HTML部分中动态添加一些内容?
岩浆

40

这是发送HTML电子邮件的一种简单方法,只需将Content-Type标头指定为“ text / html”即可:

import email.message
import smtplib

msg = email.message.Message()
msg['Subject'] = 'foo'
msg['From'] = 'sender@test.com'
msg['To'] = 'recipient@test.com'
msg.add_header('Content-Type','text/html')
msg.set_payload('Body of <b>message</b>')

# Send the message via local SMTP server.
s = smtplib.SMTP('localhost')
s.starttls()
s.login(email_login,
        email_passwd)
s.sendmail(msg['From'], [msg['To']], msg.as_string())
s.quit()

2
这是一个很好的简单答案,对于快速而肮脏的脚本非常有用,谢谢。顺便说一句,可以参考一个简单的smtplib.SMTP()示例,该示例不使用tls。我在工作中使用ssmtp和本地mailhub的内部脚本中使用了它。另外,此示例丢失了s.quit()
Mike S

1
未定义“ mailmerge_conf.smtp_server” ...至少是Python 3.6所说的...
ZEE

使用基于列表的收件人时出现错误AttributeError:'list'对象没有属性'lstrip'任何解决方案?
navotera

10

这是示例代码。这是从Python Cookbook网站上找到的代码启发而来的(找不到确切的链接)

def createhtmlmail (html, text, subject, fromEmail):
    """Create a mime-message that will render HTML in popular
    MUAs, text in better ones"""
    import MimeWriter
    import mimetools
    import cStringIO

    out = cStringIO.StringIO() # output buffer for our message 
    htmlin = cStringIO.StringIO(html)
    txtin = cStringIO.StringIO(text)

    writer = MimeWriter.MimeWriter(out)
    #
    # set up some basic headers... we put subject here
    # because smtplib.sendmail expects it to be in the
    # message body
    #
    writer.addheader("From", fromEmail)
    writer.addheader("Subject", subject)
    writer.addheader("MIME-Version", "1.0")
    #
    # start the multipart section of the message
    # multipart/alternative seems to work better
    # on some MUAs than multipart/mixed
    #
    writer.startmultipartbody("alternative")
    writer.flushheaders()
    #
    # the plain text section
    #
    subpart = writer.nextpart()
    subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
    pout = subpart.startbody("text/plain", [("charset", 'us-ascii')])
    mimetools.encode(txtin, pout, 'quoted-printable')
    txtin.close()
    #
    # start the html subpart of the message
    #
    subpart = writer.nextpart()
    subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
    #
    # returns us a file-ish object we can write to
    #
    pout = subpart.startbody("text/html", [("charset", 'us-ascii')])
    mimetools.encode(htmlin, pout, 'quoted-printable')
    htmlin.close()
    #
    # Now that we're done, close our writer and
    # return the message body
    #
    writer.lastpart()
    msg = out.getvalue()
    out.close()
    print msg
    return msg

if __name__=="__main__":
    import smtplib
    html = 'html version'
    text = 'TEST VERSION'
    subject = "BACKUP REPORT"
    message = createhtmlmail(html, text, subject, 'From Host <sender@host.com>')
    server = smtplib.SMTP("smtp_server_address","smtp_port")
    server.login('username', 'password')
    server.sendmail('sender@host.com', 'target@otherhost.com', message)
    server.quit()


5

对于python3,请改善@taltman的答案

  • 使用email.message.EmailMessage而不是email.message.Message构造电子邮件。
  • 使用email.set_contentfunc,分配subtype='html'参数。而不是低级func set_payload并手动添加标头。
  • 使用SMTP.send_messagefunc而不是SMTP.sendmailfunc发送电子邮件。
  • 使用with块自动关闭连接。
from email.message import EmailMessage
from smtplib import SMTP

# construct email
email = EmailMessage()
email['Subject'] = 'foo'
email['From'] = 'sender@test.com'
email['To'] = 'recipient@test.com'
email.set_content('<font color="red">red color text</font>', subtype='html')

# Send the message via local SMTP server.
with smtplib.SMTP('localhost') as s:
    s.login('foo_user', 'bar_password')
    s.send_message(email)

4

实际上,yagmail采取了一些不同的方法。

默认情况下,它将发送HTML,并为没有能力的电子邮件阅读器自动回退。现在已经不是17世纪了。

当然,可以覆盖它,但是这里是:

import yagmail
yag = yagmail.SMTP("me@example.com", "mypassword")

html_msg = """<p>Hi!<br>
              How are you?<br>
              Here is the <a href="http://www.python.org">link</a> you wanted.</p>"""

yag.send("to@example.com", "the subject", html_msg)

有关安装说明和更多重要功能,请查看github


3

这是一个工作示例,该示例使用Python smtplib和CC和BCC选项从Python发送纯文本和HTML电子邮件。

https://varunver.wordpress.com/2017/01/26/python-smtplib-send-plaintext-and-html-emails/

#!/usr/bin/env python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def send_mail(params, type_):
      email_subject = params['email_subject']
      email_from = "from_email@domain.com"
      email_to = params['email_to']
      email_cc = params.get('email_cc')
      email_bcc = params.get('email_bcc')
      email_body = params['email_body']

      msg = MIMEMultipart('alternative')
      msg['To'] = email_to
      msg['CC'] = email_cc
      msg['Subject'] = email_subject
      mt_html = MIMEText(email_body, type_)
      msg.attach(mt_html)

      server = smtplib.SMTP('YOUR_MAIL_SERVER.DOMAIN.COM')
      server.set_debuglevel(1)
      toaddrs = [email_to] + [email_cc] + [email_bcc]
      server.sendmail(email_from, toaddrs, msg.as_string())
      server.quit()

# Calling the mailer functions
params = {
    'email_to': 'to_email@domain.com',
    'email_cc': 'cc_email@domain.com',
    'email_bcc': 'bcc_email@domain.com',
    'email_subject': 'Test message from python library',
    'email_body': '<h1>Hello World</h1>'
}
for t in ['plain', 'html']:
    send_mail(params, t)

认为此答案涵盖了所有内容。很棒的链接
stingMantis

1

这是我使用boto3的AWS答案

    subject = "Hello"
    html = "<b>Hello Consumer</b>"

    client = boto3.client('ses', region_name='us-east-1', aws_access_key_id="your_key",
                      aws_secret_access_key="your_secret")

client.send_email(
    Source='ACME <do-not-reply@acme.com>',
    Destination={'ToAddresses': [email]},
    Message={
        'Subject': {'Data': subject},
        'Body': {
            'Html': {'Data': html}
        }
    }

0

从Office 365中的组织帐户发送电子邮件的最简单解决方案:

from O365 import Message

html_template =     """ 
            <html>
            <head>
                <title></title>
            </head>
            <body>
                    {}
            </body>
            </html>
        """

final_html_data = html_template.format(df.to_html(index=False))

o365_auth = ('sender_username@company_email.com','Password')
m = Message(auth=o365_auth)
m.setRecipients('receiver_username@company_email.com')
m.setSubject('Weekly report')
m.setBodyHTML(final_html_data)
m.sendMessage()

此处df是转换为html表的数据帧,该表将被注入html_template


这个问题没有提及有关使用Office或组织帐户的任何信息。
功夫
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.