如何使用Python发送带有HTML内容的电子邮件?我能够发送简单的文本。
如何使用Python发送带有HTML内容的电子邮件?我能够发送简单的文本。
从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()
s
对象。如果我想发送多条消息怎么办?我是每次发送消息都要退出还是全部发送(在for循环中)然后一次性退出? - xpanta以下是已被接受的答案的Gmail版本实现: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()
您可以尝试使用我的mailer模块。
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)
use_tls=True
、usr='email'
和pwd='password'
,它就能正常工作了。请注意,这里的“邮箱”和“密码”指的是您的 Gmail 邮箱地址和密码。 - ToonAlfrinkmessage.Body = """当客户端无法显示HTML电子邮件时,显示一些文本"""
。 - IvanD以下是一种简单的方法,可以通过指定Content-Type头为“text/html”来发送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()
smtplib.SMTP()
示例,它不使用tls。我在工作中使用了这个内部脚本,我们使用ssmtp和本地邮件集线器。此外,这个示例缺少s.quit()
。 - Mike S针对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'] = '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)
email.add_alternative()
(与使用email.set_content()
添加HTML的方法相同),然后使用email.add_attachment()
添加附件来改进此功能(这让我花费了很长时间才弄清楚)。 - Zilbert97EmailMessage
API只在Python 3.6及以上版本中正式提供,尽管在3.3版本中已经作为替代方法出现。新代码应该绝对使用这个API而不是旧的email.message.Message
遗留API,大部分答案中都还在建议使用旧API。任何涉及到MIMEText
或MIMEMultipart
的部分都是旧API,除非你有遗留原因,否则应该避免使用。 - tripleeeemail.set context
中使用文件而不是手动输入HTML? - Michaelreport_file = open('resetpasswordemail.html') html = report_file.read() em.set_content(html, subtype='html')
- Michael这是一段示例代码,灵感来源于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()
email.message.Message
API更古老、更杂乱。MimeWriter
库在2003年Python 2.3中已被弃用。 - tripleee实际上,yagmail 采取了一种略微不同的方法。
它将默认发送HTML格式的邮件,并自动为不支持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。
smtplib
在Python中发送纯文本和HTML电子邮件的工作示例,还包括CC和BCC选项。#!/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)
```
import smtplib
FROM = "....@gmail.com"
TO = "another....@gmail.com"
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)
```
email
库不是一个“新模块”,它与 smtplib
一样是标准库的一部分。您绝对不应该像这样组合字符串来创建消息;虽然对于非常简单的消息似乎可以工作,但一旦您离开了仅包含7位US-ASCII内容的单个 text/plain
负载的舒适领域,就会以灾难性的方式失败(即使在这种情况下,也有可能会遇到一些棘手的问题,特别是如果您不知道自己在做什么)。 - tripleee在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 中。