I'm trying to send an automated anniversary list. my code returns no errors but is sending no emails - email

function sendAnniversaryCampaing(){
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1FkKtSpvwecDEc6of2Nh37ud3qGgcNaK253S7jd7KqB0/edit#gid=0");// Sheet Url
var sheet = ss.getSheetByName("Sheet1");// Make Sure Sheet name matches at the bottom
var templateId = '157YoH_ngoESR-pwNUXfFj0dUwDYXBqOd6RCgB_cJVsQ';// the template doc with placeholders
var cDate = new Date(); //Present Day,
for(var i =2 ;i<=sheet.getLastRow(); i++){
var anDate = sheet.getRange(i,4).getValue(); // Date from SpreadSheet
if(cDate.getDate()==anDate.getDate()){
if(cDate.getMonth()==anDate.getMonth()){
var name = sheet.getRange(i,2).getValue();
var toMail= sheet.getRange(i,3).getValue();
sendMail(sheet,templateId,name,toMail);//sheet doesn't appear to be used in sendMail() Edited by Cooper.
sheet.getRange(i,5).setValue("Anniversary email sent");
}
}
}
}
function sendMail(sheet,templateId,name,toMail){
var docId = DriveApp.getFileById(templateId).makeCopy('temp').getId();
var doc = DocumentApp.openById(docId);// the temp copy
var body = doc.getBody();
body.replaceText('#name#',name);// update the temp doc
doc.saveAndClose();// save changes before conversion
var url = "https://docs.google.com/feeds/download/documents/export/Export?id="+docId+"&exportFormat=html";
var param = {
method : "get",
headers : {"Authorization": "Bearer" + ScriptApp.getOAuthToken()}
};
var htmlBody = UrlFetchApp.fetch(url,param).getContentText();
var trashed = DriveApp.getFileById(docId).setTrashed(true);// delete temp copy
MailApp.sendEmail(toMail,'Anniversary Campaing'+name,' ' ,{htmlBody : htmlBody});// send to myself to test
}

Try this:
function sendAnniversaryCampaing(){
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1FkKtSpvwecDEc6of2Nh37ud3qGgcNaK253S7jd7KqB0/edit#gid=0");// Sheet Url
var sheet = ss.getSheetByName("Sheet1");// Make Sure Sheet name matches at the bottom
var templateId = '157YoH_ngoESR-pwNUXfFj0dUwDYXBqOd6RCgB_cJVsQ';// the template doc with placeholders
var cDate = new Date().valueOf(); //Present Day,
for(var i=2;i<=sheet.getLastRow(); i++){
var anDate=new Date(sheet.getRange(i,4).getValue()).valueOf(); // Date from SpreadSheet
if(cDate==anDate){
var name=sheet.getRange(i,2).getValue();
var toMail= sheet.getRange(i,3).getValue();
sendMail(sheet,templateId,name,toMail);
sheet.getRange(i,5).setValue("Anniversary email sent");
}
}
}

Related

BCC doesn't seem to function as an option of sendEmail - name and replyTo work though

function myFunction() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Welcome");
var targetSheet = ss.getSheetByName("Done");
var startRow = 2;
var lr = sheet.getLastRow();
var dataRange = sheet.getRange(startRow, 1, lr-1, 6);
var data = dataRange.getValues();
var colNumber = sheet.getLastColumn()-1;
var delRows = [];
for (var i = 0; i < data.length; i++) {
var row = data[i];
var id = row[0];
var emailAddress = row[1];
var date = row[2];
var city = row[3];
var bccmail = row[6];
var Sender = 'XXXXXX';
var reply = 'xxxxxx#xxxxxxx.com';
if (emailAddress.match('#') === null){
continue;
};
var subject = row[4];
var message = "Hey " + id + ", welcome in the team " + row[5];
MailApp.sendEmail(emailAddress, subject, message, {bcc: bccmail,name: Sender,replyTo: reply});
var targetRange = targetSheet.getRange(targetSheet.getLastRow()+1, 1, 1, colNumber);
var sourceRange = sheet.getRange(i+startRow, 1, 1, colNumber);
sourceRange.copyTo(targetRange);
delRows.push(i+startRow);
}
delRows.reverse().forEach(ri=>{sheet.deleteRow(ri)});
Almost all the script works fine. When it comes to sendEmail, I have tried to follow these guidelines and use sendEmail(recipient, subject, body, options). 2 out of 3 options work fine but BCC doesn't work at the moment. Do you know what I am doing wrong? Can BCC be a variable?
The problem is in this line:
var bccmail = row[6];
dataRange is defined as a range with only 6 columns. data is a 2D array with the values of dataRange. row is a 1D array with a single row of data. JavaScript array indexes only start at 0, so the values are in row[0] to row[5].
Please check your sheet in which column does the bcc string is defined and count the index from 0.
Reference:
Arrays in JavaScript

Macros to import multi-column data from Google spreadsheets to auto trigger mails

How to use macros to import multi-column data from Google spreadsheets to auto trigger mails using sendEmails ? I tried tweaking the code given in google for one column containing a single alphabetic message.
function sendEmails()
{ var sheet = SpreadsheetApp.getActiveSheet(); var startColumn = 2; var numColumns = 6; var dataRange = sheet.getRange(startColumn, 1, numColumns, 4); var data = dataRange.getValues(); for (var i in data)
{ var Column = data[i]; var emailAddress = Column[0]; var Sl_No = Column[1]; var Insured_Name =Column[2]; var Policy_No = Column[3]; var subject = ('Sending emails from a Spreadsheet'); MailApp.sendEmail(emailAddress, subject, (Sl_No,Insured_Name,Policy_No)); } } –

Reference Cell for Email Address

