使用 Python 发送 HTML 电子邮件

问题描述 投票:0回答:12

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

python html email html-email
12个回答
538
投票

来自 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 = "[email protected]"
you = "[email protected]"

# 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()

82
投票

这是已接受答案的 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 = "[email protected]"
you = "[email protected]"

# 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()

72
投票

您可以尝试使用我的mailer模块。

from mailer import Mailer
from mailer import Message

message = Message(From="[email protected]",
                  To="[email protected]")
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)

67
投票

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

import email.message
import smtplib

msg = email.message.Message()
msg['Subject'] = 'foo'
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
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()

61
投票

对于python3,改进@taltman的答案

  • 使用
    email.message.EmailMessage
    而不是
    email.message.Message
    来构建电子邮件。
  • 使用
    email.set_content
    函数,分配
    subtype='html'
    参数。而不是低级功能
    set_payload
    并手动添加标头。
  • 使用
    SMTP.send_message
    函数代替
    SMTP.sendmail
    函数发送电子邮件。
  • 使用
    with
    块自动关闭连接。
from email.message import EmailMessage
from smtplib import SMTP

# construct email
email = EmailMessage()
email['Subject'] = 'foo'
email['From'] = '[email protected]'
email['To'] = '[email protected]'
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)

12
投票

这是示例代码。这是受到在 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 <[email protected]>')
    server = smtplib.SMTP("smtp_server_address","smtp_port")
    server.login('username', 'password')
    server.sendmail('[email protected]', '[email protected]', message)
    server.quit()

7
投票

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

它将“默认情况下”发送 HTML,并为无法阅读电子邮件的用户提供自动回退功能。现在已经不是17世纪了。 当然,它可以被覆盖,但这里是:

import yagmail yag = yagmail.SMTP("[email protected]", "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("[email protected]", "the subject", html_msg)

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


5
投票
smtplib

以及抄送和密件抄送选项从 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 = "[email protected]" 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': '[email protected]', 'email_cc': '[email protected]', 'email_bcc': '[email protected]', 'email_subject': 'Test message from python library', 'email_body': '<h1>Hello World</h1>' } for t in ['plain', 'html']: send_mail(params, t)



3
投票

下面是我仅使用“smtplib”发送 HTML 邮件的简单示例代码,而不使用其他任何东西。

import smtplib FROM = "[email protected]" TO = "[email protected]" SUBJECT= "Subject" PWD = "thesecretkey" TEXT=""" <h1>Hello</h1> """ #Your Message (Even Supports HTML Directly) message = f"Subject: {SUBJECT}\nFrom: {FROM}\nTo: {TO}\nContent-Type: text/html\n\n{TEXT}" #This is where the stuff happens try: server=smtplib.SMTP("smtp.gmail.com",587) server.ehlo() server.starttls() server.login(FROM,PWD) server.sendmail(FROM,TO,message) server.close() print("Successfully sent the mail.") except Exception as e: print("Failed to send the mail..", e)



2
投票

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 <[email protected]>', Destination={'ToAddresses': [email]}, Message={ 'Subject': {'Data': subject}, 'Body': { 'Html': {'Data': html} } }



2
投票
从 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


2
投票

from redmail import EmailSender email = EmailSender(host="smtp.myhost.com", port=1) email.send( subject="Example email", sender="[email protected]", receivers=["[email protected]"], html="<h1>Hi, this is HTML body</h1>" )

PyPI

安装 Red Mail: pip install redmail

Red Mail 很可能拥有您发送电子邮件所需的所有功能,并且它具有很多功能,包括:

    附件
  • 模板(使用 Jinja)
  • 嵌入图像
  • 美化桌子
  • 以抄送或密送方式发送
  • Gmail 预配置
  • 文档:
https://red-mail.readthedocs.io/en/latest/index.html

源代码:

https://github.com/Miksus/red-mail

© www.soinside.com 2019 - 2024. All rights reserved.