Reference Cell for Email Address - email

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());
}
}

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

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

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");
}
}
}

Send email when any value is input into first column Google Script

I'm looking to send an email to the recipient (clientEmail) when data is added to the first column of that specific row. The data in the first column would be a mix of numbers and letters. I've tried different methods using the following code but can never get it to send only when the value in the first column contains a value.
var EMAIL_DRAFTED = "EMAIL DRAFTED";
function draftMyEmails() {
var sheet = SpreadsheetApp.getActiveSheet(); // Use data from the active
sheet
var startRow = 2; // First row of data to process
var numRows = sheet.getLastRow() - 1; // Number of rows to process
var lastColumn = sheet.getLastColumn(); // Last column
var dataRange = sheet.getRange(startRow, 1, numRows, lastColumn) // Fetch the data range of the active sheet
var data = dataRange.getValues(); // Fetch values for each row in the range
// Work through each row in the spreadsheet
for (var i = 0; i < data.length; ++i) {
var row = data[i];
// Assign each row a variable
var clientName = row[1]; // Col B: Client name
var clientEmail = row[2]; // Col C: Client email
var message1 = row[3]; // Col D: First part of message
var message2 = row[4]; // Col E: Second part of message
var emailStatus = row[lastColumn - 1]; // Col F: Email Status
// Prevent from drafing duplicates and from drafting emails without a recipient
if (emailStatus !== EMAIL_DRAFTED && clientEmail) {
// Build the email message
var emailBody = '<p>Hi ' + clientName + ',<p>';
emailBody += '<p>' + message1 + ', your requested data, ' + message2 + ', is ready.<p>';
//Send the emaiil
MailApp.sendEmail(
clientEmail, // Recipient
'Here is your data', // Subject
'', // Body (plain text)
{
htmlBody: emailBody // Options: Body (HTML)
}
);
sheet.getRange(startRow + i, lastColumn).setValue(EMAIL_DRAFTED); // Update the last column with "EMAIL_DRAFTED"
SpreadsheetApp.flush(); // Make sure the last cell is updated right away
}
}
}
Start off by changing your for loop, know the difference between ++i and i++, in this case you'd want to use the latter. See: difference between ++i and i++.
for (var i = 0; i < data.length; i++) {
All you need to do after that is add a check in your if statement for the column in question. Note: you could define this separately like you've done for the other variables. I'll provide 2 examples and you can pick which you'd prefer to use, both will function the same.
//option 1
if (emailStatus !== EMAIL_DRAFTED && clientEmail && row[0]) {
//option 2
var checkData = row[0];
if (emailStatus !== EMAIL_DRAFTED && clientEmail && checkData) {
In the end your code should look something like this:
var EMAIL_DRAFTED = "EMAIL DRAFTED";
function draftMyEmails() {
var sheet = SpreadsheetApp.getActiveSheet(); // Use data from the active sheet
var startRow = 2; // First row of data to process
var numRows = sheet.getLastRow() - 1; // Number of rows to process
var lastColumn = sheet.getLastColumn(); // Last column
var dataRange = sheet.getRange(startRow, 1, numRows, lastColumn); // Fetch the data range of the active sheet
var data = dataRange.getValues(); // Fetch values for each row in the range
// Work through each row in the spreadsheet
for (var i = 0; i < data.length; i++) {
var row = data[i];
// Assign each row a variable
var clientName = row[1]; // Col B: Client name
var clientEmail = row[2]; // Col C: Client email
var message1 = row[3]; // Col D: First part of message
var message2 = row[4]; // Col E: Second part of message
var emailStatus = row[lastColumn - 1]; // Col F: Email Status
// Prevent from drafing duplicates and from drafting emails without a recipient
if (emailStatus !== EMAIL_DRAFTED && clientEmail && row[0]) {
// Build the email message
var emailBody = '<p>Hi ' + clientName + ',<p>';
emailBody += '<p>' + message1 + ', your requested data, ' + message2 + ', is ready.<p>';
//Send the emaiil
MailApp.sendEmail(
clientEmail, // Recipient
'Here is your data', // Subject
'', // Body (plain text)
{
htmlBody: emailBody // Options: Body (HTML)
}
);
sheet.getRange(startRow + i, lastColumn).setValue(EMAIL_DRAFTED); // Update the last column with "EMAIL_DRAFTED"
SpreadsheetApp.flush(); // Make sure the last cell is updated right away
}
}
}

Sending multiple attachments using Google Spreadsheet and Google Script

Im trying to send multiple attachments using Google Spreadsheet but I get the following error "Cannot retrieve the next object: iterator has reached the end."
It does work, because it sends the e-mail to the first email-address in the list, but it fails for the second one.
I have seen similar questions here about it, but no solutions resolve my issue.
Here is the script:
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 1;
var numRows = 2;
var dataRange = sheet.getRange(startRow, 1, numRows, 2);
var file1 = DriveApp.getFilesByName('Maandbrief December.pdf');
var file2 = DriveApp.getFilesByName('Weekendbrief 7-9 december.pdf');
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
var emailAddress = row[0];
var message = row[1];
var subject = "Maandbrief December en weekendbrief 7-9 december";
MailApp.sendEmail({to:emailAddress, subject:subject, body:message, attachments: [file1.next(), file2.next()]})
}}
Thank you for your help.
Try this:
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 1;
var numRows = 2;
var dataRange = sheet.getRange(startRow, 1, numRows, 2);
var files1 = DriveApp.getFilesByName('Maandbrief December.pdf');
while(files1.hasNext()){var file1=files1.next();}
var files2 = DriveApp.getFilesByName('Weekendbrief 7-9 december.pdf');
while(files2.hasNext()){var file2=files2.next();}
var data = dataRange.getValues();
for (var i=0;i<data.length;i++) {
var row = data[i];
var emailAddress = row[0];
var message = row[1];
var subject = "Maandbrief December en weekendbrief 7-9 december";
MailApp.sendEmail({to:emailAddress, subject:subject, body:message, attachments: [file1, file2]})
}
}
or this:
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 1;
var numRows = 2;
var dataRange = sheet.getRange(startRow, 1, numRows, 2);
var n1=0;
var n2=0;
var files1 = DriveApp.getFilesByName('Maandbrief December.pdf');
while(files1.hasNext()){var file1=files1.next();n1++;}
var files2 = DriveApp.getFilesByName('Weekendbrief 7-9 december.pdf');
while(files2.hasNext()){var file2=files2.next();n2++}
var data = dataRange.getValues();
if(n1==1 && n2==1){
for (var i=0;i<data.length;i++) {
var row = data[i];
var emailAddress = row[0];
var message = row[1];
var subject = "Maandbrief December en weekendbrief 7-9 december";
MailApp.sendEmail({to:emailAddress, subject:subject, body:message, attachments: [file1, file2]});
}
}else{
throw('More than one file with given name.');
}
}

