如何使用Python在电子邮件中发送HTML内容?我可以发送简单的短信。
当前回答
我在这里提供答案可能有点晚了,但是这个问题询问了一种发送HTML电子邮件的方法。使用像“email”这样的专用模块是可以的,但我们可以在不使用任何新模块的情况下实现相同的结果。这都归结为Gmail协议。
下面是我的简单示例代码,仅通过使用“smtplib”发送HTML邮件,而不使用其他任何代码。
```
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)
```
其他回答
如果你想要更简单的东西:
from redmail import EmailSender
email = EmailSender(host="smtp.myhost.com", port=1)
email.send(
subject="Example email",
sender="me@example.com",
receivers=["you@example.com"],
html="<h1>Hi, this is HTML body</h1>"
)
Pip从PyPI安装红色邮件:
pip install redmail
红色邮件几乎有所有你需要从发送电子邮件,它有很多功能,包括:
附件 模板化(使用Jinja) 嵌入式图像 他们的表 以抄送或密送方式发送 Gmail预配置
文档:https://red-mail.readthedocs.io/en/latest/index.html
源代码:https://github.com/Miksus/red-mail
来自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()
对于python3,改进@taltman的回答:
使用email.message. emailmessage而不是email.message. message来构造email。 使用电子邮件。Set_content func, assign subtype='html'参数。而不是低级的func set_payload和手动添加头。 使用SMTP。send_message func而不是SMTP。Sendmail func发送电子邮件。 与块一起使用,可自动关闭连接。
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)
下面是发送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()
实际上,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。