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 = '<h1>Hello!</h1>' +
'<p>This is an <strong>HTML</strong> email.</p>';
// Send the email with the HTML body
GmailApp.sendEmail(recipient, subject, '', {
htmlBody: htmlBody
});
}
Copy
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()
Copy
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
});
Copy
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
});
}
Copy
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]
});
}
Copy
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);
}
Copy
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);
}
Copy
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
});
}
Copy
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);
}
}
Copy
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.