python压缩文件夹然后在发送邮件_python实现定时压缩指定文件夹发送邮件
时间: 2023-08-11 10:17:37 浏览: 178
python实现定时压缩指定文件夹发送邮件
要实现定时压缩指定文件夹并发送邮件,可以使用Python的zipfile和smtplib库。
以下是一个示例代码:
```python
import zipfile
import smtplib
import os
import time
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE
from email import encoders
# 定义要压缩的文件夹路径和邮件相关参数
folder_to_compress = '/path/to/folder'
zip_filename = 'compressed.zip'
email_subject = 'Compressed Folder'
email_body = 'Please find the compressed folder attached.'
smtp_server = 'smtp.example.com'
smtp_port = 587
smtp_username = 'example@example.com'
smtp_password = 'password'
sender = 'example@example.com'
recipient = 'recipient@example.com'
send_time = '08:00'
# 压缩文件夹
def zip_folder(folder_path, output_path):
with zipfile.ZipFile(output_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))
# 发送邮件
def send_email(subject, body, attachment_path, smtp_server, smtp_port, smtp_username, smtp_password, sender, recipient):
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = recipient
msg['Subject'] = subject
msg.attach(MIMEText(body))
with open(attachment_path, 'rb') as f:
part = MIMEBase('application', 'octet-stream')
part.set_payload(f.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachment_path))
msg.attach(part)
smtp = smtplib.SMTP(smtp_server, smtp_port)
smtp.starttls()
smtp.login(smtp_username, smtp_password)
smtp.sendmail(sender, recipient, msg.as_string())
smtp.quit()
# 定时发送邮件
while True:
current_time = time.strftime('%H:%M')
if current_time == send_time:
zip_folder(folder_to_compress, zip_filename)
send_email(email_subject, email_body, zip_filename, smtp_server, smtp_port, smtp_username, smtp_password, sender, recipient)
os.remove(zip_filename)
time.sleep(60)
```
该代码会每分钟检查一次当前时间,如果与设定的发送时间一致,就压缩指定文件夹并发送邮件。注意,这个代码运行时会一直循环,需要手动关闭。
请注意,这只是一个示例代码,需要根据实际情况进行调整。
阅读全文