Google Sheet sends email from list when cell condition met

I'm still very new to scripting and can't work out why the below script doesn't work
function sendReturnEmail(event) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var row = sheet.getActiveRange().getRow();
var cellvalue = ss.getActiveCell().getValue().toString();
if(event.range.getA1Notation().indexOf("K") && sheet.getRange("K" + row).getDisplayValue() == "Approved")
{
var rowVals = getActiveRowValues(sheet);
var aliases = GmailApp.getAliases();
var to = rowVals.user;
var subject = "Allocation request approved";
var body = "Your allocation request of " +rowVals.quantity + " cases on " + rowVals.date + " from " + rowVals.depot + " has been approved. <br \> <br \>"
+ "Regards, <br \> <br \>" +rowVals.analyst + "<br \> CPF Team";
Logger.log(aliases);
GmailApp.sendEmail(to,subject,body,
{from: aliases[0]})
;
}}
function getActiveRowValues(sheet){
var cellRow = sheet.getActiveRange().getRow();
// get depot value
var depotCell = sheet.getRange("E" + cellRow);
var depot = depotCell.getDisplayValue();
// get date value
var dateCell = sheet.getRange("F" + cellRow);
var date = dateCell.getDisplayValue();
// get quantity value
var quantCell = sheet.getRange("G" + cellRow);
var quant = quantCell.getDisplayValue();
// return an object with your values
var analystCell = sheet.getRange("J" + cellRow);
var analyst = analystCell.getDisplayValue();
var userCell = sheet.getRange("O" + cellRow);
var user = userCell.getDisplayValue();
return {
depot: depot,
date: date,
quantity: quant,
analyst: analyst,
user: user
} }
}
The sheet is question has several scripts running in it, one of them being this:
function onEdit() {
var s = SpreadsheetApp.getActiveSheet();
if( s.getName() == "Allocation Requests" ) { //checks that we're on the correct sheet
var r = s.getActiveCell();
if( r.getColumn() == 2) { //checks the column
var nextCell = r.offset(0, 13);
nextCell.setValue(Session.getEffectiveUser());
}
}
I now want the sheet to send an email to the email address captured using the above script (which works fine) when the corresponding cell in column K is manually changed to "Approved."
Can anyone see what I'm doing wrong. I get no errors when it runs, but I'm not getting an email. I've searched other questions but none have helped. Many thanks in advance.