From 224d45643a558c70e95f936195218761da562839 Mon Sep 17 00:00:00 2001 From: Martin Abente Date: Thu, 31 Mar 2011 14:49:25 +0000 Subject: Mailer send zipped logs --- diff --git a/reports_mailer.py b/reports_mailer.py index 55c443a..efac0de 100755 --- a/reports_mailer.py +++ b/reports_mailer.py @@ -21,7 +21,11 @@ import json import time import smtplib import logging +import zipfile +import tempfile +from email import encoders from email.mime.text import MIMEText +from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from ConfigParser import ConfigParser @@ -67,10 +71,28 @@ def send_email(message): mail_server.starttls() mail_server.ehlo() mail_server.login(SMTP_USER, SMTP_PASSWORD) - mail_server.sendmail(REPORTER_ADDRESS, [LIST_ADDRESS], message.as_string()) + mail_server.sendmail(REPORTER_ADDRESS, [LIST_ADDRESS], message) mail_server.quit() -def prepare_message(subject, body, report_path): +def compress_directory(report_path, report_name): + temp_file = tempfile.TemporaryFile() + zip_file = zipfile.ZipFile(temp_file, 'w') + + for log_file in os.listdir(report_path): + log_path = os.path.join(report_path, log_file) + + if not os.path.isfile(log_path): + continue + + zip_log_path = os.path.join(report_name, log_file) + zip_file.write(log_path, zip_log_path) + + zip_file.close() + temp_file.seek(0) + return temp_file.read() + + +def prepare_message(subject, body, report_path, report_name): message = MIMEMultipart() message['Subject'] = subject message['From'] = REPORTER_ADDRESS @@ -80,23 +102,16 @@ def prepare_message(subject, body, report_path): body_attachment = MIMEText(body.encode('utf-8'), 'plain', 'utf-8') message.attach(body_attachment) - for log_path in os.listdir(report_path): - abs_log_path = os.path.join(report_path, log_path) - - if not os.path.isfile(abs_log_path): - continue - - log_file = open(abs_log_path, 'r') - payload = log_file.read().encode('utf-8') - attachment = MIMEText(payload, 'plain', 'utf-8') - log_file.close() + attachment_content = compress_directory(report_path, report_name) - attachment.add_header('Content-Disposition', - 'attachment', - filename=log_path) - message.attach(attachment) + attachment = MIMEBase('application', 'zip') + attachment.set_payload(attachment_content) + encoders.encode_base64(attachment) + attachment.add_header('Content-Disposition', 'attachment', + filename=report_name + '.zip') - return message + message.attach(attachment) + return message.as_string() def generate_body(info, report_info_path, report_name): report_time = time.ctime(os.path.getctime(report_info_path)) @@ -159,7 +174,7 @@ def check_reports(): body = generate_body(report_info, report_info_path, report) subject = generate_subject(report_info) - message = prepare_message(subject, body, report_path) + message = prepare_message(subject, body, report_path, report) try: send_email(message) -- cgit v0.9.1