First code is what I am currently using, I am trying to get my email address to reference in a cell. I've found another script that does this but when I try to combine them, it doesn't work.
function getGoogleSpreadsheetAsExcel(){
try {
var ss = SpreadsheetApp.getActive();
var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key="
+ ss.getId() + "&exportFormat=xlsx";
var params = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var blob = UrlFetchApp.fetch(url, params).getBlob();
blob.setName(ss.getName() + ".xlsx");
MailApp.sendEmail("Email Address Here", "Subject Here", "Body of Email
Here", {attachments: [blob]});
} catch (f) {
Logger.log(f.toString());
}
}
And trying to combine this to it to reference cells for me instead of edited the script.
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
SpreadsheetApp.setActiveSheet(sheet.getSheetByName('Email Test'))
var startRow = 2; // First row of data to process
var numRows = 2; // Number of rows to process
// Fetch the range of cells A2:B3
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 = "Sending emails from a Spreadsheet";
MailApp.sendEmail(emailAddress, subject, message);
}
}
Again both work on there own, but wont work when combined.
This is what I have compiled and it does send the email and attachement, but just to myself, no other recipients. Needing at least it to go to 6 other people at once.
function getGoogleSpreadsheetAsExcel(){
try {
var ss = SpreadsheetApp.getActive();
var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key="
+ ss.getId() + "&exportFormat=xlsx";
var params = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var blob = UrlFetchApp.fetch(url, params).getBlob();
blob.setName(ss.getName() + ".xlsx");
var sheet = SpreadsheetApp.getActiveSpreadsheet();
SpreadsheetApp.setActiveSheet(sheet.getSheetByName('Email Test'))
var startRow = 2; // First row of data to process
var numRows = 2; // Number of rows to process
// Fetch the range of cells A2:B3
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 = "Sending emails from a Spreadsheet";
MailApp.sendEmail(emailAddress, subject, message, {attachments: [blob]});
}
}
catch (f) {
Logger.log(f.toString());
}
}

New OAuth2 needed to run script

I have been using this script to send google-spreadsheet to my e-mail when modified. Can anybody help to replace the authentication section with an OAuth2 for Apps Script. OAuth 1.0 support was deprecated in 2012 and is scheduled to be shut down on April 20, 2015.
Thanks.
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [ {name: "Send Email", functionName: "sendEmail"}];
ss.addMenu("Scripts", menuEntries);
};
function sendEmail() {
var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheetName = SpreadsheetApp.getActiveSpreadsheet().getName();
//var email = Session.getUser().getEmail();
var email = Session.getEffectiveUser();
var subject = "this is my subject";
var body = "this is my body :)";
var oauthConfig = UrlFetchApp.addOAuthService("google");
oauthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oauthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope=https://spreadsheets.google.com/feeds/");
oauthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oauthConfig.setConsumerKey("anonymous");
oauthConfig.setConsumerSecret("anonymous");
var requestData = {"method": "GET", "oAuthServiceName": "google", "oAuthUseToken": "always"};
var url = "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key="
+ ssID + "&gid=0&portrait=true" +"&exportFormat=xls";
var result = UrlFetchApp.fetch(url , requestData);
var contents = result.getContent();
MailApp.sendEmail(email,subject ,body, {attachments:[{fileName:sheetName+".xls", content:contents, mimeType:"application//xls"}]});
};
This is an easy fix. The fetch requests requires a scope allowing drive access. You can force Apps Script to add this scope by making a call to DriveApp. Then in your fetch you add the users OAuth token to the header of the call.
function onlyToAddTheDriveScope(){
DriveApp.getRootFolder()
}
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [ {name: "Send Email", functionName: "sendEmail"}];
ss.addMenu("Scripts", menuEntries);
};
function sendEmail() {
var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheetName = SpreadsheetApp.getActiveSpreadsheet().getName();
//var email = Session.getUser().getEmail();
var email = Session.getEffectiveUser();
var subject = "this is my subject";
var body = "this is my body :)";
var requestData = {"method": "GET",
"headers":{"Authorization":"Bearer "+ScriptApp.getOAuthToken()}
};
var url = "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key="
+ ssID + "&gid=0&portrait=true" +"&exportFormat=xls";
var result = UrlFetchApp.fetch(url , requestData);
var contents = result.getContent();
MailApp.sendEmail(email,subject ,body, {attachments:[{fileName:sheetName+".xls", content:contents, mimeType:"application//xls"}]});
};

Email a reminder based on the status of a cell Google apps script

I am attempting to set a simple reminder email to a technician to remind when a routine service is due. I have a 2d array and code that works, but it only sends 1 email, which is the lowest row.
I'm kinda new to this, but I would like it to run through each row and send a reminder for every overdue.
Any help appreciated.
This is what I have now:
function Email_Reminder()
{;
var sheet = SpreadsheetApp.getActiveSheet();
statusArray = sheet.getDataRange().getValues();
status = "overdue";
for (i=3;i < statusArray.length;i++){
if (status == statusArray[i][6]) {
var customer = statusArray[i][0];
}
}
var email = "djens12#gmail.com"
var subject = "Reminder";
var body = "This is a reminder that the service is overdue for " +customer+ "";
MailApp.sendEmail(email,subject,body,{NoReply : true});
}
thanks
Just move your MailApp.sendEmail() inside your for loop
function Email_Reminder()
{;
var sheet = SpreadsheetApp.getActiveSheet();
statusArray = sheet.getDataRange().getValues();
status = "overdue";
var email = "djens12#gmail.com"
var subject = "Reminder";
for (i=3;i < statusArray.length;i++){
if (status == statusArray[i][6]) {
var customer = statusArray[i][0];
var body = "This is a reminder that the service is overdue for " +customer+ "";
MailApp.sendEmail(email,subject,body,{NoReply : true});
}
}
}