MailChimp Email Campaign Creation using python

Sheranga Gamwasam
Analytics Vidhya

--

Email marketing is an effective and powerful way to communicate with your E-commerce customers, because more than 34% of the people worldwide use emails. When we think about our own experience, we usually receive a number of generic and personalized emails each week from different types of automated E-commerce sites after analyzing their customer databases.

Why Email marketing is so important for your business?

  • It helps you to keep in contact with your audience and core customers
  • You can reach customers in real time since most people open their email on a mobile device
  • Emails feel more personal and engaging than other internet messages
  • Email marketing is one of the easiest types of online marketing to measure in terms of its performance and results
  • It’s actually very affordable

Today I will address the steps to be followed to create a generic email campaign using MailChimp API with Python. If we want to send the customized email campaign, MailChimp API gives the feature for it as well.

Since Authentication of the response is the first step of the process, we need an API key and Username. Now we will see how to generate the API key in MailChimp

1. Click your profile name to expand the Account Panel and choose Account Settings

2. Click the Extras menu and choose API keys

3. Click the Create A Key button and copy the created key

Please follow link to watch the video : How to Automate Email Campaign Using Mailchimp

GitHub repository : https://github.com/sherangaG/mailChimp-email-creation-python

Import the following libraries

from mailchimp3 import MailChimp
from string import Template

import newsletter_template # python script for html template

Following function is used to authenticate the response

MC_API_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX"
MC_USER_NAME = "XXXXXXXXXXXXXXXX"

client = MailChimp(mc_api=MC_API_KEY, mc_user=MC_USER_NAME)

We need the email lists, their first names, last names etc. to send to email recipients. Therefore we need to create the variable which is called “audience” to store the customer details.

Following function is used to create the audience

def audience_creation_function(audience_creation_dictionary):

audience_creation = ''
audience_creation_dictionary = audience_creation_dictionary
print(audience_creation_dictionary)

audience_list = {
"name": audience_creation_dictionary['audience_name'],
"contact":
{
"company": audience_creation_dictionary['company'],
"address1": audience_creation_dictionary['address1'],
"city": audience_creation_dictionary['city'],
"state": audience_creation_dictionary['state'],
"zip": audience_creation_dictionary['zip_code'],
"country": audience_creation_dictionary['country']
},
"permission_reminder": audience_creation_dictionary['audience_name'],
"campaign_defaults":
{
"from_name": audience_creation_dictionary['from_name'],
"from_email": audience_creation_dictionary['from_email'],
"subject": "",
"language": audience_creation_dictionary['language']
},
"email_type_option": False
}

try:
audience_creation = client.lists.create(data = audience_list)
except Exception as error:
print(error)

return audience_creation

After defining the above function, We can create the audience by calling the following code. Here we use the audience_creation_dictionary, that includes the audience_name, company, address1, city, state, zip_code, country, from_name, from_email and language.

audience_creation_dictionary = {
"audience_name" : "ENTER AUDIENCE NAME",
"company" : "ENTER COMPANY NAME",
"address1" : "ENTER ADDRESS",
"city" : "ENTER CITY",
"state" : "ENTER STATE", # EX: Western Province
"zip_code" : "00300",
"country" : "ENTER COUNTRY", # EX: LK
"from_name" : "ENTER FROM NAME",
"from_email" : "ENTER FROM EMAIL",
"language" : "en"
}

audience_creation = audience_creation_function(audience_creation_dictionary)

Now we have created the audience. But there are no contacts in it. We need to add contacts that we created previously to the audience

Following function is used to add contacts to the audience

def add_members_to_audience_function(audience_id, mail_list, client=client):

audience_id = audience_id
email_list = email_list

if len(email_list)!=0:
for email_iteration in email_list:
try:
data = {
"status": "subscribed",
"email_address": email_iteration
}

client.lists.members.create(list_id=audience_id, data ​=data)
print('{} has been successfully added to the {} audience'.format(email_iteration, audience_id))

except Exception as error:
print(error)
else:
print('Email list is empty')

To add the members to the audience, we need to assign values to the parameters which are audience_id and email_list

audience_id = audience_creation['id']

email_list = ['ENTER EMAIL ADDRESS1',
'ENTER EMAIL ADDRESS2']

add_members_to_audience_function(audience_id=audience_creation['id'],email_list=email_list)

Now we have added the members to the audience and now we will create the email campaign.

Following function is used to create the campaign.

def campaign_creation_function(campaign_name, audience_id, from_name, reply_to, client=client):

campaign_name = campaign_name
audience_id = audience_id
from_name = from_name
reply_to = reply_to

data = {
"recipients" :
{
"list_id": audience_id
},
"settings":
{
"subject_line": campaign_name,
"from_name": from_name,
"reply_to": reply_to
},
"type": "regular"
}

new_campaign = client.campaigns.create(data=data)

return new_campaign

Following code is used to implement the campaign_creation_function with three parameters

campaign_name = 'CAMPAIGN NAME'
from_name = 'FROM NAME'
reply_to = 'REPLY MAIL ADDRESS'
campaign = campaign_creation_function(campaign_name=campaign_name,
audience_id=audience_creation['id'],
from_name=from_name,
reply_to=reply_to,
client=client)

I have created the simple html template for news letter campaign using HTML and CSS style and embedded in the python script (newsletter_template.py)

def customized_template(html_code, campaign_id, client=client):

html_code = html_code
campaign_id = campaign_id
string_template = Template(html_code).safe_substitute()

try:
client.campaigns.content.update(
campaign_id=campaign_id,
data={'message': 'Campaign message', 'html': string_template}
)
except Exception as error:

print(error)

Following code is used to call the customized_template function

html_code = newsletter_template.html_code           
customized_template(html_code=html_code, campaign_id=campaign['id'])

Following function is used to send the email

def send_mail(campaign_id, client=client):      
try:
client.campaigns.actions.send(campaign_id = campaign_id)
except Exception as error:
print(error)

Call the send_email function

send_mail(campaign_id=campaign['id'])

As I mentioned earlier, we are able to send personalized email campaigns using python and MailChimp API. If you need any help regarding this, comment below

Please follow link to glimpse a guide on How to Automate Email Campaign Using Mailchimp

--

--