Boost Productivity: Automate Gmail to Multiple Recipients with Google Sheets and Apps Script
- For those who find sending Gmail each time to be cumbersome
- For those who want to send emails to multiple recipients by only changing part of the message
When sending emails to customers or contacts managed in a spreadsheet, do you find yourself sending similar content to each one individually?
For example, if you need to send emails to multiple recipients by only changing the meeting schedule in the email body, doing it manually can lead to mistakes and take a lot of time.
In such cases, it would be convenient to have a method to automatically send emails using Google Sheets.
In this article, we will introduce how to automate email sending using Google Sheets and Google Apps Script.
This allows you to focus on other important tasks without spending time on sending emails every time.
Completed example
Gmail Content
Here is a completed example of how to automatically send emails using the spreadsheet and Google Apps Script we will create this time.
Based on the information for each recipient entered in the Google Sheet, a portion of the email body is automatically customized, and then the email is sent via Gmail.
In this example, the changes to be inserted into the email body include the name, meeting date, and meeting time.
A pre-prepared email draft is duplicated, and these pieces of information are automatically replaced, allowing for personalized emails to be sent.
Google Sheet Input Fields
Column A (First Name) | Enter the recipient’s first name. This name will be inserted into the email body sent via Gmail. |
Column B (Last Name) | Enter the last name. In this example, it will not appear in the email body. |
Column C (Email Address) | Enter the recipient’s email address. |
Column D (Meeting Date) | Enter the meeting date. |
Column E (Meeting Time) | Enter the meeting time. |
Column F (Check) | Check the box for individuals who are the target of the email. This column is used to select whether to send the email or not. |
Column G (Sent Time) | The timestamp of when the email was sent is automatically recorded. This allows you to verify whether the email was sent. |
Sheet Name | As an example, the name “Email Sending List” is used. This sheet name will be used when executing the Google Apps Script. |
How to Use the Check Box in Column F
By using the checkboxes in Column F, you can easily select the recipients to whom the emails will be sent.
For example, if you want to send emails to Mr. Smith and Mr. Johnson but want to send one to Mr. Brown later, you would uncheck Mr. Brown.
Emails are sent only for the rows where the checkbox is checked, and the send time is recorded in Column G after the email is sent.
Google Apps Script Settings
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Email Sending List'); // Specify the tab name "Email Sending List"
var range = sheet.getRange("A2:G"); // Get the data range from A2 to column G
var data = range.getDisplayValues(); // Get the displayed data within the range
var draftId = getDraftIdBySubject('Regarding Meeting Schedule'); // Email draft subject
if (!draftId) {
Logger.log("Error: Draft not found.");
return; // Exit if the draft is not found
}
data.forEach(function(row, index) {
var sentTime = row[6]; // Column G: Sent Time
if (row[5] === 'TRUE' && !sentTime) { // Check if the checkbox in column F is checked
var recipient = row[2]; // Column C: Email Address
var subject = 'Regarding Meeting Schedule'; // Subject of the email to be sent
var body = getDraftMessageBody(draftId); // Get the draft message body
var attachments = getDraftAttachments(draftId); // Get the draft attachments
// Replace placeholders with data from the spreadsheet
body = body.replace(/{First Name}/g, row[0]) // Column A: First Name
.replace(/{Meeting Date}/g, row[3]) // Column D: Meeting Date
.replace(/{Meeting Time}/g, row[4]); // Column E: Meeting Time
// Send email using GmailApp.sendEmail (with HTML body)
GmailApp.sendEmail(recipient, subject, '', {
htmlBody: body,
attachments: attachments // Add attachments to the email
});
// Record the sent time in Column G
var userTimezone = Session.getScriptTimeZone(); // Get the user's script timezone
var localTime = Utilities.formatDate(new Date(), userTimezone, 'MM/dd/yyyy HH:mm:ss');
sheet.getRange(index + 2, 7).setValue(localTime); // Record the sent time in Column G
}
});
}
// Function to get draft attachments
function getDraftAttachments(draftId) {
var draft = GmailApp.getDraft(draftId);
var message = draft.getMessage();
return message.getAttachments(); // Get attachments
}
// Function to get draft ID by specified subject
function getDraftIdBySubject(subject) {
var drafts = GmailApp.getDrafts();
for (var i = 0; i < drafts.length; i++) {
if (drafts[i].getMessage().getSubject() === subject) {
return drafts[i].getId();
}
}
Logger.log("Error: No draft found with subject '" + subject + "'.");
return null; // Return null if no draft is found
}
// Function to get the draft message body
function getDraftMessageBody(draftId) {
var draft = GmailApp.getDraft(draftId);
var message = draft.getMessage();
return message.getBody(); // Get the draft HTML body
}
スクリプトの説明
- Main Process:
sendEmails()
-
sendEmails()
is the main function that retrieves data from the Google Sheet and automatically sends emails corresponding to each row. - Retrieving Spreadsheet Data
-
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Email Sending List'); // Specify the tab name "Email Sending List" var range = sheet.getRange("A2:G"); // Get the data range from A2 to column G var data = range.getDisplayValues(); // Get the displayed data within the range
SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Email Sending List')
: Specify and retrieve the sheet named “Email Sending List.”sheet.getRange("A2:G")
: Retrieve data by specifying the range from A2 to column G.
This range includes the first name, email address, meeting date, meeting time, checkbox, and sent time.getDisplayValues()
: Retrieve the displayed values within the range in an array format.
- Retrieving Draft Email
-
var draftId = getDraftIdBySubject('Regarding Meeting Schedule'); // Email draft subject if (!draftId) { Logger.log("Error: Draft not found."); return; // Exit if the draft is not found }
getDraftIdBySubject('打合せ日程について')
: Search for the draft with the subject “Regarding Meeting Schedule” in Gmail and retrieve its ID.- If the draft is not found, log an error message and terminate the process.
- Send Emails for Each Data Entry
-
data.forEach(function(row, index) { var sentTime = row[6]; // Column G: Sent Time if (row[5] === 'TRUE' && !sentTime) { // Check if the checkbox in column F is checked
- Check the sent time in column G. Since the sent time is recorded for sent rows, verify it accordingly.
row[5] === 'TRUE'
: Check if the checkbox in column F is “TRUE” (checked) to determine whether the email should be sent to that recipient.- The subsequent email sending process will be executed for rows that meet these conditions.
- Preparing to Send Emails
-
var recipient = row[2]; // Column C: Email Address var subject = 'Regarding Meeting Schedule'; // Subject of the email to be sent var body = getDraftMessageBody(draftId); // Get the draft message body var attachments = getDraftAttachments(draftId); // Get the draft attachments
-
row[2]
: Retrieve the email address from column C to specify the recipient.getDraftMessageBody(draftId)
,getDraftAttachments(draftId)
: Retrieve the body and attachments of the previously obtained draft email.
- Customization
-
// Replace placeholders with data from the spreadsheet body = body.replace(/{First Name}/g, row[0]) // Column A: First Name .replace(/{Meeting Date}/g, row[3]) // Column D: Meeting Date .replace(/{Meeting Time}/g, row[4]); // Column E: Meeting Time
body.replace()
:Based on the spreadsheet data, replace the placeholders in the draft email ({First Name}
,{Meeting Date}
,{Meeting Time
) with the actual data.row[0]
: Use column A (First Name),row[3]
: column D (Meeting Date), androw[4]
: column E (Meeting Time) to dynamically customize each individual email content.
- Sending Email
-
// Send email using GmailApp.sendEmail (with HTML body) GmailApp.sendEmail(recipient, subject, '', { htmlBody: body, attachments: attachments // Add attachments to the email });
GmailApp.sendEmail()
: Send the email to the specified recipient using the retrieved body and attachments.- Using `
htmlBody
` allows sending the email in HTML format.
- Recording the Sent Time
-
// Record the sent time in Column G var userTimezone = Session.getScriptTimeZone(); // Get the user's script timezone var localTime = Utilities.formatDate(new Date(), userTimezone, 'MM/dd/yyyy HH:mm:ss'); sheet.getRange(index + 2, 7).setValue(localTime); // Record the sent time in Column G
Utilities.formatDate()
: Get the current date and time.sheet.getRange(index + 2, 7).setValue(localTime)
:Record the sent time in column G of the row where the email was sent. This helps prevent duplicate sending.
- Helper Functions:
getDraftAttachments(draftId)
-
// Function to get draft attachments function getDraftAttachments(draftId) { var draft = GmailApp.getDraft(draftId); var message = draft.getMessage(); return message.getAttachments(); // Get attachments }
- Retrieve the attachments based on the specified draft email ID.
- Use `
GmailApp.getDraft()
` to obtain the draft email and then retrieve the attachments from its message.
- Helper Functions:
getDraftIdBySubject(subject)
-
// Function to get draft ID by specified subject function getDraftIdBySubject(subject) { var drafts = GmailApp.getDrafts(); for (var i = 0; i < drafts.length; i++) { if (drafts[i].getMessage().getSubject() === subject) { return drafts[i].getId(); } } Logger.log("Error: No draft found with subject '" + subject + "'."); return null; // Return null if no draft is found }
- Search through all drafts saved in Gmail to find the email with the specified subject and retrieve its ID. If it’s not found, return null.
- Helper Functions:
getDraftMessageBody(draftId)
-
// Function to get the draft message body function getDraftMessageBody(draftId) { var draft = GmailApp.getDraft(draftId); var message = draft.getMessage(); return message.getBody(); // Get the draft HTML body }
- Retrieve the body (in HTML format) from the draft email corresponding to the specified ID.
his script automatically sends emails from Gmail based on the email addresses and meeting schedules listed in a spreadsheet.
The email body is created by customizing a pre-prepared draft email template.
Emails are sent individually based on the information in the spreadsheet, and the date and time of sending are also recorded.
Recording the sent time helps prevent duplicate emails from being sent.
Steps
Open Google Sheets, then click on “Extensions” in the menu and select “Apps Script” to open the editor.
Copy the code above and paste it into the editor.
Once you’ve written the code, name it and save it.
(For example: “Send Email”)
Create email draft
Next, open Gmail and create a draft email template.
In the draft email, use placeholders { } like below, so that data from the spreadsheet can be inserted.
Example draft
Subject: Regarding Meeting Schedule
Dear {First Name},
We are pleased to inform you of the scheduled meeting details as follows:
- Meeting Date: {Meeting Date}
- Time: {Meeting Time}
Thank you and best regards.
By including placeholders like {First Name}
and Meeting Date
in the email body, data from the spreadsheet will be automatically inserted.
Run the script to send emails
Once all settings are complete, run the script from the Apps Script editor screen.
Open Google Sheets, then click on “Extensions” in the menu and select “Apps Script” to open the editor.
Execute the script to send the emails.
If you’re running the script for the first time, you need to authorize it.
Therefore, press “Review Permissions.“
Detailed Authorization Steps
Press “Advanced.”
Press “Go to Untitled project (Unsafe).”
After that, press “Allow.”
This will automatically send emails to the people checked in the spreadsheet and record the sent date and time.
Recording sent date and time in the google sheet
Additionally, creating a button on the spreadsheet allows you to run the script more easily.
Gmail sending content
Summary
With this, the basic email sending automation using Google Sheets and Google Apps Script is complete.
Once set up, you can efficiently automate what used to be a labor-intensive email sending task.
Utilize this method whenever you need to change only parts of the email to send to different recipients.
-
Google Sheets
How to Achieve Accurate and Natural Translations in Google Sheets Using the DeepL API
-
Google Sheets
Automate News Collection with Google Apps Script: Fetch Daily Updates from Google News to Google Sheets
-
Google Sheets
Effortlessly Duplicate Gmail Drafts: Boost Productivity with Google Sheets and Apps Script
Our company offers support for improving work efficiency through the use of Google Apps Script.
If you need assistance with Google Apps Script customization or error resolution, please feel free to contact us.
We are fully committed to supporting your business improvements.
Contact us here
Comments