DEV Community

Cover image for How to Send Emails With Google App Script
Dzenana Kajtaz
Dzenana Kajtaz

Posted on • Originally published at mailtrap.io

How to Send Emails With Google App Script

If you’re a beginner like me and have spent hours unsuccessfully searching for the right piece of content or GitHub page that covers how to use Google App Script to send email, you’re in the right place!

In this article, I will take you step by step through the process of sending emails via Google Scripts.

So hold tight; we’re in for a ride!

Know your options: MailApp vs GmailApp
During my research on the topic of sending emails with Google Apps Script – the JavaScript cloud scripting language – I noticed two services repeatedly mentioned. Those services are MailApp and GmailApp.

What I discovered after looking into them was that both are intended to send emails but come with different functionalities and cater to different needs. So, let’s break them down so you can confidently choose the best service for your specific use case!

Snapshot comparison:

Use MailApp if your email-sending tasks have minimal requirements and are straightforward.
Use GmailApp when you need to interact with Gmail features and complex email functionalities.
MailApp:

Great for sending plain text or HTML emails that don’t require you to interact with the full Gmail features
Does not directly interact with the Gmail interface, and emails sent through MailApp don’t appear in the Gmail “Sent” folder
Has an email sending limit based on your Google account type (e.g., free, Google Workspace) and is separate from the Gmail account sending limits
Intended for heavy Gmail users
GmailApp:

Comes with a rich set of features for completing more complex email-sending tasks, such as sending from aliases, changing the status of an email to read/unread, email search, and label manipulation
Has full integration with the sender’s Gmail account, and emails sent with GmailApp appear in the Gmail “Sent” folder
Provides high flexibility for handling complex email compositions such as rich email formatting and including inline images
Has an email sending limit based on your Gmail account sending limit
Not suitable for bulk email senders and heavy Gmail users
How to send emails using Google Apps Script
To send my emails from Google Apps Script, I decided to go with the GmailApp service. Why? Well, simply because it’s more advanced. So, for the rest of this tutorial and in the code snippets, you’ll see me using this service.

With that out of the way, let’s get into the email-sending process, starting with plain text emails.

*Step 1 – Get your Google Apps Script Editor ready
*

To write the code that will facilitate the email sending, you need to head over to the Google Apps Script website and log in with your Google account.
Then, click on New Project to create a new script.

Image description
*Step 2 – Start writing the script
*

The script I used to send emails is pretty simple.

In the script code, I first set the email recipient and subject. Then, I define the message body before calling the sendEmail function and passing it all the necessary parameters.

`function sendPlainTextEmailDirectlyWithGmailApp() {
var emailaddress = 'recipient@example.com'; // Replace with the actual recipient's email address
var subject = 'Test Email Subject'; // Replace with your desired subject
var message = 'This is a plain text email body.'; // Replace with your plain text message

// Send the email directly
GmailApp.sendEmail(emailaddress, subject, message);
}`

*Step 3 – Save your project and give it a name
*

Before you run your code, the project created needs to be saved and named. This can be done by clicking on the good old floppy disk icon.

Image description

*Step 4 – 3, 2, 1…Run the script
*

And just like that, your code is ready to run! So, now, go into your script editor, select the function you want to run from the dropdown, and click the play (▶️) icon.

Image description

*Step 5 – Authorize the script
*

If it’s your first time running your script, Google will ask you to give the application authorization for sending on your behalf.

Image description

Once this happens, review permissions, choose your account, and grant the permissions necessary for the script to send emails and manage them for you.

Note: Steps such as opening the script editor, saving and running your project, as well as authorizing the script will be essentially the same for all the other email types I cover in this article. So, to avoid repetition, I will mostly skip including these steps from this point on.

*HTML emails
*

In the previous section, I focussed only on plain text email. Now, I’ll take it a level up by showing you how I sent HTML emails.

As the code for sending plain text and HTML emails is not that significantly different, I simply modified what I had already written to fit my HTML email-sending needs.

`function sendHtmlEmailWithGmailApp() {
var recipient = 'recipient@example.com'; // Replace with the actual recipient's email address
var subject = 'Test HTML Email Subject'; // Replace with your desired subject

// Define the HTML body of the email
var htmlBody = '

Hello!

' +
'

This is an HTML email.

';

// Send the email with the HTML body
GmailApp.sendEmail(recipient, subject, '', {
htmlBody: htmlBody
});
}`

