1 | # Example email backend implementation for App Engine.
|
---|
2 | # Most of this code is taken from here:
|
---|
3 | # http://code.google.com/p/google-app-engine-django/source/browse/trunk/appengine_django/mail.py
|
---|
4 |
|
---|
5 | import logging
|
---|
6 |
|
---|
7 | from django.core.mail.backends.base import BaseEmailBackend
|
---|
8 | from django.core.mail import EmailMultiAlternatives
|
---|
9 | from django.core.exceptions import ImproperlyConfigured
|
---|
10 |
|
---|
11 | try:
|
---|
12 | from google.appengine.api import mail as gaemail
|
---|
13 | except ImportError, err:
|
---|
14 | raise ImproperlyConfigured(('Failed to import App Engine libraries: %s'
|
---|
15 | % err))
|
---|
16 |
|
---|
17 |
|
---|
18 | class AppEngineEmailBackend(BaseEmailBackend):
|
---|
19 |
|
---|
20 | def send_messages(self, email_messages):
|
---|
21 | num_sent = 0
|
---|
22 | for message in email_messages:
|
---|
23 | if self._send(message):
|
---|
24 | num_sent += 1
|
---|
25 | return num_sent
|
---|
26 |
|
---|
27 | def _copy_message(self, message):
|
---|
28 | """Create and return App Engine EmailMessage class from message."""
|
---|
29 | gmsg = gaemail.EmailMessage(sender=message.from_email,
|
---|
30 | to=message.to,
|
---|
31 | subject=message.subject,
|
---|
32 | body=message.body)
|
---|
33 | if message.extra_headers.get('Reply-To', None):
|
---|
34 | gmsg.reply_to = message.extra_headers['Reply-To']
|
---|
35 | if message.bcc:
|
---|
36 | gmsg.bcc = list(message.bcc)
|
---|
37 | if message.attachments:
|
---|
38 | gmsg.attachments = [(a[0], a[1]) for a in message.attachments]
|
---|
39 | if isinstance(message, EmailMultiAlternatives): # look for HTML
|
---|
40 | for content, mimetype in message.alternatives:
|
---|
41 | if mimetype == 'text/html':
|
---|
42 | gmsg.html = content
|
---|
43 | break
|
---|
44 | return gmsg
|
---|
45 |
|
---|
46 | def _send(self, message):
|
---|
47 | try:
|
---|
48 | msg = self._copy_message(message)
|
---|
49 | except (ValueError, AttributeError, gaemail.Error):
|
---|
50 | # e.g. a empty body raises ValueError
|
---|
51 | if not self.fail_silently:
|
---|
52 | raise
|
---|
53 | return False
|
---|
54 | try:
|
---|
55 | msg.send()
|
---|
56 | except gaemail.Error:
|
---|
57 | if not self.fail_silently:
|
---|
58 | raise
|
---|
59 | return False
|
---|
60 | return True
|
---|