This is the code I used (found online, not my own), but I can't figure out how to add an attachment to this code.
function sendEmails() {
// Load the spreadsheet data
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
const allData = sheet.getDataRange().getValues();
const headers = allData[0];
const rows = allData.slice(1);
// Helper function to detect column indices
const getColIndex = (headerName) => {
const index = headers.indexOf(headerName);
if (index === -1) throw new Error(`Header "${headerName}" not found.`);
return index;
};
// Detect column indices
const nameCol = getColIndex("Name");
const emailCol = getColIndex("Email");
const sentCol = getColIndex("Sent");
// Loop through the entire spreadsheet
rows.forEach((row, i) => {
const name = row[nameCol];
const email = row[emailCol];
const sent = row[sentCol];
// Skip rows that have been sent already
if (!email || sent) return;
// Send an email with a personalized subject and body
MailApp.sendEmail(
email,
`Submission received`,
`Dear ${name},\n\nThank you for your submission. We'll be in touch shortly.\n\nYours truly,\nJames`
);
// Log timestamp in the Sent column
sheet.getRange(i + 2, sentCol + 1).setValue(new Date());
});
}
I have changed the headers "email" and "name" to match the headers of my google sheet. And it worked.
The attachment is in my google drive and this is my latest try to add an attachment, this time not even an email got sent.
function sendEmails() {
// Load the spreadsheet data
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
const allData = sheet.getDataRange().getValues();
const headers = allData[0];
const rows = allData.slice(1);
// Helper function to detect column indices
const getColIndex = (headerName) => {
const index = headers.indexOf(headerName);
if (index === -1) throw new Error(`Header "${headerName}" not found.`);
return index;
};
// Detect column indices
const nameCol = getColIndex("Namn");
const emailCol = getColIndex("E-postadress");
const sentCol = getColIndex("Sent");
// Loop through the entire spreadsheet
rows.forEach((row, i) => {
const name = row[nameCol];
const email = row[emailCol];
const sent = row[sentCol];
// Skip rows that have been sent already
if (!email || sent) return;
// Send an email with a personalized subject and body
function sendEmails(){
const id = '1ezM-QiJ73Ry4xmNMdWHdC-4jXJ4gUHhB';
const sub = `Postpartum Checklist`
const body = `Dear ${name},\n\nSå härligt att du tar dina första steg mot en positiv postpartum upplevelse. Oavsett om det är din första eller fjärde gång, hoppas jag att du hittar lite trygghet i den här checklistan.\n\nLadda ner och skriv ut den, eller få ditt utskriven exemplar från mig om du valde att bli kontaktad för en första konsultation.\n\nMvh,\nLeila`
const att = DriveApp.getFileById(id);
MailApp.sendEmail(email,sub, body, att);
}
// Log timestamp in the Sent column
sheet.getRange(i + 2, sentCol + 1).setValue(new Date());
});
}