/ programming

Sending e-mails from Google App Engine using Mandrill

One of the most popular services for sending emails is Mandrill. They have python client library here but it doesn't work on Google App Engine. It's not Mandrill library issue, they use requests which newest version doesn't work correctly on GAE. You can read about those issues in those two threads:

Here is a simple class which uses urlfetch and deferred to send e-mails through Mandrill.

import json

from google.appengine.api import urlfetch
from google.appengine.ext import deferred

import settings


class MandrillEmail(object):

    @classmethod
    def email(
        cls, email, recipient_name, subject, tags, message_text, message_html
    ):
        message = {
            'from_email': settings.FROM_EMAIL,
            'from_name': settings.FROM_NAME,
            'html': message_html,
            'subject': subject,
            'tags': tags,
            'text': message_text,
            'to': [{
                'email': email,
                'name': recipient_name,
                'type': 'to'
            }],
        }

        deferred.defer(
            cls.send,
            message,
            _queue='emails',
        )

    @classmethod
    def send(cls, message):
        message = {
            'key': settings.MANDRILL_API_KEY,
            'message': message
        }

        urlfetch.fetch(
            url='https://mandrillapp.com/api/1.0/messages/send.json',
            payload=json.dumps(message),
            method=urlfetch.POST,
            headers={
                'Content-Type': 'Content-type: application/json; charset=utf-8'
            }
        )

Example of usage:

MandrillEmail.email(
    '[email protected]',
    None,
    'E-mail title',
    ['registration', ],
    'E-mail as test',
    'E-mail as html'
)