Send an Email with an Attachment

Apps Script lets you attach files to emails using GmailApp.sendEmail() with the attachments option. You can attach files from Google Drive, convert Google Sheets or Docs to PDF on the fly, or create in-memory blobs.

Attaching a File from Google Drive

function sendEmailWithDriveAttachment() { var file = DriveApp.getFileById("YOUR_FILE_ID"); var recipient = "[email protected]"; GmailApp.sendEmail( recipient, "Your Contract – Pro Plan", "Please find your contract attached.", { attachments: [file.getAs(MimeType.PDF)] } ); Logger.log("Email with attachment sent to " + recipient); }

Converting a Google Sheet to PDF and Attaching It

This is one of the most common patterns — exporting a sheet as a PDF and emailing it directly:

function sendSheetAsPDF() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheetId = ss.getSheetByName("Sales Tracker").getSheetId(); var url = "https://docs.google.com/spreadsheets/d/" + ss.getId() + "/export?format=pdf&gid=" + sheetId + "&portrait=true&fitw=true"; var token = ScriptApp.getOAuthToken(); var response = UrlFetchApp.fetch(url, { headers: { Authorization: "Bearer " + token } }); var pdfBlob = response.getBlob().setName("Sales Tracker – March 2024.pdf"); GmailApp.sendEmail( "[email protected]", "Sales Tracker – March 2024", "Please find the monthly sales tracker attached.", { attachments: [pdfBlob] } ); Logger.log("Sales Tracker PDF emailed to manager."); }

Sending Individual Customer Reports from Sheet Data

This example generates a plain-text summary for each closed customer and sends it as a .txt attachment:

function sendCustomerSummaries() { var sheet = SpreadsheetApp .getActiveSpreadsheet() .getSheetByName("Sales Tracker"); var data = sheet.getRange(2, 1, sheet.getLastRow() - 1, 8).getValues(); // Columns: [Customer Name, Email, Product, Amount, Region, Sales Rep, Status, Date] data.forEach(function(row) { var customerName = row[0]; var email = row[1]; var product = row[2]; var amount = row[3]; var region = row[4]; var salesRep = row[5]; var status = row[6]; if (status !== "Closed") return; var summaryText = [ "Acme Corp – Account Summary", "============================", "Customer: " + customerName, "Product: " + product, "Amount: $" + amount + "/month", "Region: " + region, "Account Rep: " + salesRep, "Status: " + status ].join("\n"); var blob = Utilities.newBlob(summaryText, "text/plain", customerName + " - Summary.txt"); GmailApp.sendEmail( email, "Your Acme Corp Account Summary", "Please find your account summary attached.", { attachments: [blob] } ); Logger.log("Summary sent to " + email); }); }

With the sample data, summaries are sent to [email protected] and [email protected]. Mark Chen is skipped.

Attaching Multiple Files

GmailApp.sendEmail(recipient, subject, body, { attachments: [ DriveApp.getFileById("CONTRACT_FILE_ID").getAs(MimeType.PDF), DriveApp.getFileById("INVOICE_FILE_ID").getAs(MimeType.PDF) ] });