Python 详细讲解用 Python 发送 SMTP 邮件的教程
简介
简单邮件传输协议(Simple Mail Transfer Protocol,SMTP)是一种用于发送电子邮件的协议。Python 提供了 smtplib 模块,允许您使用 SMTP 服务器发送邮件。本教程将详细讲解如何使用 Python 发送 SMTP 邮件。
安装 smtplib 模块
smtplib 模块是 Python 内置的模块,无需额外安装。可以直接在代码中导入使用。
import smtplib
连接到 SMTP 服务器
在开始发送邮件之前,需要先连接到 SMTP 服务器。您可以使用 smtplib.SMTP()
函数进行连接,并指定 SMTP 服务器的主机名和端口号。
smtp_server = 'smtp.example.com'
smtp_port = 587
server = smtplib.SMTP(smtp_server, smtp_port)
登录到 SMTP 服务器
大多数 SMTP 服务器需要进行身份验证,因此在发送邮件之前需要先登录到 SMTP 服务器。可以使用 server.login()
函数进行登录,需要提供登录所需的用户名和密码。
username = 'your_username'
password = 'your_password'
server.login(username, password)
构造邮件内容
在发送邮件之前,需要构造好邮件的内容。可以使用 Python 的 email 模块来创建邮件对象。
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# 创建邮件对象
msg = MIMEMultipart()
# 设置邮件标题
msg['Subject'] = 'Python SMTP 邮件测试'
# 设置发件人
msg['From'] = 'sender@example.com'
# 设置收件人
msg['To'] = 'recipient@example.com'
# 设置邮件正文
body = MIMEText('这是一封由 Python 发送的测试邮件。')
msg.attach(body)
# 添加附件
attachment_file = 'path/to/attachment.txt'
attachment = MIMEText(open(attachment_file, "rb").read(), _subtype='plain', _charset='utf-8')
attachment["Content-Disposition"] = 'attachment; filename="%s"' % attachment_file
msg.attach(attachment)
发送邮件
构造好邮件对象后,可以使用 server.sendmail()
函数进行发送。
sender = 'sender@example.com'
recipients = ['recipient@example.com']
# 发送邮件
server.sendmail(sender, recipients, msg.as_string())
添加异常处理
在使用 smtplib 模块发送邮件过程中,可能会出现各种异常情况,例如连接失败、登录失败等。为了保证程序的稳定性,可以添加异常处理机制。
try:
# 连接到 SMTP 服务器
server = smtplib.SMTP(smtp_server, smtp_port)
# 登录到 SMTP 服务器
server.login(username, password)
# 发送邮件
server.sendmail(sender, recipients, msg.as_string())
print('邮件发送成功')
except Exception as e:
print('邮件发送失败:', e)
finally:
# 关闭连接
server.quit()
完整代码示例
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMETe
smtp_server = 'smtp.example.com'
smtp_port = 587
username = 'your_username'
password = 'your_password'
sender = 'sender@example.com'
recipients = ['recipient@example.com']
attachment_file = 'path/to/attachment.txt'
try:
# 连接到 SMTP 服务器
server = smtplib.SMTP(smtp_server, smtp_port)
# 登录到 SMTP 服务器
server.login(username, password)
# 创建邮件对象
msg = MIMEMultipart()
# 设置邮件标题
msg['Subject'] = 'Python SMTP 邮件测试'
# 设置发件人
msg['From'] = sender
# 设置收件人
msg['To'] = ", ".join(recipients)
# 设置邮件正文
body = MIMEText('这是一封由 Python 发送的测试邮件。')
msg.attach(body)
# 添加附件
attachment = MIMEText(open(attachment_file, "rb").read(), _subtype='plain', _charset='utf-8')
attachment["Content-Disposition"] = 'attachment; filename="%s"' % attachment_file
msg.attach(attachment)
# 发送邮件
server.sendmail(sender, recipients, msg.as_string())
print('邮件发送成功')
except Exception as e:
print('邮件发送失败:', e)
finally:
# 关闭连接
server.quit()
运行结果
请确保配置正确的 SMTP 服务器信息、用户名和密码,并确保附件文件路径正确,然后运行以上代码。在控制台中,你会看到类似以下的输出:
邮件发送成功
总结
本教程详细讲解了如何使用 Python 发送 SMTP 邮件。通过 smtplib 模块和 email 模块,我们可以轻松地构造和发送邮件。