用Python发送电子邮件
你可以用 Python 发送邮件,使用多个库,但最常见的是 smtplib 和 email。
Python 中的"smtplib"模块定义了一个 SMTP 客户端会话对象,可用于向任何带有 SMTP 或 ESMTP 监听器守护进程的互联网机器发送邮件。电子邮件"包"是一个用于管理电子邮件的库,包括MIME和其他基于RFC 2822的消息文档。
处理和传递电子邮件的应用程序称为"邮件服务器"。简单邮件传输协议(SMTP)是一种协议,用于在邮件服务器之间发送电子邮件和路由邮件。它是电子邮件传输的互联网标准。
Python smptlib.SMTP() 功能
Python smptlib.SMTP() 函数用于创建 SMTP 客户端会话对象,建立与 SMTP 服务器的连接。这种连接允许你通过服务器发送邮件。
搭建SMTP服务器
在发送邮件之前,你需要搭建一个SMTP服务器。常见的SMTP服务器包括Gmail、Yahoo或其他邮件服务提供商提供的服务器。
创建 SMTP 对象
发送电子邮件时,你需要通过以下函数获得SMTP类的对象------
python
import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
以下是参数的详细情况 −
-
host − 这是运行你 SMTP 服务器的主机。你可以指定主机的IP地址或域名,比如 tutorialspoint.com。这是一个可选的论点。
-
port − 如果你提供主机参数,则需要指定一个端口,其中SMTP服务器正在监听。通常这个端口是25。
-
local_hostname − 如果你的SMTP服务器运行在本地机器上,那么你可以选择只用localhost作为选项。
示例
以下脚本连接到端口25的"smtp.example.com"SMTP服务器,可选地识别并保护连接,登录(如有需要),发送邮件,然后退出会话−
python
import smtplib
# Create an SMTP object and establish a connection to the SMTP server
smtpObj = smtplib.SMTP('smtp.example.com', 25)
# Identify yourself to an ESMTP server using EHLO
smtpObj.ehlo()
# Secure the SMTP connection
smtpObj.starttls()
# Login to the server (if required)
smtpObj.login('username', 'password')
# Send an email
from_address = 'your_email@example.com'
to_address = 'recipient@example.com'
message = """\
Subject: Test Email
This is a test email message.
"""
smtpObj.sendmail(from_address, to_address, message)
# Quit the SMTP session
smtpObj.quit()
Python smtpd 模块
Python smtpd 模块用于创建和管理一个简单的邮件传输协议(SMTP)服务器。该模块允许您搭建一个SMTP服务器,能够接收和处理来电邮件,因此在测试和调试应用内的电子邮件功能时非常有价值。
搭建 SMTP 调试服务器
smtpd 模块预装了 Python,并包含本地 SMTP 调试服务器。该服务器适合测试电子邮件功能,而无需实际发送邮件到指定地址;相反,它会将邮件内容打印到控制台。
运行该本地服务器消除了处理消息加密或使用凭证登录邮件服务器的需求。
启动 SMTP 调试服务器
您可以使用命令提示符或终端中的以下命令启动本地 SMTP 调试服务器 −
python
python -m smtpd -c DebuggingServer -n localhost:1025
示例
以下示例演示如何利用 smtplib 功能与本地 SMTP 调试服务器一起发送假邮件 −
python
import smtplib
def prompt(prompt):
return input(prompt).strip()
fromaddr = prompt("From: ")
toaddrs = prompt("To: ").split()
print("Enter message, end with ^D (Unix) or ^Z (Windows):")
# Add the From: and To: headers at the start!
msg = ("From: %s\r\nTo: %s\r\n\r\n"
% (fromaddr, ", ".join(toaddrs)))
while True:
try:
line = input()
except EOFError:
break
if not line:
break
msg = msg + line
print("Message length is", len(msg))
server = smtplib.SMTP('localhost', 1025)
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
在此例中 −
-
From− 你输入发送者的电子邮件地址(fromaddr)。
-
To − 你输入收件人的电子邮件地址(toaddrs),可以是多个用空格分隔的地址。
-
Message − 你输入消息内容,结尾为 ^D(Unix)或 ^Z(Windows)。
sendmail() 方法中的"smtplib"会将邮件发送到运行于"localhost"(1025端口)的本地 SMTP 调试服务器,使用指定的发送人、收件人和消息内容。
输出
当你运行程序时,控制台会输出程序和SMTP服务器之间的通信。与此同时,运行SMTPD服务器的终端会显示收到的邮件内容,帮助你调试和验证邮件发送过程。
python
python example.py
From: abc@xyz.com
To: xyz@abc.com
Enter message, end with ^D (Unix) or ^Z (Windows):
Hello World
^Z
控制台反映的日志如下 −
python
From: abc@xyz.com
reply: retcode (250); Msg: b'OK'
send: 'rcpt TO:<xyz@abc.com>\r\n'
reply: b'250 OK\r\n'
reply: retcode (250); Msg: b'OK'
send: 'data\r\n'
reply: b'354 End data with <CR><LF>.<CR><LF>\r\n'
reply: retcode (354); Msg: b'End data with <CR><LF>.<CR><LF>'
data: (354, b'End data with <CR><LF>.<CR><LF>')
send: b'From: abc@xyz.com\r\nTo: xyz@abc.com\r\n\r\nHello
World\r\n.\r\n'
reply: b'250 OK\r\n'
reply: retcode (250); Msg: b'OK'
data: (250, b'OK')
send: 'quit\r\n'
reply: b'221 Bye\r\n'
reply: retcode (221); Msg: b'Bye'
SMTPD服务器运行的终端显示该输出−
python
---------- MESSAGE FOLLOWS ----------
b'From: abc@xyz.com'
b'To: xyz@abc.com'
b'X-Peer: ::1'
b''
b'Hello World'
------------ END MESSAGE ------------
使用 Python 发送 HTML 邮件
要用 Python 发送 HTML 邮件,你可以使用 smtplib 库连接到 SMTP 服务器,使用 email.mime 模块来合理构建和格式化你的邮件内容。
构建HTML邮件消息
发送HTML邮件时,你需要指定特定的头部并相应结构化消息内容,以确保收件人的邮件客户端识别并呈现为HTML。
示例
以下是在 Python 中以电子邮件形式发送 HTML 内容的示例 −
python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# Email content
sender = 'from@fromdomain.com'
receivers = ['to@todomain.com']
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['From'] = 'From Person <from@fromdomain.com>'
msg['To'] = 'To Person <to@todomain.com>'
msg['Subject'] = 'SMTP HTML e-mail test'
# HTML message content
html = """\
<html>
<head></head>
<body>
<p>This is an e-mail message to be sent in <b>HTML format</b></p>
<p><b>This is HTML message.</b></p>
<h1>This is headline.</h1>
</body>
</html>
"""
# Attach HTML content to the email
part2 = MIMEText(html, 'html')
msg.attach(part2)
# Connect to SMTP server and send email
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, msg.as_string())
print("Successfully sent email")
except smtplib.SMTPException as e:
print(f"Error: unable to send email. Error message: {str(e)}")
以电子邮件发送附件
要在 Python 中发送电子邮件附件,您可以使用 smtplib 库连接到 SMTP 服务器,使用 email.mime 模块来构建和格式化您的邮件内容,包括附件。
构建带有附件的电子邮件
发送带有附件的邮件时,你需要使用MIME(多用途互联网邮件扩展)正确格式化邮件。这需要将 Content-Type 头设置为 multipart/mixed ,表示邮件包含文本和附件。邮件的每个部分(文本和附件)都被边界分隔开。
示例
以下是示例,发送带有文件 /tmp/test.txt 作为附件的电子邮件 −
python
import smtplib
import base64
filename = "/tmp/test.txt"
# Read a file and encode it into base64 format
fo = open(filename, "rb")
filecontent = fo.read()
encodedcontent = base64.b64encode(filecontent) # base64
sender = 'webmaster@tutorialpoint.com'
reciever = 'amrood.admin@gmail.com'
marker = "AUNIQUEMARKER"
body ="""
This is a test email to send an attachment.
"""
# Define the main headers.
part1 = """From: From Person <me@fromdomain.net>
To: To Person <amrood.admin@gmail.com>
Subject: Sending Attachment
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (marker, marker)
# Define the message action
part2 = """Content-Type: text/plain
Content-Transfer-Encoding:8bit
%s
--%s
""" % (body,marker)
# Define the attachment section
part3 = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename=%s
%s
--%s--
""" %(filename, filename, encodedcontent, marker)
message = part1 + part2 + part3
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, reciever, message)
print "Successfully sent email"
except Exception:
print "Error: unable to send email"
使用 Gmail 的 SMTP 服务器发送电子邮件
要用 Gmail 的 Python SMTP 服务器发送邮件,你需要在 "587" 端口 smtp.gmail.com 设置连接,使用"TLS"加密,使用 Gmail 凭证进行认证,使用 Python 的 smtplib 和 email.mime 库构建邮件,然后使用 sendmail() 方法发送。最后,用 quit() 关闭 SMTP 连接。
示例
以下是一个示例脚本,演示如何使用Gmail的SMTP服务器发送电子邮件 −
python
import smtplib
# Email content
content = "Hello World"
# Set up SMTP connection to Gmail's SMTP server
mail = smtplib.SMTP('smtp.gmail.com', 587)
# Identify yourself to the SMTP server
mail.ehlo()
# Start TLS encryption for the connection
mail.starttls()
# Gmail account credentials
sender = 'your_email@gmail.com'
password = 'your_password'
# Login to Gmail's SMTP server
mail.login(sender, password)
# Email details
recipient = 'recipient_email@example.com'
subject = 'Test Email'
# Construct email message with headers
header = f'To: {recipient}\nFrom: {sender}\nSubject: {subject}\n'
content = header + content
# Send email
mail.sendmail(sender, recipient, content)
# Close SMTP connection
mail.quit()
在运行上述脚本之前,发件人的 Gmail 账户必须配置为允许访问"更少" 安全应用。点击以下链接。
https://myaccount.google.com/lesssecureapps将显示的切换按钮设置为开启。

如果一切顺利,执行上述脚本。消息应被送达到收件人的收件箱。