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

Python邮件模块中的email.mime.multipartMIMEMultipart()使用指南

发布时间:2023-12-26 08:29:39

email模块是Python中用于处理邮件的标准库。其中的email.mime.multipart模块可以用于创建和处理多部分邮件,即可以包含文本、附件、HTML等多种内容的邮件。

MIMEMultipart()函数是email.mime.multipart模块中的一个类,用于创建一个多部分邮件对象。

使用MIMEMultipart()函数创建多部分邮件对象的基本步骤如下:

1. 导入相关模块

from email.mime.multipart import MIMEMultipart

2. 创建MIMEMultipart对象

msg = MIMEMultipart()

3. 设置邮件头部信息

msg['From'] = 'sender@example.com'
msg['To'] = 'receiver@example.com'
msg['Subject'] = 'This is a multipart email'

4. 设置邮件正文内容

msg.attach(MIMEText('This is the text part of the email', 'plain'))

5. 设置邮件附件

attach_file = open('attachment.txt', 'rb')
attachment = MIMEBase('application', 'octet-stream')
attachment.set_payload((attach_file).read())
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', 'attachment; filename=attachment.txt')
msg.attach(attachment)

6. 发送邮件

smtpObj = smtplib.SMTP('smtp.example.com', 587)
smtpObj.send_message(msg)
smtpObj.quit()

使用MIMEMultipart()函数的例子如下:

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

# 创建一个MIMEMultipart对象
msg = MIMEMultipart()

# 设置邮件头部信息
msg['From'] = 'sender@example.com'
msg['To'] = 'receiver@example.com'
msg['Subject'] = 'This is a multipart email'

# 设置邮件正文内容
msg.attach(MIMEText('This is the text part of the email', 'plain'))

# 设置邮件附件
attach_file = open('attachment.txt', 'rb')
attachment = MIMEBase('application', 'octet-stream')
attachment.set_payload((attach_file).read())
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', 'attachment; filename=attachment.txt')
msg.attach(attachment)

# 发送邮件
smtpObj = smtplib.SMTP('smtp.example.com', 587)
smtpObj.send_message(msg)
smtpObj.quit()

以上示例中,我们通过MIMEMultipart()函数创建了一个多部分邮件对象msg。然后设置了邮件头部信息、邮件正文内容和邮件附件。最后调用SMTP类发送邮件。

总结:

MIMEMultipart()函数是email模块中的一个类,用于创建多部分邮件对象。通过设置邮件头部信息、邮件正文内容和邮件附件,可以创建一个包含多种内容的邮件。最后,使用SMTP类的方法发送邮件。