Send Email Campaign using Node.Js and Mailchimp API

Create lists of audience and send Digital Marketing Campaign from the node.Js application by using Mailchimp Email provider.

Vijay KMS
Geek Culture

--

If your business is not on the internet, then your business will be out of business ” — Bill Gates.

As taking your business online is inevitable these days, Digital Marketing plays a significant role in it. There are many Email providers out there to send marketing campaigns via email.

Mailchimp is one of the best email service providers as it is highly flexible and easy to use. It also has a very good API service that can be easily integrated with our application.

Here, we are going to see how to create audience lists and send email marketing campaigns by using Mailchimp API in the Node.Js application.

To use Mailchimp API, you need to create an account in Mailchimp. And then, you need to generate the API key.

Create Setup in the Node.Js Application

After the API key has been generated, install the Mailchimp_marketing npm module.

The entire source code can be found in this GitHub repository.

npm install @mailchimp/mailchimp_marketing

Then configure the API key in the Node index.js file.

const mailchimp = require("@mailchimp/mailchimp_marketing")mailchimp.setConfig({
apiKey: "00000xxxx0000x0x00xx00x00x00000-us6",
server: "us6",
})

Now, we see how to create a list of audiences(list of emails) and grouping them. And then, we will send email campaigns to specific groups as well as to the entire list.

Audience/List

Creating an Audience list and sending a campaign involves series of steps.

  1. Create Audience List
  2. Add list Members
  3. Grouping the audiences
  4. Send campaigns (We will the steps in the next section)

In Mailchimp, the Audience is nothing but a list of emails. It contains the details about the company, the sender details, list name and so on. To create a list, use the add list endpoint.

Create Audience List

Assume that the arguments we get from req.body is sent from the client-side in all the below code.

const express = require('express')
const mailchimp = require("@mailchimp/mailchimp_marketing")
const app = express()
app.use(express.static(path.join(__dirname, './index')))
mailchimp.setConfig({
apiKey: "00000xxxx0000x0x00xx00x00x00000-us6",
server: "us6",
})
app.post('/audience/create', async (req, res) => {
const { name, company, address, city, state, zip, country, from_name, from_email, subject, language } = req.body
const footerContactInfo = { company, address1: address, city, state, zip, country }const campaignDefaults = { from_name, from_email, subject, language }async function createAudience() {
try {
const audience = await mailchimp.lists.createList({
name: name,
contact: footerContactInfo,
permission_reminder: "*|LIST:DESCRIPTION|*",
email_type_option: true,
campaign_defaults: campaignDefaults
})
res.send(audience.id)
}
catch (err) {
res.status(400).send(err)
}
}
createAudience()})

The list Id will be returned in response to the successful creation of the list in your Mailchimp account. By using that Id, we can add members to the list.

You have to upgrade your Mailchimp plan to create more than one list.

Add list Members

We can add members one by one and also add bulk email addresses. Adding members to the list requires an email address and subscription status. We can add first name, last name, phone number and other personal information in the merge fields. A tag can be added to the group the email addresses.

Adding one member at a time

app.post('/audience/add/member', async (req, res) => {
const { listId, firstname, lastname, email, tag } = req.body
const addListMember = async () => {
try {
const response = await mailchimp.lists.addListMember(listId, {
email_address: email,
status: 'subscribed',
email_type: 'html',
merge_fields: {
FNAME: firstname,
LNAME: lastname
},
tags: [tag]
})

res.send(response)
}
catch (err) {
res.status(400).send(err)
}
}
addListMember()
})

Adding bulk email addresses (Multiple members)

app.post('/audience/add/members', async (req, res) => {
const { listId, members } = req.body
const membersList = []
members.forEach(member => {
const memberDetails = {
email_address: member.email_address,
email_type: 'html',
status: 'subscribed',
merge_fields: {
FNAME: member.firstname,
LNAME: member.lastname
}
}
membersList.push(memberDetails)
})
const addMultipleMembers = async () => {
try {
const response = await mailchimp.lists.batchListMembers(listId, {
members: membersList,
update_existing: true
})

res.send(response)
}
catch (err) {
res.status(400).send(err)
}
}
addMultipleMembers()
})

Grouping the audiences

In Mailchimp, the segment is nothing but grouping the members of similar fashion in a list. We can group members based on tag names(like customers, employees, investors and so on) and members status such as subscribed, unsubscribed, pending, etc.
The advantage of grouping the audience list is that we can send campaigns to a specific segment.

app.post('/audience/create/segment', async (req, res) => {const { listId, segment_name, emailList } = req.bodyconst conditions = []
emailList.forEach(email => {
conditions.push(
{
"field": "EMAIL",
"op": "contains",
"value": email // email address
})
})
const createSegment = async () => {
try {
const response = await mailchimp.lists.createSegment(listId, {
name: segment_name,
options: {
match: 'any',
conditions: conditions
}
})

res.send(response)
}
catch (err) {
res.status(400).send(err)
}
}
createSegment()
})

To learn more about the segment conditions, visit here.

Email Campaigns

We are halfway through. We have created an Audience list, add members to it and grouped them(Segments). Now we can prepare for sending email campaigns.

  1. Create template
  2. create campaign
  3. Send campaign

Create template

A template is nothing but a normal HTML. We can create our template programmatically and add it to our Mailchimp account or, we can design our template directly in the Mailchimp user interface itself. Either way, after creating the template, we will be getting the template id. All we need is to pass that template id in the body parameters while creating the campaign.

Here we are going to design a template programmatically and send it to our Mailchimp account.

app.post('/campaign/create/template', (req, res) => {
const { templateName } = req.body
const createTemplate = async (err, htmlTemplate) => {
if (err) {
res.send("An error occured while reading template html file!")
}
try {
const template = await mailchimp.templates.create({
name: templateName,
html: htmlTemplate
})

res.send(template.id)
}
catch (err) {
res.status(400).send(err)
}
}
/* Read the html document as utf8*/
fs.readFile('./template.html', 'utf8', createTemplate)
})

Create and Send Campaign

To create a campaign, we depend on three things. The Audience/list id, segment id and the template id. Apart from that, there are settings options that we can pass in the body request.

We can send a campaign to the entire list or only to the particular segment. In the case of sending a campaign to the entire list, only the Audience/list id is enough. We do not need a segment id.

After creating the campaign, we will be getting the campaign Id that is required to send/trigger the campaign.

app.post('/campaign/send', async (req, res) => {
const { ListId, SegmentId, tempalteId, subjectLine, previewText, campaignTitle, fromName, replyTo } = req.body
const createCampaign = async () => {
try {
const campaign = await mailchimp.campaigns.create({
type: "regular",
recipients: {
segment_opts: {
saved_segment_id: SegmentId,
match: 'any'
},
list_id: ListId
},
settings: {
subject_line: subjectLine,
preview_text: previewText,
title: campaignTitle,
template_id: tempalteId,
from_name: fromName,
reply_to: replyTo,
to_name: "*|FNAME|*",
auto_footer: true,
inline_css: true,
}
})

return campaign.id
}
catch (err) {
res.status(400).send(err)
}
}
const sendCampaign = async (campaignId) => {
try {
await mailchimp.campaigns.send(campaignId)
res.redirect("success.html")
}
catch (e) {
res.redirect("fail.html")
}
}
const campaignId = await createCampaign()
sendCampaign(campaignId)
})

Conclusion

We have seen how to create an Audience list, group them, and send email campaigns to them by integrating the Mailchimp API in the Node.Js application. There are still a lot more you can do with the Mailchimp API.

Happy Exploring!

--

--