How to send emails using the Mailchimp Transactional email API

Learn how to send transactional emails from your Python application using the Mailchimp Transactional email API, formerly known as Mandrill.

How to send emails using the Mailchimp Transactional email API
Picture by Torsten Dettlaff, Pexels.
5 minutes to read

While Mailchimp is best known for its email marketing functionality, it also includes an excellent transactional email API designed to allow developers to send transactional emails from their applications.

Formerly known as Mandrill, the Mailchimp Transactional email API lets you send emails from your own domain and get high levels of deliverability and tracking on open rates and click rates to help you monitor performance.

The Mailchimp Transactional email API is very inexpensive to use, and is free on the paid versions of Mailchimp. The API is specifically designed for sending transactional emails. If you want to send bulk emails, such as email marketing campaigns, you should use the Mailchimp Marketing API instead.

In this project, I’ll show you how quick and easy it is to integrate email support into your Python applications and automations.

Install the Mailchimp Transactional API

You can install the Mailchimp Transactional email API package in two ways. You can either install it via the PyPi Python package management system by entering pip3 install mailchimp-transactional or you can install the package directly from GitHub using the command below.

!pip install git+https://github.com/mailchimp/mailchimp-transactional-python.git

Import the packages

Next, import the packages you’ll need to send transactional emails. We’ll need the mailchimp_transactional and the ApiClientError package so we can create accurate exceptions that aid debugging.

import mailchimp_transactional as MailchimpTransactional
from mailchimp_transactional.api_client import ApiClientError

Define your Mailchimp API key

To authenticate with the Mailchimp Transactional API you’ll need to create an API key, which you can do using your Mailchimp account. Save the Mailchimp API key in a variable called MAILCHIMP_API_KEY so you can load it in your functions.

MAILCHIMP_API_KEY = 'xxxxxxxxxxx'

Test your API connection

To test that your Mailchimp API key is working, there’s a useful ping() function provided. We’ll create a try except block to test the connection. If it works, you’ll get a message back from Mailchimp. If it fails , you’ll get an ApiClientError exception telling you what went wrong.

try:
    mailchimp = MailchimpTransactional.Client(MAILCHIMP_API_KEY)
    response = mailchimp.users.ping()
    print('API called successfully: {}'.format(response))
except ApiClientError as error:
    print('An exception occurred: {}'.format(error.text))
    
mailchimp = MailchimpTransactional.Client(MAILCHIMP_API_KEY)

Send an email using the Mailchimp Transactional API

Assuming the previous step worked correctly, you can now send your email via the Mailchimp Transactional API. The try/except block is much the same as the previous one, but we’re instead calling the messages.send() function.

The messages.send() function takes a single parameter, which is a dictionary of the email you want to send. The dictionary content, stored in message shows some of the fields you can fill in. You can find a full list of fields in the Mailchimp Transactional API documentation.

message = {
    "from_email": "matt@example.com",
    "from_name": "Matt Clarke",
    "subject": "The model has run successfully",
    "text": "ROC/AUC = 0.91",
    "to": [
      {
        "email": "bob@example.com",
        "type": "to"
      }
    ]
}
try:
    mailchimp = MailchimpTransactional.Client(MAILCHIMP_API_KEY)
    response = mailchimp.messages.send({"message":message})
    print('API called successfully: {}'.format(response))
except ApiClientError as error:
    print('An exception occurred: {}'.format(error.text))
    

Create a function you can re-use

To make a simple reusable function that you can use in your Python automations to send an email we’ll wrap up the code above into a function called send_email(). All you need to do is create a dictionary containing the message and pass it to the function and your email will be sent.

 def send_email(message):
    """Send an email using the Mailchimp Transcational API. 
    
    Args: 
        message (dictionary): Message dictionary in the below format. 
        
        message = {
            "from_email": "matt@example.com",
            "from_name": "Matt Clarke",
            "subject": "The model has run successfully",
            "text": "ROC/AUC = 0.91",
            "to": [
              {
                "email": "bob@example.com",
                "type": "to"
              }
            ]
        }
    
    Returns:
        response
    """
    
    try:
        response = mailchimp.messages.send({"message":message})
        return response
    except ApiClientError as error:
        print('An exception occurred: {}'.format(error.text))

Matt Clarke, Saturday, December 18, 2021

Matt Clarke Matt is an Ecommerce and Marketing Director who uses data science to help in his work. Matt has a Master's degree in Internet Retailing (plus two other Master's degrees in different fields) and specialises in the technical side of ecommerce and marketing.