From d2331ea5df339a69703df7506eb9359eb6ce3328 Mon Sep 17 00:00:00 2001 From: emkael Date: Wed, 15 Mar 2017 12:57:43 +0100 Subject: * mail queue processor --- app/backend/mail_queue.py | 78 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 app/backend/mail_queue.py (limited to 'app') diff --git a/app/backend/mail_queue.py b/app/backend/mail_queue.py new file mode 100644 index 0000000..5ab600a --- /dev/null +++ b/app/backend/mail_queue.py @@ -0,0 +1,78 @@ +import datetime +import json +import os + +import emails +from dateutil.tz import tzutc +from rcal.db import Session +from rcal.model import MailQueue + +BASEPATH = os.path.join( + os.environ['PYTHONPATH'], + '..', + '..') + + +def get_config(section, filename='config/mailer.json'): + config = json.load(open(os.path.join(BASEPATH, filename))) + return config[section] + + +def get_queue(session, queue_config): + return session.query(MailQueue).filter( + MailQueue.is_sent.is_(False), + MailQueue.send_attempts <= queue_config['retry'] + ).order_by( + MailQueue.send_attempts.desc(), + MailQueue.last_attempt_time + ).limit(queue_config['batch']).all() + + +def prepare_message(item, sender): + msg = emails.Message(html=item.html_body, + text=item.text_body.strip(), + subject=item.subject.strip(), + mail_from=(sender['name'], sender['from'])) + if sender['send_copies']: + msg.set_bcc((sender['name'], sender['from'])) + return msg + + +def dump_error(item, retry_limit): + print ('Message #%d to %s reached maximum failed send attepmts (%d), dropping from queue.' + 'Message created: %s' + 'Last error message: %s') % ( + item.id, item.recipient_mail, retry_limit, + item.create_time, + item.last_error_info) + + +def main(): + session = Session.create() + + queue_config = get_config('queue') + sender = get_config('mail') + smtp_conf = get_config('smtp') + + for item in get_queue(session, queue_config): + item.send_attempts += 1 + item.last_attempt_time = datetime.datetime.now(tzutc()) + + msg = prepare_message(item, sender) + msg_response = msg.send(to=(item.recipient_name, item.recipient_mail), + smtp={'host': smtp_conf['host'], + 'port': smtp_conf['port'], + 'ssl': smtp_conf['tls'], + 'user': smtp_conf['user'], + 'password': smtp_conf['pass']}) + if msg_response.status_code in [250, ]: + item.is_sent = True + else: + item.last_error_info = msg_response.status_text + if item.send_attempts >= queue_config['retry']: + dump_error(item, queue_config['retry']) + + session.commit() + +if __name__ == '__main__': + main() -- cgit v1.2.3