summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authoremkael <emkael@tlen.pl>2017-03-15 12:57:43 +0100
committeremkael <emkael@tlen.pl>2017-03-15 12:57:43 +0100
commitd2331ea5df339a69703df7506eb9359eb6ce3328 (patch)
treeb5a1d544bae24981b6c4bbc88ebf9e8dc8e778d0
parentffa472d81caecae933000d58033de7b0a99cdb5a (diff)
* mail queue processor
-rw-r--r--app/backend/mail_queue.py78
-rw-r--r--config/mailer.jsonbin316 -> 379 bytes
2 files changed, 78 insertions, 0 deletions
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()
diff --git a/config/mailer.json b/config/mailer.json
index 5de7be2..5c2b5aa 100644
--- a/config/mailer.json
+++ b/config/mailer.json
Binary files differ