Ticket #10355: demo_backend_appengine.py

File demo_backend_appengine.py, 2.1 KB (added by Andi Albrecht, 15 years ago)

Demo backend: App Engine

Line 
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
5import logging
6
7from django.core.mail.backends.base import BaseEmailBackend
8from django.core.mail import EmailMultiAlternatives
9from django.core.exceptions import ImproperlyConfigured
10
11try:
12 from google.appengine.api import mail as gaemail
13except ImportError, err:
14 raise ImproperlyConfigured(('Failed to import App Engine libraries: %s'
15 % err))
16
17
18class 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
Back to Top