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

如何在Python中使用MIMEMultipart()创建多个附件的邮件

发布时间:2023-12-25 18:30:56

在Python中,我们可以使用MIMEMultipart()创建带有多个附件的邮件。MIMEMultipart()email.mime.multipart模块中的一个类,它允许我们创建包含多个部分(包括文本、HTML、附件等)的邮件。

下面是一个使用MIMEMultipart()创建多个附件的邮件的例子:

首先,我们需要导入相关模块和类:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication

然后,我们可以定义邮件的发送者、接收者、主题和内容:

sender = 'youremail@gmail.com'
receiver = 'recipientemail@gmail.com'
subject = 'Email with Multiple Attachments'

# 创建MIMEMultipart对象
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = subject

接下来,我们可以创建邮件的正文部分并将其附加到MIMEMultipart对象中:

# 邮件正文
body = 'This is the body of the email.'
msg.attach(MIMEText(body, 'plain'))

然后,我们可以创建附件并将其附加到MIMEMultipart对象中:

#       个附件
attachment1 = MIMEApplication(open('file1.txt', 'rb').read())
attachment1.add_header('Content-Disposition', 'attachment', filename='file1.txt')
msg.attach(attachment1)

# 第二个附件
attachment2 = MIMEApplication(open('file2.png', 'rb').read())
attachment2.add_header('Content-Disposition', 'attachment', filename='file2.png')
msg.attach(attachment2)

在上面的示例中,我们使用了MIMEApplication()来创建附件,然后使用add_header()方法为附件添加内容描述。最后,我们将附件添加到MIMEMultipart对象中。

最后,我们可以使用smtp模块将带有多个附件的邮件发送出去:

# 邮件服务器设置
smtp_server = 'smtp.gmail.com'
smtp_port = 587
username = 'youremail@gmail.com'
password = 'yourpassword'

# 创建SMTP对象
smtp_obj = smtplib.SMTP(smtp_server, smtp_port)

# 开启TLS连接
smtp_obj.starttls()

# 登录SMTP服务器
smtp_obj.login(username, password)

# 发送邮件
smtp_obj.sendmail(sender, receiver, msg.as_string())

# 退出SMTP服务器
smtp_obj.quit()

在上面的示例中,我们将邮件服务器设置为Gmail,并创建了SMTP对象。然后,我们使用starttls()方法开启TLS连接,并使用login()方法登录SMTP服务器。最后,使用sendmail()方法发送邮件并使用quit()方法退出SMTP服务器。

通过上面的例子,我们可以使用MIMEMultipart()类在Python中创建带有多个附件的邮件。希望这个例子能够帮助到你。