Python中使用MIMEMultipart()发送带有压缩文件夹的邮件
发布时间:2023-12-25 18:35:17
在Python中,可以使用MIMEMultipart()发送带有压缩文件夹的邮件。MIMEMultipart()是MIME(Multipurpose Internet Mail Extensions)协议的一部分,用于在邮件中添加多个部分。
以下是一个使用MIMEMultipart()发送包含压缩文件夹的邮件的示例代码:
import os
import smtplib
import zipfile
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
def send_compressed_folder_email(sender_email, sender_password, receiver_email, folder_path):
# 创建MIMEMultipart对象
msg = MIMEMultipart()
# 设置邮件发送者、接收者和主题
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = 'Compressed Folder Email'
# 创建压缩文件
zip_path = 'compressed_folder.zip'
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
for root, dirs, files in os.walk(folder_path):
for file in files:
zipf.write(os.path.join(root, file))
# 添加压缩文件到邮件
with open(zip_path, 'rb') as zip_file:
attachment = MIMEBase('application', 'zip')
attachment.set_payload(zip_file.read())
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', f'attachment; filename={zip_path}')
msg.attach(attachment)
# 发送邮件
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender_email, sender_password)
server.sendmail(sender_email, receiver_email, msg.as_string())
server.quit()
# 删除临时创建的压缩文件
os.remove(zip_path)
# 使用示例
sender_email = 'your_email@gmail.com'
sender_password = 'your_password'
receiver_email = 'recipient_email@example.com'
folder_path = '/path/to/folder'
send_compressed_folder_email(sender_email, sender_password, receiver_email, folder_path)
在上面的代码中,我们首先创建了一个MIMEMultipart()对象,并设置了邮件的发送者、接收者和主题。然后,我们创建一个压缩文件夹,将文件夹中的所有文件添加到压缩文件中。接下来,我们将压缩文件作为附件添加到邮件中,并使用SMTP服务器发送邮件。最后,我们删除临时创建的压缩文件。
请注意,你需要替换示例代码中的以下变量:
- sender_email:发送者的电子邮件地址
- sender_password:发送者的电子邮件密码
- receiver_email:接收者的电子邮件地址
- folder_path:要压缩的文件夹的路径
还应该确保你的Python环境中已安装相关的库,例如smtplib和email。
希望以上示例可以帮助你在Python中使用MIMEMultipart()发送带有压缩文件夹的邮件。