When inspecting the modified code above, you will notice that while setting the body of the email, I formatted it as HTML. I then called the same sendEmail function and passed it the four instead of three parameters – recipient, subject, an empty string, and an object.

The object passed to the function contains a single property called htmlBody, which is set to the variable containing the body of the email. Thanks to this property, GmailApp knows how to use HTML content as the email body.

The empty string is passed instead of a regular parameter typically used to set the plain text body of the email, which, in this case, is not necessary.

*Emails with attachments
*

Adding an attachment when sending an email using Google Apps Script is a two-step process – first, you retrieve the file from Google Drive or another source, and then you attach it to the email message.

To retrieve the file, I used the following code snippet:

DriveApp.getFilesByName("Example.pdf").next()

This snippet uses the DriveApp Google Apps Script service and its getFilesByName function. As the getFilesByName function returns a collection of files that match a specific name, another function, next, is called on the returned object.

Then, to attach the retrieved file, I passed a fourth parameter to the sendEmail function. This parameter represents an array that can include one or more attachments.

`GmailApp.sendEmail(recipient, subject, body, {
attachments: [file.getAs(MimeType.PDF)] // Adjust the MIME type as necessary
});
In my code, you will also see the getAs function. This function converts an attached file into a specific format. Here are some examples of how to use getAs to complete various file conversions:

file.getAs(MimeType.MICROSOFT_WORD);
file.getAs(MimeType.PLAIN_TEXT);
file.getAs(MimeType.JPEG);
file.getAs(MimeType.PNG);
file.getAs(MimeType.CSV);
file.getAs(MimeType.HTML);`

And here is the full email-sending code:

`function sendEmailWithAttachment() {
var recipient = "recipient@example.com"; // Replace with the recipient's email address
var subject = "Email with Attachment"; // Replace with your email subject
var body = "Please find the attached file."; // Plain text body of the email
var file = DriveApp.getFilesByName("Example.pdf").next(); // Replace 'Example.pdf' with your file's name

GmailApp.sendEmail(recipient, subject, body, {
attachments: [file.getAs(MimeType.PDF)] // Adjust the MIME type as necessary
});
}`
getFileById route

Google Apps Script facilitates more than one way of adding an attachment. So, besides the getFilesByName function paired with passing the attachments as an array, there is also the getFileById function and Blob (yes, you read that right :D) combination.

So, instead of retrieving the file by name, you can also retrieve it by ID. And instead of attaching an array, you can attach a Blob – a binary large object representing data that can be treated as a file.

Using a Blob is a straightforward way to attach files without needing to adjust or specify the file format explicitly. And this is what it looks like when implemented in my code:

`function sendEmailWithAttachment() {
// Define the email parameters
var recipient = 'recipient@example.com';
var subject = 'Test Email with Attachment';
var body = 'This is a plain text email with an attachment.';

// Get the file from Google Drive (replace 'fileId' with the actual file ID)
var file = DriveApp.getFileById('fileId');

// Create a blob from the file
var blob = file.getBlob();

// Send the email with the attachment
GmailApp.sendEmail(recipient, subject, body, {
attachments: [blob]
});
}`

Emails with multiple recipients
HTML content covered, attachments covered, and single-recipient emails covered. But what if you want to share your email with more than one person? For that, I found two options:

separating the email addresses with commas within a single string
using an array of email addresses and then joining them into a string
Let me show you both!

When it comes to the first option, you need to modify the recipient variable in your script by setting its value to be a string containing email addresses separated by commas.

Then, simply pass the variable to the function sendEmail as you did earlier.

`function sendEmailToMultipleRecipients() {
var recipients = "recipient1@example.com,recipient2@example.com"; // Separate email addresses with commas
var subject = "Email to Multiple Recipients";
var body = "This is a test email sent to multiple recipients.";

GmailApp.sendEmail(recipients, subject, body);
}`

The second option also involves modifying the recipient variable in your script. Only this time, the variable’s value will be set to an array of strings, each representing an email address.

The array is then combined into a single string, separated by commas, using the join function.

`function sendEmailToArrayOfRecipients() {
var recipientArray = ["recipient1@example.com", "recipient2@example.com", "recipient3@example.com"]; // An array of email addresses
var recipients = recipientArray.join(","); // Join the array into a comma-separated string
var subject = "Email to Multiple Recipients";
var body = "This is a test email sent to multiple recipients.";

GmailApp.sendEmail(recipients, subject, body);
}`

