Pythonsmtplib教程展示了如何使用smtplib模块在Python中发送电子邮件。要发送电子邮件,我们使用Python开发服务器、Mailtrap在线服务和共享的虚拟主机邮件服务器。
邮件传输协议
简单邮件传输协议(SMTP)是一种用于电子邮件传输的通信协议。Is是一个Internet标准,于1982年由RFC821首次定义,并于2008年由RFC5321更新为扩展SMTP添加。邮件服务器和其他邮件传输代理使用SMTP发送和接收邮件。
smtplib模块
smtplib是一个使用SimpleMail传输协议(SMTP)发送电子邮件的Python库。smtplib
是内置模块;我们不需要安装它。它抽象掉了SMTP的所有复杂性。
邮件服务器
要真正发送电子邮件,我们需要访问邮件服务器。Python带有一个简单的开发邮件服务器。Mailslurper是一个易于使用的本地开发服务器。共享虚拟主机提供商使我们能够访问邮件服务器。我们可以在帐户中找到详细信息。
注意:避免使用Gmail,因为它是一个高度安全的服务器,而且要使其正常工作非常复杂。事实上,大多数(如果不是全部)Internet上演示如何使用Gmail服务器发送电子邮件的示例都不起作用。相反,请使用开发服务器或共享Web托管服务器。
最后,我们可以使用网络服务。有MailTrap或MailSlurp等开发Web服务,或Mailgun或Mandrill等生产服务。
使用Python内置邮件服务器
$ python -m smtpd -c DebuggingServer -n localhost:1025
我们在端口1025上启动Python内置邮件服务器。
#!/usr/bin/python import smtplib from email.mime.text import MIMEText sender = 'admin@example.com' receivers = ['info@example.com'] port = 1025 msg = MIMEText('This is test mail') msg['Subject'] = 'Test mail' msg['From'] = 'admin@example.com' msg['To'] = 'info@example.com' with smtplib.SMTP('localhost', port) as server: # server.login('username', 'password') server.sendmail(sender, receivers, msg.as_string()) print("Successfully sent email")
我们向本地开发邮件服务器发送一条简单的文本消息。
sender = 'admin@example.com' receivers = ['info@example.com']
我们提供发送者和接收者。example.com
是专门用于文档中说明性示例的域名。
msg = MIMEText('This is test mail') msg['Subject'] = 'Test mail' msg['From'] = 'admin@example.com' msg['To'] = 'info@example.com'
MimeText
用于发送文本电子邮件。我们提供主题、起点和终点选项。
with smtplib.SMTP('localhost', port) as server: ...
SMTP
类管理与SMTP服务器的连接。
# server.login('username', 'password')
因为我们使用本地开发服务器,所以我们不需要登录。
server.sendmail(sender, receivers, msg.as_string())
邮件是用sendmail
发送的。
$ python -m smtpd -c DebuggingServer -n localhost:1025 ---------- MESSAGE FOLLOWS ---------- b'Content-Type: text/plain; charset="us-ascii"' b'MIME-Version: 1.0' b'Content-Transfer-Encoding: 7bit' b'Subject: Test mail' b'From: admin@example.com' b'To: info@example.com' b'X-Peer: ::1' b'' b'This is test mail' ------------ END MESSAGE ------------
我们在发送电子邮件后收到此消息。
发送邮件到Mailtrap
Mailtrap提供免费计划,允许我们每月发送500封邮件。设置Mailtrap非常简单。如果我们有Github或Google帐户,这实际上需要几秒钟。
设置页面中提供了必要的凭据。此外,还有显示如何使用该服务的简短代码示例,包括smtplib
、Django
或Flask
。
#!/usr/bin/python import smtplib from email.mime.text import MIMEText sender = 'admin@example.com' receiver = 'info@example.com' msg = MIMEText('This is test mail') msg['Subject'] = 'Test mail' msg['From'] = 'admin@example.com' msg['To'] = 'info@example.com' user = 'username' password = 'passoword' with smtplib.SMTP("smtp.mailtrap.io", 2525) as server: server.login(user, password) server.sendmail(sender, receiver, msg.as_string()) print("mail successfully sent")
该示例向Mailtrap帐户发送一封简单的邮件。
server.login(user, password)
用户名和密码在设置页面给出;它们由随机字符组成,例如24h328df3e32。
发送带附件的邮件
MIMEMultipart
在我们有附件或想要提供相同内容的替代版本(例如纯文本/HTML版本)时使用。
falcon blue sky cloud
我们有一个简单的文本文件。
#!/usr/bin/python import smtplib from os.path import basename from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication sender = 'admin@example.com' receiver = 'info@example.com' msg = MIMEMultipart() msg['Subject'] = 'Test mail with attachment' msg['From'] = 'admin@example.com' msg['To'] = 'info@example.com' filename = 'words.txt' with open(filename, 'r') as f: part = MIMEApplication(f.read(), Name=basename(filename)) part['Content-Disposition'] = 'attachment; filename="{}"'.format(basename(filename)) msg.attach(part) user = 'username' password = 'password' with smtplib.SMTP("smtp.mailtrap.io", 2525) as server: server.login(user, password) server.sendmail(sender, receiver, msg.as_string()) print("Successfully sent email")
该示例将带有文本文件附件的电子邮件发送到Mailtrap。
filename = 'words.txt' with open(filename, 'r') as f: part = MIMEApplication(f.read(), Name=basename(filename))
我们读取了文本文件的内容。
part['Content-Disposition'] = 'attachment; filename="{}"'.format(basename(filename)) msg.attach(part)
附件是用attach
方法添加的。
带有STARTTLS的邮件陷阱
Mailtrap不支持任何SMTP端口上的SSL,它仅支持STARTTLS。如果我们尝试使用SSL,我们会收到以下错误消息:
ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1045)
所谓的机会型TLS(传输层安全)是纯文本通信协议的扩展。它提供了一种将纯文本连接升级为加密(TLS或SSL)连接的方法,而不是使用单独的端口进行加密通信。为此,一些协议使用名为STARTTLS的命令。它的主要目的是作为被动监控的对策。
#!/usr/bin/python import smtplib from email.mime.text import MIMEText port = 465 sender = 'admin@example.com' receiver = 'info@example.com' msg = MIMEText('Secured test mail') msg['Subject'] = 'Test mail' msg['From'] = 'admin@example.com' msg['To'] = 'info@example.com' user = 'username' password = 'password' with smtplib.SMTP("smtp.mailtrap.io", port) as server: server.starttls() # Secure the connection server.login(user, password) server.sendmail(sender, receiver, msg.as_string()) print("mail successfully sent")
该示例使用机会性TLS向Mailtrap帐户发送电子邮件。
server.starttls() # Secure the connection
starttls
将与SMTP服务器的连接置于TLS模式。
通过SSL发送邮件
以下示例通过SSL发送电子邮件。使用虚拟主机SMTP服务器(来自websupport.sk)。
#!/usr/bin/python import smtplib, ssl from email.mime.text import MIMEText sender = 'admin@example.com' receivers = ['info@example.com'] port = 465 user = 'admin@example.com' password = 'password' msg = MIMEText('This is test mail') msg['Subject'] = 'Test mail' msg['From'] = 'admin@example.com' msg['To'] = 'info@example.com' context = ssl.create_default_context() with smtplib.SMTP_SSL("smtp.websupport.sk", port, context=context) as server: server.login(user, password) server.sendmail(sender, receivers, msg.as_string()) print('mail successfully sent')
SMTP_SSL
通过SSL加密套接字连接。
在本教程中,我们使用了Pythonsmtplib模块来发送电子邮件。
列出所有Python教程。