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

使用Python的email.mime.multipart库发送带有压缩文件附件的邮件

发布时间:2023-12-14 11:52:26

使用Python的email.mime.multipart库可以方便地发送带有压缩文件附件的邮件。下面是一个使用例子,用于发送一个包含压缩文件附件的邮件。

首先,导入相应的库和模块。

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

接下来,设置发送方和接收方的邮件地址。

sender = 'sender@example.com'
receiver = 'receiver@example.com'

创建一个MIMEMultipart对象,并设置邮件主题和发送方、接收方信息。

msg = MIMEMultipart()
msg['Subject'] = 'Email with Compressed File Attachment'
msg['From'] = sender
msg['To'] = receiver

添加邮件正文的文本内容。

text = 'This email contains a compressed file attachment.'
msg.attach(MIMEText(text))

创建一个MIMEApplication对象来表示压缩文件,并添加到邮件附件中。

attachment = MIMEApplication(open('compressed_file.zip', 'rb').read())
attachment.add_header('Content-Disposition', 'attachment', filename='compressed_file.zip')
msg.attach(attachment)

连接到SMTP服务器,并发送邮件。

smtp_server = 'smtp.example.com'
smtp_port = 587
smtp_username = 'smtp_username'
smtp_password = 'smtp_password'

server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(smtp_username, smtp_password)
server.sendmail(sender, receiver, msg.as_string())
server.quit()

在代码中,我们使用了SMTP服务器的地址和端口号,以及发送方的用户名和密码来进行身份验证。请注意,这是一个示例代码,请根据实际情况进行相应的更改。

以上就是使用Python的email.mime.multipart库发送带有压缩文件附件的邮件的一个示例。你可以根据自己的需求,修改邮件主题、正文以及附件的文件名和路径来发送不同的邮件。