The latter approach is particularly useful if the list of recipients is dynamic or large.

CC and BCC recipients
If you want to include CC or BCC recipients in the emails you send from Google Apps Script, at your disposal are the CC and BCC fields in the optional parameters object.

Here is how I made use of them:

`function sendEmailWithCCAndBCC() {
var primaryRecipient = "primary@example.com"; // Primary recipient
var ccRecipients = "cc1@example.com,cc2@example.com"; // CC recipients
var bccRecipients = "bcc1@example.com,bcc2@example.com"; // BCC recipients
var subject = "Email with CC and BCC";
var body = "This email is sent with CC and BCC recipients.";

GmailApp.sendEmail(primaryRecipient, subject, body, {
cc: ccRecipients,
bcc: bccRecipients
});
}`
How to send condition-based emails using Google Apps Script
With manual email-sending out of the way, it’s time for some automation.

In Google Apps Script, automation is used when sending condition-based emails. What’s particularly interesting about these emails is that they leverage the ability of Google Apps Script to interact with Google Services such as Gmail, Sheets, Docs, etc.

Personally, I like to use condition-based emails for tasks such as automating email notifications, reminders, or alerts. And here’s how!

Sending email based on cell value
Let’s imagine you have an Excel or Google spreadsheet containing data on inventory levels. Once those levels drop below a certain threshold, you want to send out an automatic notification or alert to whoever is responsible.

To do so in Google Apps Script, you’ll need the following code:

`function checkCellValueAndSendEmail() {
// ID of the Google Sheet you want to check
var sheetId = 'YOUR_SHEET_ID_HERE';
var sheet = SpreadsheetApp.openById(sheetId).getActiveSheet();

// Assuming the value to check is in cell A1
var cellValue = sheet.getRange('A1').getValue();

// Condition to send email
if (cellValue === 'Send Email') {
var email = 'recipient@example.com'; // Replace with the recipient's email
var subject = 'Alert from Google Sheet';
var body = 'The condition to send an email has been met.';

GmailApp.sendEmail(email, subject, body);
Enter fullscreen mode Exit fullscreen mode

}
}
`What this code does is open a sheet based on an ID you define and pass to the openById function. It then selects a data range within the sheet. In the case of my code, that range is specified as “A1”, which refers to the cell located in column A and row 1 of the spreadsheet.

If the cell value equals “Send Email”, my code then composes and sends an email in the same manner I covered in the previous sections. Cool, huh?

Automate your script further (Optional)
Within the Google Apps Script editor, you can set a script to run according to a schedule or after an event.

This is done by:

  • Clicking on the clock icon (Triggers icon) in the left sidebar.

Image description

  • Clicking + Add Trigger in the bottom right corner. Choosing the function you want to run and setting the event source (for the code to run at specific intervals, Time-driven should be the event source)

Image description

  • Clicking Save.

I should note that when you are setting up the script and email triggers, you’ll need to make sure all necessary permissions are granted for the script to run. For the example I provided, these permissions would include accessing Google Sheets data and sending emails.

Sending email after form submission
Another use case of Google Apps Script that I found particularly cool is the creation of automated emails after a Google Form submission.

To do so, all you need is to create a trigger that runs a code snippet after each response you receive. The code, you guessed it, will send an email using the GmailApp service.

This is how I linked my Google Form and email-sending code:

*Step 1 – Retrieve the form ID
*

The unique ID of each Google form can be found in its URL. These URLs should have the following format:

https://docs.google.com/forms/d/e/[FORM_ID]/viewform
Once you have the ID, copy and save it, as you’ll need to incorporate it into the code soon.

*Step 2 – Get the code ready
*

The code I used for this task is just slightly different from the code used for plain text email sending. So, along with the standard tasks of defining the recipient, subject, and body as well as calling the sendEmail function, at the top of the code you’ll extract all the form responses and then access a specific response.

The extracting is done using the getItemResponses function. Accessing a specific response, on the other hand, is done by calling the getResponse function on a variable holding an array of responses from a form submission.

This is how it all looks in code:

