However, when it comes to performing mass mailing, it can be quite challenging to personalize each email for every recipient.
This is where mail merge comes into play.
In this blog, we will discuss how to perform mail merge in Google Sheets and Google Docs using Google Apps Script.
In the script editor, create a new function and give it a name. This function will be used to perform the mail merge.
Step 4: Write the Google Apps Script Code
The following code can be used to perform mail merge in Google Sheets and Google Docs using Google Apps Script:
function sendEmails() { var sheet = SpreadsheetApp.getActiveSheet(); var startRow = 2; // First row of data to process var numRows = 10; // Number of rows to process var dataRange = sheet.getRange(startRow, 1, numRows, sheet.getLastColumn()) var data = dataRange.getValues(); var templateFile = DriveApp.getFileById('TEMPLATE_DOC_ID'); // replace with your template file ID var templateDoc = DocumentApp.openById(templateFile.getId()); for (var i = 0; i < data.length; ++i) { var row = data[i]; var recipientName = row[0]; var recipientEmail = row[1]; var copyDoc = templateDoc.makeCopy(); var copyId = copyDoc.getId(); var copyDocFile = DriveApp.getFileById(copyId); var copyDocFolder = DriveApp.getFolderById('FOLDER_ID'); // replace with your folder ID copyDocFolder.addFile(copyDocFile); var copyDocUrl = copyDocFile.getUrl(); var subject = 'Your Subject Here'; var body = 'Your email body text here'; var emailOptions = { htmlBody: body, attachments: [copyDoc.getAs(MimeType.PDF)], name: 'Automatic Emailer Script' } MailApp.sendEmail(recipientEmail, subject, body, emailOptions); copyDocFile.setTrashed(true); } }
The above code uses the SpreadsheetApp and DocumentApp services to read data from the Google Sheet and create a copy of the Google Docs template for each recipient.
It then replaces the placeholders in the copied document with actual data from the sheet, converts the document to a PDF, and sends an email to the recipient with the PDF as an attachment.
Make sure to replace 'TEMPLATE_DOC_ID' and 'FOLDER_ID' with the actual ID of your Google Docs template and folder, respectively. Also, customize the subject and body of the email as per your requirements.
Step 5: Run the Script