diff options
author | Magnus Hagander | 2013-04-19 13:56:49 +0000 |
---|---|---|
committer | Magnus Hagander | 2013-04-19 13:58:38 +0000 |
commit | ac331360a13f5b87ecc56e7cba4a708d86579ea6 (patch) | |
tree | 30fb03faa7b49191c0690e6d76e1bdd517cd884d /postgresqleu/mailqueue/util.py | |
parent | a01fbc87b9f1d010bfee8f370fa64ba66d92e80d (diff) |
Add a simple mail queue in the database
Adds a function to call that will render a complete MIME message, and
write the resulting text to a database table.
Then there is a cron job that runs at regular intervals (every 5 mins or so)
and sends all the queued emails.
This brings in two important functions:
* The ability to "send" emails from regular web views without the risk of ending
up blocking on the SMTP server.
* The abilitty to "transactionally send email" - meaning that mail sen this way
will just disappear if the transaction (normally managed by django) that's open
when it was sent ends up rolling back. This prevents re-sending email over and
over again when some later step in the process fails.
Diffstat (limited to 'postgresqleu/mailqueue/util.py')
-rw-r--r-- | postgresqleu/mailqueue/util.py | 30 |
1 files changed, 30 insertions, 0 deletions
diff --git a/postgresqleu/mailqueue/util.py b/postgresqleu/mailqueue/util.py new file mode 100644 index 00000000..038a2058 --- /dev/null +++ b/postgresqleu/mailqueue/util.py @@ -0,0 +1,30 @@ +from email.mime.text import MIMEText +from email.mime.multipart import MIMEMultipart +from email.mime.nonmultipart import MIMENonMultipart +from email.Utils import formatdate + +from models import QueuedMail + +def send_simple_mail(sender, receiver, subject, msgtxt, attachments=None): + # attachment format, each is a tuple of (name, mimetype,contents) + # content should already be base64 encoded + msg = MIMEMultipart() + msg['Subject'] = subject + msg['To'] = receiver + msg['From'] = sender + msg['Date'] = formatdate(localtime=True) + + msg.attach(MIMEText(msgtxt, _charset='utf-8')) + + if attachments: + for filename, contenttype, content in attachments: + main,sub = contenttype.split('/') + part = MIMENonMultipart(main,sub) + part.set_payload(content) + part.add_header('Content-Transfer-Encoding', 'base64') + part.add_header('Content-Disposition', 'attachment; filename="%s"' % filename) + msg.attach(part) + + + # Just write it to the queue, so it will be transactionally rolled back + QueuedMail(sender=sender, receiver=receiver, fullmsg=msg.as_string()).save() |