Bri*_*ach 5 python zip email-attachments
我正在将一些 csv 压缩成一个 zip 文件,以便从我的 Web 应用程序中通过电子邮件发送出去。
celery运行此任务并负责发送电子邮件。结构描述如下
import zipfile
...
def email_performance_report(performance_dict)
zippath = performance_dict['folderpath'] + '.zip'
ziph = zipfile.ZipFile(zippath, 'w')
for root, dirs, files in os.walk(performance_dict['folderpath']):
for file in files:
filename = os.path.join(root, file)
archivename = os.path.dirname(filename).split('/')[-1]
filename_short = filename.split('/')[-1]
ziph.write(filename, os.path.join(archivename, filename_short))
ziph.close()
''' attach attachment '''
with open(zippath, 'rb') as f:
attachment = MIMEText(f.read())
clean_attachment_name = zippath.split('/')[-1].split('|__|')[0] + '.zip'
attachment.add_header('Content-Disposition', 'attachment', filename=clean_attachment_name)
msg.attach(attachment)
try:
mailserver.sendmail(os.environ['MAIL_SENDER'], performance_dict['email_to'], msg.as_string())
except smtplib.SMTPDataError:
sqllogger.critical('A emailing of the report failed due to zippy zip issues') # intermittent gmail issue with zip files
return False
os.remove(zippath)
shutil.rmtree(performance_dict['folderpath'])
return
@celery.task(base=SqlAlchemyTask, name='tasks.daily_performance_report')
def generate_daily_performance_report(pd):
... build performance dictionary ...
email_daily_performance_report(performance_dict)
Run Code Online (Sandbox Code Playgroud)
clean_attachment_name是删除了 uuid 的文件路径。uuid 这样,如果多个用户同时尝试生成报告,他们就不会互相干扰。
我的用户报告空的 zip 文件。zip 文件夹的大小是正确的,如果他们将电子邮件转发给我,我可以在 Ubuntu (Linux Mint) 上很好地打开 zip 文件。所有 csv 文件都存在。
我在这里遗漏了跨平台问题吗?
| 归档时间: |
|
| 查看次数: |
273 次 |
| 最近记录: |