function sendEmailAfterFormSubmit() {
var form = FormApp.openById(‘TARGET_FORM_ID’);
var responsesCount = form.getResponses().length;
var responses = form.getResponses();
var response = responses[responsesCount-1];
var responseItems = response.getItemResponses();
var firstResponse = responseItems[0].getResponse();
// Email details
var email =recipient@example.com';
var subject = 'New Form Submission';
var body = 'A new form has been submitted. First question response: ' + firstResponse;
GmailApp.sendEmail(email, subject, body);

If you want to customize the email content further based on a form response, you can do so by accessing different parts of the responses array.

My form consisted of 3 questions:

What is your name?
What is your favorite color?
Please provide your feedback.
And to customize my email, I used the following code:

`function sendCustomEmailAfterFormSubmit() {
// Access the form responses from the event object
var form = FormApp.openById(‘TARGET_FORM_ID’);
var responsesCount = form.getResponses().length;
var responses = form.getResponses();
var response = responses[responsesCount-1];
var responseItems = response.getItemResponses();

// Extracting individual responses
var nameResponse = responseItems[0].getResponse(); // Response to the first question (name)
var colorResponse = responseItems[1].getResponse(); // Response to the second question (favorite color)
var feedbackResponse = responseItems[2].getResponse(); // Response to the third question (feedback)

// Email details
var recipient = 'recipient@example.com'; // Replace with the actual recipient's email
var subject = 'Thank You for Your Feedback';

// Customizing the email body with the form responses
var body = "Hello " + nameResponse + ",\n\n" +
"Thank you for submitting your feedback. " +
"We are glad to know that your favorite color is " + colorResponse + ". " +
"Here's the feedback we received from you:\n" +
"\"" + feedbackResponse + "\"\n\n" +
"We appreciate your input and will get back to you shortly.";

// Sending the customized email
GmailApp.sendEmail(recipient, subject, body);
}`

Limitations of sending with Google Apps Script
By this point in the article, you’re probably thinking, “Man, you can do a lot with Google Apps Script”. And yes, you’re right, but there are limitations.

Let me introduce you to the key ones!

Daily quota – daily quota limits are enforced by Google Apps Script on sending emails and these vary based on the account type (e.g., personal Gmail vs. Google Workspace). Along with the number of emails, these limits also extend to the number of recipients.
Execution time – limits are posed on the total execution time per day for scripts as well as individual script executions. For most accounts, 6 minutes is the maximum execution time per script.
Concurrent executions – the number of scripts that can execute concurrently is limited, affecting scripts designed to handle high volumes of requests or operations simultaneously.
URL fetch calls and external requests – the number of calls and the size of the request, as well as the response, are limited for scripts that make external network calls, such as ones to APIs and web services.
Script project and storage size – Google Apps Script has a maximum size limit for each script and the data stored by it when using various services within the platform (Properties Service, Cache Service, etc.).
Libraries and dependencies – per project, there is a limit on the number and the size of libraries used.
How to send emails with Google Apps Script and email API?
While sending through the Gmail service is pretty simple and effective, I like to have a bit more flexibility and features. For this, the option I gravitate to the most is using an email API.

In Google Apps Script, HTTP requests to external email APIs are made using the UrlFetchApp service. And I will now show you how to make such a request to a reliable email API offered by Mailtrap Email Sending.

With Mailtrap Email Sending, you get an email infrastructure with high deliverability rates by design. On top of that, you can expect each email you send through this sending solution to reach a recipient’s inbox in seconds.

*Limitations of sending with Google Apps Script
*

By this point in the article, you’re probably thinking, “Man, you can do a lot with Google Apps Script”. And yes, you’re right, but there are limitations.

Let me introduce you to the key ones!

  • Daily quota – daily quota limits are enforced by Google Apps Script on sending emails and these vary based on the account type (e.g., personal Gmail vs. Google Workspace). Along with the number of emails, these limits also extend to the number of recipients.

  • Execution time – limits are posed on the total execution time per day for scripts as well as individual script executions. For most accounts, 6 minutes is the maximum execution time per script.

  • Concurrent executions – the number of scripts that can execute concurrently is limited, affecting scripts designed to handle high volumes of requests or operations simultaneously.

  • URL fetch calls and external requests – the number of calls and the size of the request, as well as the response, are limited for scripts that make external network calls, such as ones to APIs and web services.

  • Script project and storage size – Google Apps Script has a maximum size limit for each script and the data stored by it when using various services within the platform (Properties Service, Cache Service, etc.).

  • Libraries and dependencies – per project, there is a limit on the number and the size of libraries used.

*How to send emails with Google Apps Script and email API?
*

Read the full article on the Mailtrap blog!

Top comments (0)