How to Build a Mailchimp Embed Form in AMP Pages

Mi Guoliang

Introduction

Mailchimp is an excellent solution to manage the email subscription to your website. Mailchimp provides embed form, APIs, and online email design tools. Mailchimp can send a welcome email to your visitor when people subscribe to your email list on your website. Mailchimp is free for a small website. More about Mailchimp, visit its official website.

AMP is a web component framework to create user-first websites easily. AMP is a solution to speed up your website performance, and it is very friendly to Google SEO. My website that you are visiting is an AMP website. AMP is also a specification to your HTML using, so many limitations can break your programming habits.

Mailchimp is not AMP friendly, because CORS error occurs when you submit a form in AMP pages for securities reason by Mailchimp. So how to using both benefits of them is the critical content in this article.

Solution

Use an AWS Lambda function as an agent to subscribe to a visitor’s email to Mailchimp. Mailchimp provides APIs and SDKs so that developers can custom their workflows easily and flexible.

1. Create a AWS Lambda function in Python 3.7

2. Setup Envrionment Variables to Lambda Function

For security reasons, developers should separate secrets, credentials, and passwords from source code. AWS Lambda provides environment variable settings like other famous platforms such as CircleCI, and so on.

Here, we need set Mailchimp username, api key, and list id here.

You can learn How to find your List ID in Mailchimp.

3. Create a Python virtual envrionment

In some cases, you may need to use a virtual environment to install dependencies for your function. That can occur if your function or its dependencies have dependencies on native libraries, or if you used Homebrew to install Python.

Run command mkdir -p aws-lambda-function; cd aws-lambda-function to create and enter the project folder.

~/aws-lambda-function$ source v-env/bin/activate
(v-env) ~/aws-lambda-function$

4. Install Dependencies

5. Deactivate the Python virtual environment

6. Write code

Create the program file and paste code into it.

import json
import base64
import os
import logging
from requests_toolbelt.multipart import decoder
from mailchimp3 import MailChimp
from mailchimp3.mailchimpclient import MailChimpError

logger = logging.getLogger()
logger.setLevel(logging.INFO)

def parse_email(content_type, body):
    multipart_string = base64.b64decode(body)
    parts = decoder.MultipartDecoder(multipart_string, content_type).parts
    for part in parts:
        if 'name="email"' in str(part.headers[b'Content-Disposition']):
            return part.text
    return None

def my_handler(event, context):
    api_key = os.environ['API_KEY']
    username = os.environ['USERNAME']
    list_id = os.environ['LIST_ID']
    client = MailChimp(mc_api=api_key, mc_user=username)
    content_type = event['headers']['Content-Type']
    email = parse_email(content_type, event['body'])
    try:
        lists = client.lists.all()
        logger.info(lists)
        members = client.lists.members.create(list_id, {
            'email_address': email,
            'status': 'subscribed'
        })
    except MailChimpError as e:
        print(e)
        return {
            'statusCode': 400,
            "header": {
                "Content-Type": "application/json"
            },
            'body': str(e)
        }
    return {
        'statusCode': 200,
        "header": {
            "Content-Type": "application/json"
        }
        'body': ''
    }

7. Package the Python virual environment and your code

Create a shell script file, and paste code into the file.

#!/usr/bin/bash

rm -rf ${OLDPWD}/function.zip
cd v-env/lib/python3.7/site-packages
zip -r9 ${OLDPWD}/function.zip .
cd ${OLDPWD}
zip -g function.zip function.py
aws lambda update-function-code --function-name mailchimp-proxy --zip-file fileb://function.zip

8. Deploy your code to the remote

Run command sh package.sh to start the script we just created.

9. Verify your AWS Lambda function

10. Build a Mailchimp Embed Form in your AMP Pages

Import neccessary AMP javascript file in your <head>.

<script async src="https://cdn.ampproject.org/v0.js"></script>
<script async custom-template="amp-mustache" src="https://cdn.ampproject.org/v0/amp-mustache-0.2.js"></script>
<script async custom-element="amp-form" src="https://cdn.ampproject.org/v0/amp-form-0.1.js"></script>

Paste codes into the HTML file.

<!-- Begin Mailchimp Signup Form -->
<div id="mc_embed_signup">
    <form action-xhr="<YOUR ENDPOINTS>" method="post"
        id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
        <div id="mc_embed_signup_scroll">
            <input type="email" value="" name="email" class="email" id="mce-EMAIL" placeholder="email address" required>
            <div class="clear"><input type="submit" value="Subscribe" id="mc-embedded-subscribe" class="button"></div>
        </div>
        <div submit-success>
            <template type="amp-mustache">
                <h1>Thanks for your subscription!</h1>
            </template>
        </div>
        <div submit-error>
            <template type="amp-mustache">
                <h1>You have subscribed!</h1>
            </template>
        </div>
    </form>
</div>
<!--End mc_embed_signup-->

11. Verify the form on your AMP Pages

People can create a static website easily by Jekyll. You learn Jekyll in 5 minutes by reading A Beginner’s Guide on Jekyll. People also can create an AMP page in their familiar ways.

Run your website by command jekyll serve and open http://localhost:4000 on your browser.

In my blog website, what you are visiting is a live demo, you can try to subscribe to your email at the bottom of the pages.

12. Verify subscriptions on your Mailchimp console

Conclusion

There are many frameworks, tools, and practices for frontend development. But not all of them have excellent compatibility. So we need to do some work to integrate their features to gain excellent user experience and speed up our development.

You can download full source code about the Python program in my Github https://github.com/miguoliang/mailchimp-proxy-aws-lambda and use it in your project if you want.

If you like my share, you can:

• Follow My Programming Experiences Page on Facebook.

• Follow My Twitter.

• Subscribe to my mail list.