使用Python和email.message模块发送带有回执请求的电子邮件
发布时间:2023-12-27 17:11:21
发送带有回执请求的电子邮件是通过设置邮件的 Disposition-Notification-To 头来实现的。Disposition-Notification-To 头告诉邮件服务器在邮件被读取或删除时向指定的邮箱发送回执。在 Python 中,我们可以使用 email.message 模块来创建和发送电子邮件。
首先,我们需要导入以下模块:
import smtplib from email.message import EmailMessage
接下来,我们创建一个 EmailMessage 对象来存储邮件的内容和设置。
msg = EmailMessage()
然后,我们需要设置邮件的一些基本属性,例如发送者、收件人、主题和正文。
msg['From'] = 'sender@example.com'
msg['To'] = 'receiver@example.com'
msg['Subject'] = 'Testing email with receipt request'
msg.set_content('This is the body of the email.')
为了请求回执,我们需要设置 Disposition-Notification-To 头。
msg['Disposition-Notification-To'] = 'receipt@example.com'
然后,我们需要创建一个 SMTP 连接来发送邮件。
smtp_server = 'smtp.example.com'
smtp_port = 587
smtp_username = 'sender@example.com'
smtp_password = 'password'
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.starttls()
server.login(smtp_username, smtp_password)
server.send_message(msg)
这是一个完整的例子,将所有的代码组合在一起:
import smtplib
from email.message import EmailMessage
msg = EmailMessage()
msg['From'] = 'sender@example.com'
msg['To'] = 'receiver@example.com'
msg['Subject'] = 'Testing email with receipt request'
msg.set_content('This is the body of the email.')
msg['Disposition-Notification-To'] = 'receipt@example.com'
smtp_server = 'smtp.example.com'
smtp_port = 587
smtp_username = 'sender@example.com'
smtp_password = 'password'
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.starttls()
server.login(smtp_username, smtp_password)
server.send_message(msg)
上述代码中,我们使用了一个 SMTP 服务器和认证信息来发送邮件。你需要将 smtp_server、smtp_port、smtp_username 和 smtp_password 替换为你自己的 SMTP 服务器和认证信息。
这是一个简单的例子,演示了如何使用 email.message 模块发送带有回执请求的电子邮件。请注意,具体的用法和设置可能因 SMTP 服务器的不同而有所差异,因此你需要根据你使用的 SMTP 服务器的文档进行适当的调整。
