Send transactional emails from your Django project using Cocoonmail’ SMTP service.

As Cocoonmail’ SMTP service requires sending an API-like email body rather than a full email, it’s not recommended to use Cocoonmail as the default SMTP service for your app in your settings file. Instead, use a custom connection for each email request that you want to send through Cocoonmail.

Sending email from Django with Cocoonmail’ SMTP service is easy but there’s one gotcha: the email body needs to be an API-like payload.

This may seem strange at first but it allows you to use Cocoonmail’ WYSIWYG editor to craft your emails and keep email templating outside of your code repo.

We are using a custom connection for sending this email as typically only some emails in a project will be sent through Cocoonmail.

The connection’s password value should be an API key from your API Settings page.

Every email sent from Django over Cocoonmail SMTP requires a transactional email to be set up in your Cocoonmail account. Note the transactionalId value in the email payload.
from django.conf import settings

from django.core.mail import send_mail, get_connection

import json



with get_connection(

    host=settings.COCOONMAIL_SMTP_HOST, 

    port=settings.COCOONMAIL_SMTP_PORT, 

    username=settings.COCOONMAIL_SMTP_HOST_USER, 

    password=settings.COCOONMAIL_SMTP_HOST_PASSWORD, # API key from your Cocoonmail Settings

    use_tls=True # Has to be True

) as connection:



    email = 'dan@cocoonmail.com'



    # This payload can be copied from a transactional email's 

    #  Publish page in Cocoonmail

    payload = {

        "transactionalId": "closfz8ui02yqk10npt9gnw5a",

        "email": email,

        "dataVariables": {

            "buttonUrl": "https://myapp.com/login/",

            "userName": "Bob"

        }

    }



    send_mail(

        "Subject here", # Overwritten by Cocoonmail template

        json.dumps(payload), # Stringify the payload

        "from@example.com", # Overwritten by Cocoonmail template

        [email],

        fail_silently=False,

        connection=connection

    )