Python中如何使用email.message模块发送带有自定义标头的电子邮件
发布时间:2023-12-27 17:09:57
在Python中,我们可以使用email.message模块来发送带有自定义标头的电子邮件。 email.message模块是Python标准库中的一部分,提供了创建和处理电子邮件的功能。
以下是一个例子,演示如何使用email.message模块发送带有自定义标头的电子邮件。
首先,我们需要导入email.message模块和其他必要的模块:
import smtplib from email.message import EmailMessage
接下来,我们创建一个EmailMessage对象,用于设置邮件的内容和标头:
msg = EmailMessage()
设置邮件的发件人、收件人和主题:
msg['From'] = 'sender@example.com' msg['To'] = 'receiver@example.com' msg['Subject'] = 'Hello World'
设置自定义标头:
msg.add_header('X-Custom-Header', 'Custom Value')
添加邮件正文:
msg.set_content('This is the body of the email.')
我们还可以添加附件:
msg.add_attachment(open('attachment.pdf', 'rb').read(), maintype='application', subtype='pdf', filename='attachment.pdf')
最后,我们使用SMTP服务器发送邮件:
with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
smtp.starttls()
smtp.login('sender@example.com', 'password')
smtp.send_message(msg)
完整的例子如下:
import smtplib
from email.message import EmailMessage
msg = EmailMessage()
msg['From'] = 'sender@example.com'
msg['To'] = 'receiver@example.com'
msg['Subject'] = 'Hello World'
msg.add_header('X-Custom-Header', 'Custom Value')
msg.set_content('This is the body of the email.')
with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
smtp.starttls()
smtp.login('sender@example.com', 'password')
smtp.send_message(msg)
请注意,上述示例中使用了Gmail的SMTP服务器,你需要将smtp.gmail.com更改为你自己的SMTP服务器地址,并使用正确的邮箱地址和密码进行身份验证。
这就是使用email.message模块发送带有自定义标头的电子邮件的例子。你可以根据自己的需求添加更多标头、正文和附件。
