function sendEmailWithAttachments() {
var spreadsheetId = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheetName = "Sheet1"; // Change this to the name of the sheet you want to export
var url = "https://docs.google.com/spreadsheets/d/" + spreadsheetId + "/export" + "?format=xlsx&" + "gid=" + SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName).getSheetId();
var params = { method: "GET", headers: { "authorization": "Bearer " + ScriptApp.getOAuthToken() } };
var blob = UrlFetchApp.fetch(url, params).getBlob().setName(sheetName + ".xlsx");
var message = {
to: "email@domain.com",
cc: "email@domain.com",
subject: "Email Subject",
body: "Email Body",
name: "Your Name",
attachments: [blob]
};
MailApp.sendEmail(message);
}
This code sends an email with a single attachment, which is the exported contents of a specified sheet in the active spreadsheet. To send multiple attachments, you can use the following code:
function sendEmailWithMultipleAttachments() {
var spreadsheetId = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheetNames = ["Sheet1", "Sheet2", "Sheet3"]; // Change this to the names of the sheets you want to export
var attachments = [];
sheetNames.forEach(function(sheetName) {
var url = "https://docs.google.com/spreadsheets/d/" + spreadsheetId + "/export" + "?format=xlsx&" + "gid=" + SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName).getSheetId();
var params = { method: "GET", headers: { "authorization": "Bearer " + ScriptApp.getOAuthToken() } };
var blob = UrlFetchApp.fetch(url, params).getBlob().setName(sheetName + ".xlsx");
attachments.push(blob);
});
var message = {
to: "email@domain.com",
cc: "email@domain.com",
subject: "Email Subject",
body: "Email Body",
name: "Your Name",
attachments: attachments
};
MailApp.sendEmail(message);
}
This code sends an email with multiple attachments, which are the exported contents of multiple sheets in the active spreadsheet.
You can also use a trigger to send the email with attachments automatically on a schedule. For example, the following code sends an email with attachments every day at 8 AM:
function createTrigger() {
ScriptApp.newTrigger("sendEmailWithAttachments")
.timeBased()
.everyDays(1)
.atHour(8)
.create();
}
Be sure to replace "sendEmailWithAttachments" with the name of the function you want to run.