How to use Google Apps Script to send email with attachment

This example shows you how to send email from a Google Sheet with an attachment.

Suppose we have a Google Sheet with all the clients and their email addresses. We need to get a PDF form filled and signed by each of these clients. The plan is to send the PDF form as attachment to each client and then ask them to fill, sign and send it back.

Here is the Google Sheet.
client list google sheet

You can make a copy of the sample sheet here.

Add a menu item to the Google Sheet

First, let us add a menu item to the Google Sheet for this part of the automation.

do File → Save and close and re-open the Google Sheet.

You should now see the new Menu item.

Upload the file

The next step is to upload the PDF file to your Google Drive. Go to drive.google.com. You may want to create a new folder to keep the files. Then upload the file:

Give a unique name to the file. We will be using the name to fetch the file and attach to the email.

Create an email template

Let us now create an HTML file that will serve as the email template. Do File → New and select HTML.
This is a simple email template. You have to customize per your needs.

Sending the email

We have all the pieces ready; now we can compose and send the email.

Fetching the file and attaching the file is done by these lines:

getClientInfo() function gets the client details from the row. Then we use that client details in the email template and compose the email.

MailApp.sendEmail() function is used to send the email.

Next, we need a way to invoke this function. We had already added a menu item. Just update the function to get the current row to send the email to the client of that row.

Do File → Save. Go back to the Google Sheet and do Automation → send PDF Form.

It should send an email to the client in that row.

sample email

Send all emails in a single step

You may not want to send each email one-by-one. Here is the code to send all emails in a single step. All you have to do is iterate through each row and run the sendEmailWithAttachment() function.

See Also…

Leave a Reply 0 comments

Leave a Reply: