How to make requests to the Mailrelay API in Python

Do you use any mailing tool to manage your list of subscribers? My favorite is Mailrelay and I use it in all my projects where I run one.

Why do I use Mailrelay? Basically for the following reasons:

  • Your technical service is exceptional. They solve all the doubts I have in a short space of time and they are very kind.
  • It is very easy to use and has everything that can be asked of a tool of this type.
  • Its free plan is the best on the market: it allows you to send up to 75,000 free emails per month and manage up to 15,000 contacts. Almost nothing.
  • And perhaps the most important thing together with its technical service: They adapt perfectly to the RGPD.

No, this time I am not going to teach you how to use Mailrelay to carry out your mailing campaigns. I am going to teach you something better and that is not in your manuals: How to integrate your Python project with the Mailrelay API.

Integrating the Mailrelay API in your Python project

Thanks to the Mailrelay API you can manage your list of subscribers from your own source code. In my case, it is common for me to add a user of one of my applications to the list of subscribers after registering in it.

The only bad thing about the API documentation is that all the examples use the PHP language 🙃😖

Although it is not difficult to understand what they do, you may not know how to translate these examples into your favorite language: Python 🐍

But don’t worry, below I will show you a couple of cases to use Python with the Mailrelay API.

Adding a subscriber to the list

In this link is the documentation of the addSubscriber operation of the Mailrelay API.

In my case, I use the requests library to make requests to the API. Here I show you how to add a subscriber to the list and to certain groups:

import record
import requests

log = log. getLogger ( __name__ )

languages ​​= dict ()
languages ​​[ 'is' ] = 2
languages ​​[ 'in' ] = 3

API_ENDPOINT = "https://<your_account>.ip-zone.com/ccm/admin/api/version/2/&type=json"

define subscribe_user_to_newsletter ( user ) : 
    """
    This method is used to add a new subscriber to the mailing list.
    It should be used when a new user signs up.

    The ids of the Mailrelay groups are:

        1: All users
        2: Users language 'en'
        3: Users language 'hi'

    Args:
        user: User registered in the system

    """

    if current_app.config [ 'APP_ENV' ] == current_app.config [ 'APP_ENV_PRODUCTION' ] :
        language_group = languages. get ( user.language, None )
        user_groups = [ 1 ]
        if language_group:
            user_groups. append ( language_group )
        payload = {
            "function" : "addSubscriber" ,
            "apiKey" : current_app.config [ 'MAILRELAY_API_KEY' ] ,
            "email" : user.email,
            "name" : user.nick,
            "groups[]" : user_groups
        }
        try :
            r = requests. post ( API_ENDPOINT, data=payload )
            if r.status_code != 200 :
                logger. error ( u 'Could not add user {} to Mailrelay' . format ( user.email ))
                return
            else :
                response = r. json ()
                if not response or response [ "status" ] == 0 : 
                    logger. error ( u 'Could not add user {} to Mailrelay' . format ( user.email ))
                    return
                mailrelay_user_id = response. get ( 'data' , None )
                logger. info ( u 'User {} was added to Mailrelay with id: {}' . format ( user.email, mailrelay_user_id ))
        except Exception:
            logger. exception ( u 'Could not add user {} to Mailrelay' . format ( user.email ))

Remember to replace of the API_ENDPOINT variable with yours. Also keep in mind that you must indicate your API Key in the corresponding parameter. In the example, I am getting this value from the configuration parameters of my application. To finish, simply tell you that I add the subscriber to the list in case I am in the production environment.

Updating a subscriber list

Updating a subscriber is very similar. The documentation for the updateSubscriber operation can be found here. Keep in mind that to update a subscriber you need to indicate his id, which you get when adding the subscriber to the list. If you haven’t stored it, as in my case, you can retrieve it by calling the getSubscribers operation beforehand:

def update_subscriber ( user ) : 
    """
    This method is used to update the data of a mailing list subscriber.
    It should be used when the user information associated with the newsletter changes.
    The ids of the Mailrelay groups are:
        1: All users
        2: Users language 'en'
        3: Users language 'hi'
    Args:
        user: User to modify
    """
    if current_app.config [ 'APP_ENV' ] == current_app.config [ 'APP_ENV_PRODUCTION' ] :
        language_group = languages. get ( user.language, None )
        user_groups = [ 1 ]
        if language_group:
            user_groups. append ( language_group )
       # First we must obtain the user id corresponding to Mailrelay
        payload = {
            "function" : "getSubscribers" ,
            "apiKey" : current_app.config [ 'MAILRELAY_API_KEY' ] ,
            "email" : user.email
        }
        try :
            r = requests. post ( API_ENDPOINT, data=payload )
            if r.status_code != 200 :
                logger. error ( u 'Could not retrieve user {} from Mailrelay' . format ( user.email ))
                return
            else :
                response = r. json ()
                if not response or response [ "status" ] == 0 : 
                    logger. error ( u 'Could not retrieve user {} from Mailrelay' . format ( user.email ))
                    return
                subscribers = response. get ( "data" , None )
                if not subscribers: 
                    logger. warning ( u 'Could not retrieve user {} from Mailrelay' . format ( user.email ))
                    return
                subscriber_id = subscribers [ 0 ][ "id" ]
        except Exception:
            logger. exception ( u 'Could not retrieve user {} from Mailrelay' . format ( user.email ))
            return
       # Once the user id is available, the corresponding endpoint is invoked
       # to update it
        payload = {
            "function" : "updateSubscriber" ,
            "apiKey" : current_app.config [ 'MAILRELAY_API_KEY' ] ,
            "id" : subscriber_id,
            "email" : user.email,
            "name" : user.nick,
            "groups[]" : user_groups
        }
        logger. info ( "Updating Mailrelay user {} - Groups: {}" . format ( user.email, user_groups ))
        try :
            r = requests. post ( API_ENDPOINT, data=payload )
            if r.status_code != 200 :
                logger. error ( u 'Could not modify Mailrelay user {}' . format ( user.email ))
                return
            else :
                response = r. json ()
                if not response or response [ "status" ] == 0 : 
                    logger. error ( u 'Could not modify Mailrelay user {}' . format ( user.email ))
                    return
                logger. info ( u 'Mailrelay user {} has been modified with id: {}' . format ( user.email,
                                                                                             subscriber_id ))
        except Exception:
            logger. exception ( u 'Could not modify Mailrelay user {}' . format ( user.email ))

Conclution

As you may have noticed, migrating the Mailrelay API examples from PHP to Python code is very simple, don’t you think? You simply have to review the operation you want to perform and use the requests library to make requests to the endpoint.

You already know that if you have any questions you can contact me by commenting below. Thank you 🙂