1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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()
|