欢迎访问宙启技术站
智能推送

Python中如何使用smtplib发送带有自定义邮件头的电子邮件

发布时间:2024-01-16 04:12:44

在Python中,可以使用smtplib模块来发送邮件。smtplib提供了一个SMTP类,其中有发送邮件的方法和属性。要发送带有自定义邮件头的电子邮件,可以使用Email模块来设置邮件头。

首先,需要导入相应的模块:

import smtplib
from email.mime.text import MIMEText
from email.header import Header

创建一个SMTP对象,并连接到SMTP服务器:

# 连接SMTP服务器
smtp_server = "smtp.example.com"
smtp_port = 587
smtp_username = "your_username"
smtp_password = "your_password"
smtp_conn = smtplib.SMTP(smtp_server, smtp_port)
smtp_conn.ehlo()
smtp_conn.starttls()
smtp_conn.login(smtp_username, smtp_password)

接下来,创建一个MIMEText对象,并设置邮件内容:

# 创建邮件内容
subject = "This is the subject of the email"
body = "This is the body of the email"
mime_text = MIMEText(body, "plain")
mime_text["Subject"] = Header(subject, "utf-8")

设置自定义邮件头:

# 设置自定义邮件头
custom_header = "X-Custom-Header"
custom_value = "Custom Value"
mime_text.add_header(custom_header, custom_value)

设置发件人、收件人和抄送人:

# 设置发件人、收件人和抄送人
from_addr = "from@example.com"
to_addr = "to@example.com"
cc_addr = "cc@example.com"
mime_text["From"] = Header(from_addr, "utf-8")
mime_text["To"] = Header(to_addr, "utf-8")
mime_text["Cc"] = Header(cc_addr, "utf-8")

发送邮件:

# 发送邮件
smtp_conn.sendmail(from_addr, [to_addr, cc_addr], mime_text.as_string())

最后,关闭与SMTP服务器的连接:

# 关闭连接
smtp_conn.quit()

以上就是使用smtplib发送带有自定义邮件头的电子邮件的基本步骤。下面是一个完整的例子:

import smtplib
from email.mime.text import MIMEText
from email.header import Header

# 连接SMTP服务器
smtp_server = "smtp.example.com"
smtp_port = 587
smtp_username = "your_username"
smtp_password = "your_password"
smtp_conn = smtplib.SMTP(smtp_server, smtp_port)
smtp_conn.ehlo()
smtp_conn.starttls()
smtp_conn.login(smtp_username, smtp_password)

# 创建邮件内容
subject = "This is the subject of the email"
body = "This is the body of the email"
mime_text = MIMEText(body, "plain")
mime_text["Subject"] = Header(subject, "utf-8")

# 设置自定义邮件头
custom_header = "X-Custom-Header"
custom_value = "Custom Value"
mime_text.add_header(custom_header, custom_value)

# 设置发件人、收件人和抄送人
from_addr = "from@example.com"
to_addr = "to@example.com"
cc_addr = "cc@example.com"
mime_text["From"] = Header(from_addr, "utf-8")
mime_text["To"] = Header(to_addr, "utf-8")
mime_text["Cc"] = Header(cc_addr, "utf-8")

# 发送邮件
smtp_conn.sendmail(from_addr, [to_addr, cc_addr], mime_text.as_string())

# 关闭连接
smtp_conn.quit()

上述例子中,我们使用MIMEText对象创建了一封纯文本邮件,并设置了自定义邮件头。可以根据需要使用不同的MIME类型,例如在邮件中包含HTML内容或附件。根据实际情况修改SMTP服务器的设置和邮件的内容即可。