Open In App

Create Newsletter app using Mailchimp and Django

Last Updated : 19 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we’ll use MailChimp and Django to make a simple mailing app. When people subscribe to our app, we’ll learn how to create an audience list and save the users in MailChimp using Python.

Have you considered how they could send emails to subscribers with only one click? MailChimp is the greatest email marketing software. It also allows you to manage your audiences and send bulk emails by allowing you to build multiple lists. However, simply sending emails is insufficient. It should have some appealing MailChimp layouts and text, and you may choose preset templates for your email directly.

Create MailChimp Free Account:

To create a MailChimp account and get an API key follow the below steps:

Step 1: Go to MailChimp.com and signup for free. Also, set up the profile of your account.

Step 2:  Now, to get the API key, From the bottom left of your screen, Go to the profile>> Extras >> API Key >> Create API Key. Furthermore, it would help if you store your API key. We will use it later in our Django app.

 

Step 3: Next, we need to create an audience list. Go to https://us14.admin.mailchimp.com/lists/, and click on the Create Audience. Fill in the required details and see your audience on the audience dashboard.

 

Step 4: Now, we need to get the audience list id. Go to the audience settings -> list id. Store the list id to use it in the Django app.

 

Create Django APP:

Step 1: Users need to enter the below command into the terminal to create a new Django App.

django-admin startproject mailchimpNewsletter

Step 2: Next, go to the project directory.

cd mailchimpNewsletter

Now, users need to create a views.py file in the project directory. Also, create a templates folder and create a home.html  ( templates>> home.html ) ,success.html, and error.html file in that.

Project structure: It should look like this.

 

Step 3: Before we dive into setting up the project, install the Mailchimp-marketing python library by entering the below command to the project directory.

pip install mailchimp-marketing

Step 4: In this step, we will integrate Mailchimp with the Django App.

  • urls.py: Add the below code with the code of the urls.py file. We have set up the URLs for our Django App in this file.

Python3




from django.contrib import admin
from django.urls import path
from . import views
 
urlpatterns = [
    path('admin/', admin.site.urls),
    path("", views.subscribeToNewsLetter, name="subscribeToNewsLetter"),
    path("success", views.success, name="success"),
    path("error", views.error, name="error"),
]


  • views.py: In this file, we will add basic code to subscribe the user to Mailchimp.

Python3




from django.shortcuts import redirect, render
from mailchimp_marketing import Client
from mailchimp_marketing.api_client import ApiClientError
 
api_key = "acfa4fffd113041454c6d953a71fa3e5-us14"
list_id = "f4f5ad20f7"
 
# function to manage subscriber
def subscribeToNewsLetter(request):
    if request.method == "POST":
 
        # getting users input from the form
        email = request.POST['email']
        firstName = request.POST['firstName']
        lastName = request.POST['lastName']
 
        # initializing the mailchimp client with api key
        mailchimpClient = Client()
        mailchimpClient.set_config({
            "api_key": api_key,
        })
 
        userInfo = {
            "email_address": email,
            "status": "subscribed",
            "merge_fields": {
                "FNAME": firstName,
                "LNAME": lastName
            }
        }
 
        try:
            # adding member to mailchimp audience list
            mailchimpClient.lists.add_list_member(list_id, userInfo)
            return redirect("success")
        except ApiClientError as error:
            print(error.text)
            return redirect("error")
 
    return render(request, "home.html")
 
def success(request):
    return render(request, 'success.html')
 
def error(request):
    return render(request, 'error.html')


  • home.html: It is the basic template to collect the user’s email, first name, and last name.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <title>Email subscriptions</title>
 
    <!-- Bootstrap -->
 
    <style>
        form {
            position: absolute;
            left: 40%;
            display: flex;
            flex-direction: column;
        }
 
        input {
            margin: 10px 0;
            width: 300px;
            height: 50px;
        }
 
        button {
            width: 300px;
            height: 50px;
        }
 
        h1 {
            color: green;
            margin-bottom: 20px;
        }
    </style>
</head>
 
<body style="text-align:center">
 
    <h1>GeeksforGeeks</h1>
    <h2>Subscribe to Our NewsLetter App</h2>
 
    <!--Email subscription Form -->
    <form method="post" action="{% url 'subscribeToNewsLetter' %}">
        {% csrf_token %}
        <input type="email" name="email" placeholder="Your Email">
        <input type="text" name="firstName" placeholder="Your firstName">
        <input type="text" name="lastName" placeholder="Your lastName">
        <button class="btn btn-secondary" type="submit">Submit</button>
    </form>
 
</body>
 
</html>


  • success.html: We will redirect a user to this template when they subscribe to our newsletter successfully.

HTML




<!DOCTYPE html>
<html lang="en" dir="ltr">
 
<head>
    <meta charset="utf-8">
    <title>successfully</title>
        integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
 
<body>
    <div class="jumbotron jumbotron-fluid">
        <div class="container">
            <h1 class="display-4">Awesom</h1>
            <p class="lead">You are successful to signup in newsletter website,
                please look forward.</p>
 
 
 
 
        </div>
    </div>
</body>
 
</html>


  • error.html: We will redirect a user to this template when some error occurs while subscribing to our newsletter.

HTML




<!DOCTYPE html>
<html lang="en" dir="ltr">
 
<head>
    <meta charset="utf-8">
    <title>Failure</title>
        integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
 
<body>
    <div class="jumbotron jumbotron-fluid">
        <div class="container">
            <h1 class="display-4">Uh oh!</h1>
            <p class="lead">Contact the developer</p>
 
 
 
 
            <form class="" action="/error" method="post">
                <button class="btn btn-lg " type="submit"
                        name="button">Try again</button>
            </form>
        </div>
    </div>
</body>
 
</html>


Step 5: Add ‘DIRS’ : [os.path.join.(BASE_DIR, ‘templates’)] in your templates list.

 

Step 6: To run the project on your terminal, go to the project directory and enter the below command.

python manage.py runserver

Output: You will see that the app is running successfully on localhost:8000.

 

At last, in MailChimp, you can go to the Audience >> All contacts, and you will see the list of all added contacts.

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads