send mail with attachment in each row on google app script - google-apps-script

I use attachment in each cell to send mail auto.
Note:
column 0: Firstname Column 4: Email Address Colum 5: Year Column 6: File Attachment.
var EMAIL_SENT = 'EMAIL_SENT';
//Sends non-duplicate emails with data from the current spreadsheet.
function autosendEmails() {
var ws = SpreadsheetApp.openById('Your Sheet Id');
var sheet= ws.getSheetByName('Mail Merge');
var startRow = 2; // First row of data to process
var numRows = ws.getLastRow(); // Number of rows to process // Fetch the range of cells E2:H3
var dataRange = sheet.getRange(startRow, 1, numRows, 7);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
// var FileID = DriveApp.getFileById('Your File Id')
for (var i = 0; i < data.length; i++) {
var row = data[i]; var emailAddress = row[4]; // First column
var Subjectmail ="Test mail"
var bodyemail = "Dear"
var pdfname = row[6];
var emailSent = row[7]; // Four column
if (emailSent !== EMAIL_SENT) {
// Prevents sending duplicates
var subject = 'Test mail';
MailApp.sendEmail(emailAddress, Subjectmail, bodyemail, {attachments: pdfname});
sheet.getRange(startRow + i, 8).setValue(EMAIL_SENT); // Make sure the cell is updated right away in case the script is interrupted SpreadsheetApp.flush();
}
}
}

Taking into consideration you're retrieving the file name from var pdfname = row[6]; , then what you must do to attach the file to your mail and send it, it's to retrieve the actual file from your drive and putting it into an array as I did in this example:
// Inside your function, just change this line
function autosendEmails() {
...
MailApp.sendEmail(emailAddress, Subjectmail, bodyemail, {
attachments: buildAttachment(pdfname) // Call this function to be able to send an attachment file
});
...
}
// Add this function to your code
function buildAttachment(pdfname){
// Initialize the array
var fileArr = [];
// Get the file form your drive
var getMyFile = DriveApp.getFilesByName(pdfname).next();
// build an array
fileArr.push(getMyFile);
// return the file within an array
return fileArr;
}
Reference
This post could help you, too.
Docs
Class MailApp
Class DriveApp

This might work better for you:
Read the comments for explanation.
function autosendEmails() {
var ws = SpreadsheetApp.openById('Your Sheet Id');
var sheet= ws.getSheetByName('Mail Merge');
var startRow = 2; // First row of data to process
var dataRange = sheet.getRange(startRow, 1, sheet.getLastRow()-1,sheet.getLastColumn());//you were missing your last column and you were grabbing an empty row and the end of your list because the third parameter is the number of rows in the data not the number of rows in the sheet.
var data=dataRange.getValues();
for (var i=0;i<data.length;i++) {
var row=data[i];
var emailAddress = row[4]; // First column
var Subjectmail ="Test mail"
var bodyemail = "Dear"
var pdfname = row[6];
var emailSent = row[7]; // Four column
if (emailSent !== "EMAIL_SENT") {
MailApp.sendEmail(emailAddress, Subjectmail, bodyemail, {attachments: ["an array of files"]});//attachments should be an array of files not an array of filenames
sheet.getRange(startRow + i, 8).setValue(EMAIL_SENT);
}
}
}

This is an example I normally use
function SendMailFC() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
var message ="HELLO"
for (var i = 2; i <= 3; i++) {
var row = values[i];
var mail = row[7];
var name = row[4].substring(0,row[4].indexOf(" ",row[4].indexOf(" ")+1));
var company = row[1].substring(0,row[1].indexOf(","));
var Greeting = 'Hello ' + name+',<br><br>';
var stat = row[10];
var subject = "SUBJECT";
if(stat){
GmailApp.sendEmail(FROM, subject, "", {htmlBody: '<html>'+greeting+message+'</html>'} );
}
}

Related

how can you use a gmail script to attach more than one image at a time. below is an example of a working script to attach one image

I'm trying to set up a Google Sheet with some data to email images. I have the code working below to send a single image attachment but I would like to send more than one image at a time if it is possible. How could I change the code below to work with multiple images?
function emailImage(){
var EMAIL_SENT = "EMAIL_SENT";
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2;
var numRows = sheet.getLastRow();
// Fetch the range of cells
var dataRange = sheet.getRange(startRow, 1, numRows, 5)
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var emailAddress = row[0]; // First column
var subject = row[1]; // Second column
var message = row[2]; // Third column
var image = UrlFetchApp.fetch(row[3]).getBlob(); // Fourth column
var emailSent = row[4]; // Fifth column
if (emailSent != EMAIL_SENT) { // Prevents sending duplicates
MailApp.sendEmail(emailAddress, subject, message, {attachments: [image]});
sheet.getRange(startRow + i, 5).setValue(EMAIL_SENT);
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
}
This is just a snippet to help you along:
var image1 = UrlFetchApp.fetch(row[3]).getBlob();
var image2 = 'However you wish to get it';
var options = { attachments: [] };
option.attachments.push(image1);
option.attachments.push(image2);
MailApp.sendEmail(emailAddress, subject, message, options);
With the help of #MetaMan I was finally able to get this working....
function emailImage(){
var EMAIL_SENT = "EMAIL_SENT";
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2;
var numRows = sheet.getLastRow();
// Fetch the range of cells
var dataRange = sheet.getRange(startRow, 1, numRows, 6)
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var emailAddress = row[0]; // First column
var subject = row[1]; // Second column
var message = row[2]; // Third column
var image1 = UrlFetchApp.fetch(row[3]).getBlob();
var image2 = UrlFetchApp.fetch(row[4]).getBlob();
var emailSent = row[5]; // Fifth column
if (emailSent != EMAIL_SENT) { // Prevents sending duplicates
MailApp.sendEmail(emailAddress, subject, message, {attachments: [image1, image2]});
sheet.getRange(startRow + i, 6).setValue(EMAIL_SENT);
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
}

GmailApp.sendEmail syntax with Alias

I wrote a piece of code to send automatically emails from a list in google sheet (which works), but when I want to add an Alias email, I cannot seem to make it work. Any help would be greatly appreciated. Here is the code:
// This constant is written in column C for rows for which an email
// has been sent successfully.
var EMAIL_SENT = 'EMAIL_SENT';
/**
* Sends non-duplicate emails with data from the current spreadsheet.
*/
function sendEmails2() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows =3; // Number of rows to process
// Fetch the range of cells A2:E3
var dataRange = sheet.getRange(startRow, 1, numRows, 5);
// add the attachments variables
var contents = DriveApp.getFolderById("").getFiles();
var attachments = [];
while (contents.hasNext()) {
var file = contents.next();
{
attachments.push(file);
}
}
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var emailAddress = row[0]; // First column
var message = row[1]; // Second column
var cuota = row[3]; // Fourth column
var emailSent = row[4]; // Fifth column
if (emailSent !== EMAIL_SENT && emailAddress !== "#N/A" && cuota !== 0) {
// Prevents sending duplicates, no emails and parents that have already paid
var subject = 'Recordatorio de cuota';
//Do not forget to remove EMAIL_SENT once done otherwise it won't work a 2nd time
var me = Session.getActiveUser().getEmail();
var aliases = GmailApp.getAliases()
GmailApp.sendEmail(emailAddress,subject, message, {attachments: attachments},
{from: aliases[0]};
sheet.getRange(startRow + i, 5).setValue(EMAIL_SENT);
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
}
Try this:
function sendEmails2() {
var ss=SpreadsheetApp.getActive();
var sh=SpreadsheetApp.getActiveSheet();
var sr=2;
var numRows=3;
var rg=sh.getRange(sr,1,sh.getLastRow()-sr+1,sh.getLastColumn());
var contents=DriveApp.getFolderById("*****FolderId******").getFiles();
var attachments=[];
while (contents.hasNext()) {
var file=contents.next();
attachments.push(file);
}
var data=rg.getValues();
for (var i=0; i < data.length; ++i) {
var row=data[i];
var emailAddress=row[0];
var message=row[1];
var cuota=row[3];
var emailSent=row[4];
if (emailSent!="EMAIL_SENT" && emailAddress!="#N/A" && cuota!=0) {
var subject='Recordatorio de cuota';
var me=Session.getActiveUser().getEmail();
var aliases=GmailApp.getAliases()
GmailApp.sendEmail(emailAddress,subject, message,{attachments:attachments,from:aliases[0]});
sh.getRange(sr+i,5).setValue("EMAIL_SENT");
}
}
}

How to send email if cell date equals today

I am trying to create a Google Apps Script that works with a spreadsheet to send out an email if certain criteria is met. Specifically to send out an email if Column C equals today & column A equals false.
Link to the spreadsheet:
https://docs.google.com/spreadsheets/d/1kULWOMtZaay6PcgF5XTwVoJnKPo7JSA_AK50J8RNYzk/edit?usp=sharing
I was able to set this up to that the spreadsheet handles most of the work. Column D checks for the date, and that column A is checked and then the script will send when column D reads TRUE. I am wondering if I can have the Google Apps Script check for today's date, instead of the spreadsheet.
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 50; // Number of rows to process
var numOfColumns = sheet.getLastColumn();
// Fetch the range of cells
var dataRange = sheet.getRange(startRow, 1, numRows, numOfColumns);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
var sendTrigger = "";
var i = 0;
for (i=0;i<data.length;i++) {
var row = data[i];
var emailAddress = row[4]; // fifth column
var message = row[5]; // sixth column
sendTrigger = row[3];
if (sendTrigger == 1) {
var subject = ("This is a test of the send email function");
MailApp.sendEmail(emailAddress, subject, message);
};
};
};
I want the script to check column A and column C and send out an email if Column A equals FALSE and column C equals TODAY
Try this:
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 50; // Number of rows to process
var numOfColumns = sheet.getLastColumn();
var dataRange = sheet.getRange(startRow, 1, numRows, numOfColumns);
var data = dataRange.getValues();
var sendTrigger = "";
var dt=new Date();
var dv=new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).valueOf();
for (var i=0;i<data.length;i++) {
var row = data[i];
var emailAddress = row[4]; // fifth column
var message = row[5]; // sixth column
var d=new Date(row[2]);
if (!row[0] && new Date(d.getFullYear(),d.getMonth(),d.getDate()).valueOf()==dv) {
var subject = ("This is a test of the send email function");
MailApp.sendEmail(emailAddress, subject, message);
}
}
}

Trouble with simple google script send email with cc

Please someone help me with this code.I need to add cc with different emails in 1 column.
Hope someone can help me.
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 20; // Number of rows to process
// Fetch the range of cells A2:C3
var dataRange = sheet.getRange(startRow, 1, numRows, 2)
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
var emailAddress = row[0]; // First column
var message = row[1]; // Second column
var subject = "EXCEPTION REPORT";
MailApp.sendEmail(emailAddress, subject, message);
}
}
Using the options parameter of .sendEmail as in the reference.
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 20; // Number of rows to process
// Fetch the range of cells A2:C3
var dataRange = sheet.getRange(startRow, 1, numRows, 2)
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
var emailAddress = row[0]; // First column
var ccAddress = row[--index of cc column--];
var message = row[1]; // Second column
var subject = "EXCEPTION REPORT";
MailApp.sendEmail(emailAddress, subject, message, {cc : ccAddress});
}
}

Gmail app send email with multiple attachments

I would like to learn tosend bulk google mails with attachments using a spreadsheet.
In a spreadsheet, i have put the email address, the content template, and the attachments urls.
Here is what I found as code that I tried to use for my purpose :
var EMAIL_SENT = "EMAIL_SENT";
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2;
var numRows = 5;
var blobs = [];
var dataRange = sheet.getRange(startRow, 1, numRows, 5)
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var emailAddress = row[2]; // 3rd column
var subject = "Attachments";
var message = row[4]; // 5th column
var attachments = row[3]; // Fourth column
var emailSent = row[0]; // 1st column
if (emailSent != EMAIL_SENT) {
GmailApp.sendEmail(emailAddress, subject, message, attachments);
sheet.getRange(startRow + i, 1).setValue(EMAIL_SENT);
SpreadsheetApp.flush();
}
}
}
When I tried lunching it, the email was sent but without attachments.
Please help me.
Many thanks in advance.
Your not stating what attachments to send. I see your calling something within the spreadsheet but not the attachment.
Try using something like this
var file = DriveApp.getFilesByName('attacheddoc.pdf');
if (file.hasNext()) {
MailApp.sendEmail(emailAddress, subject, message, {
attachments: [file.next().getAs(attacheddoc.PDF)],
name: 'Attached Documents'
}
So your code should look like
var EMAIL_SENT = "EMAIL_SENT";
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2;
var numRows = 5;
var blobs = [];
var dataRange = sheet.getRange(startRow, 1, numRows, 5)
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var emailAddress = row[2]; // 3rd column
var subject = "Attachments";
var message = row[4]; // 5th column
var attachments = row[3]; // Fourth column
var emailSent = row[0]; // 1st column
if (emailSent != EMAIL_SENT) {
var file = DriveApp.getFilesByName(attachments.pdf');
if (file.hasNext()) {
MailApp.sendEmail(emailAddress, subject, message, {
attachments: [file.next().getAs(attachments+'.PDF')],
name: 'Attached Documents'
}
}
}
}
Hopefully that works for you. Would require some tinkering. However, I can't really do that for you without seeing the sheet. If it works +1?? :)