comparison gpp/mailer/__init__.py @ 180:aef00df91165

Implement #63, add a queued email facility.
author Brian Neal <bgneal@gmail.com>
date Sun, 21 Mar 2010 20:33:33 +0000
parents
children 767cedc7d12a
comparison
equal deleted inserted replaced
179:70b2e307c866 180:aef00df91165
1 from socket import error as socket_error
2 import smtplib
3 import time
4
5 import django.core.mail
6
7 import mailer.models
8
9
10 def enqueue_mail(subject, message, from_email, recipient_list):
11 """Creates mailer mail queue entries for the given email."""
12
13 if len(subject) > mailer.models.MAX_SUBJECT:
14 subject = u'%s...' % subject[:mailer.models.MAX_SUBJECT - 3]
15
16 for recipient in recipient_list:
17 mailer.models.Message(
18 from_address=from_email,
19 to_address=recipient,
20 subject=subject,
21 body=message).save()
22
23
24 def send_queued_mail():
25 """Reads the queued messages from the database, sends them, and removes them
26 from the queue."""
27
28 sent, errors = 0, 0
29
30 import logging
31 logging.debug("Sending queued mail...")
32 start_time = time.time()
33
34 msgs = mailer.models.Message.objects.all()
35 for msg in msgs:
36 try:
37 django.core.mail.send_mail(
38 msg.subject,
39 msg.body,
40 msg.from_address,
41 [msg.to_address],
42 fail_silently=False)
43 except (socket_error, smtplib.SMTPException), e:
44 errors += 1
45 logging.error("Error sending queued mail: %s" % e)
46 else:
47 sent += 1
48 msg.delete()
49
50 end_time = time.time()
51 logging.debug("Sent queued mail: %d successful, %d error(s); elapsed time: %.2f" % (
52 sent, errors, end_time - start_time))