Recently, we have been writing a lot of stuff related to Web Design and Development, like collecting form responses, that can be implemented using Google Apps Script and Serverless Architecture.
In this blog, you will learn about email marketing. You will set up custom email marketing purely using Google Apps Script. The advantage is you can take control of your email marketing campaign and create your own automated workflows.
Contents
Creating a Spreadsheet
First of all, you need a Google Sheet where you can store all of your email addresses to whom you want to send the emails. So, first create a new spreadsheet.
Creating a Google Apps Project
Next, you need to connect your Google Sheet to a Google Apps Script. From Tools, select the Script Editor.
Writing Code
Finally, it is time to write some code.
a.) Main.gs
Add the following code to this file:
function sendEmails(mail_template='content',
subject='Testing my Email Marketing') {
// get the active spreadsheet and data in it
const id = SpreadsheetApp.getActiveSpreadsheet().getId()
const sheet = SpreadsheetApp.openById(id).getActiveSheet()
const data = sheet.getDataRange().getValues()
// iterate through the data, starting at index 1
for (let i = 1; i < data.length; i++) {
const row = data[i]
const email = row[0]
const name = row[1]
// check if you can send an email
if (MailApp.getRemainingDailyQuota() > 0) {
// populate the template
let template = HtmlService.createTemplateFromFile(mail_template)
template.name = name
const message = template.evaluate().getContent()
GmailApp.sendEmail(
email, subject, '',
{htmlBody: message, name: 'RavSam Team'}
)
}
}
}
The comments have been included in the file for a proper description of the above function.
Always use GmailApp.sendEmail instead of MailApp.sendEmail. It is a more stable and reliant function.
b.) content.html
Since the Main.gs uses an HTML file and populates it, you need to create an HTML template file. Add the following code to content.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
Hi <?= name ?>. You are testing your beta features for email marketing.
</body>
</html>
The <?= name ?>
template variable gets auto-filled by the email marketing script.
4. Running the Script
You have done all the necessary setup to start a successful email marketing campaign. Before you execute your code, you need to grant permissions to your script:
Results
Let’s check the inbox to see if any email is received. Awesome! You can see that the email was delivered successfully to the user’s inbox.
You can create more beautiful and custom HTML templates and manage your email marketing campaigns around them. In the next blog, you will learn to track whether a user opens your emails or not.