summaryrefslogtreecommitdiff
path: root/app
diff options
context:
space:
mode:
Diffstat (limited to 'app')
-rw-r--r--app/backend/mail_queue.py78
1 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()