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

Python中email.mime.multipart模块简介及使用方法详解

发布时间:2023-12-26 08:30:45

email.mime.multipart模块是Python中用于创建包含多个部分的MIME消息的模块。MIME(Multipurpose Internet Mail Extensions)是一种用于在电子邮件中传输不同类型数据的标准。

使用email.mime.multipart模块可以创建包含文本、HTML、附件等多个部分的邮件消息,并将它们合并成一个MIME消息。下面是使用email.mime.multipart模块的详细使用方法:

1. 导入模块

from email.mime.multipart import MIMEMultipart

2. 创建MIMEMultipart对象

msg = MIMEMultipart()

3. 添加文本、HTML、附件等部分

可以使用MIMEMultipart对象的attach()方法来添加文本、HTML或附件等部分。attach()方法接受一个MIMEText、MIMEImage、MIMEAudio、MIMEBase等对象作为参数。

from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase

# 添加文本部分
text_part = MIMEText("This is a test email.")
msg.attach(text_part)

# 添加HTML部分
html_part = MIMEText("<html><body><h1>This is a test email.</h1></body></html>", "html")
msg.attach(html_part)

# 添加附件
with open("attachment.txt", "rb") as attachment:
    attach_part = MIMEBase("application", "octet-stream")
    attach_part.set_payload(attachment.read())
    attachment.close()
    attach_part.add_header("Content-Disposition", 'attachment', filename="attachment.txt")
    msg.attach(attach_part)

4. 设置邮件头部信息

可以使用MIMEMultipart对象的add_header()方法来设置邮件头部信息,例如发件人、收件人、主题等。

msg.add_header("From", "sender@example.com")
msg.add_header("To", "recipient@example.com")
msg.add_header("Subject", "Test email")

5. 序列化MIMEMultipart对象

将MIMEMultipart对象序列化为字符串,可以使用as_string()方法。

email_str = msg.as_string()

下面是一个完整的使用email.mime.multipart模块的例子:

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase

# 创建MIMEMultipart对象
msg = MIMEMultipart()

# 添加文本部分
text_part = MIMEText("This is a test email.")
msg.attach(text_part)

# 添加附件
with open("attachment.txt", "rb") as attachment:
    attach_part = MIMEBase("application", "octet-stream")
    attach_part.set_payload(attachment.read())
    attachment.close()
    attach_part.add_header("Content-Disposition", 'attachment', filename="attachment.txt")
    msg.attach(attach_part)

# 设置邮件头部信息
msg.add_header("From", "sender@example.com")
msg.add_header("To", "recipient@example.com")
msg.add_header("Subject", "Test email")

# 序列化MIMEMultipart对象
email_str = msg.as_string()

print(email_str)

以上就是使用email.mime.multipart模块创建并操作MIME消息的方法和一个完整的例子。可以根据需要添加不同类型的部分到邮件消息中,并设置相应的邮件头部信息。最后将MIME消息序列化为字符串,可以用于发送邮件或保存为文件。