I'm trying to send an email to multiple email addresses that can be found in a single cell separated by commas. I have done this before with gmail.app and it worked perfectly but I am trying to do it now using MailApp and I get an error saying the email is invalid.
Here is the code:
function mail() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var responses = ss.getSheetByName("referencias");
var mail = ss.getSheetByName("MAILS");
var mailok = mail.getRange(1,1).getValues();
var active_range = responses.getActiveRange();
var cambio = responses.getRange(active_range.getRowIndex(), 5).getValue();
var nuevo = responses.getRange(3, 11).getValue();
var cancelados = responses.getRange(3, 12).getValue();
var fecha =responses.getRange(3, 8).getValue();
var date = Utilities.formatDate(fecha, "GMT+2", "dd/MM/YYYY")
var message = {
to: "email here",
subject: "CAMBIOS REFERENCIAS Y DROPS: Resumen refes canceladas/añadidas",
body:"Los siguientes modelos fueron modificados en el Master Doc ayer fecha " +date +".\n\n" + "Refes añadidas:" + nuevo + "\n\nRefes canceladas:"+ cancelados+ "\n\nCualquier consulta podéis contestar a este mail."+"\n\n Además, encontraréis adjunto un PDF con una tabla resumen de los cambios de drops."+"\n\nArchivo: https://docs.google.com/spreadsheets/d//edit#gid=1098522138",
attachments: [SpreadsheetApp.getActiveSpreadsheet().getAs(MimeType.PDF).setName("Tabla")]
}
MailApp.sendEmail(message);
}
How can I send this email to many recipients at the same time? This email will be sent automatically everyday and ideally I would like it to be sent in a thread, however I have to fix this first before I try to do that.
If there is any missing information or confusion just let me know!
Issue:
Range.getValues() returns a 2D array, even if the range is a single cell.
If you want to return the value of a single cell, consider using Range.getValue() instead.
Solutions:
As suggested in comments, either change this line:
to: "email here",
To this one:
to: mailok[0][0],
Or, alternatively, these ones:
var mailok = mail.getRange(1,1).getValues();
// ...
to: "email here",
To these ones:
var mailok = mail.getRange(1,1).getValue();
// ...
to: mailok,
Related
Using script I replaced body txt in a copied doc. I want to get that doc id and send that via email automatically after doc was created. Not sure if its possible but my current code is below. Please help.
var templateFile = DriveApp.getFileById("1baIoahNT9YJ84mnUcp1pyWR0U5v235z29vPCkiv4rIc");
var templateResponseFolder = DriveApp.getFolderById("1mmFKjNnbTy2k8ZWobtcvdtIcwyse3NVd");
var copy = templateFile.makeCopy(deptName + " " + "Cost Recovery Agreement", templateResponseFolder);
var doc = DocumentApp.openById(copy.getId());
var body = doc.getBody();
body.replaceText("{{DeptName}}", deptName);
body.replaceText("{{DeptCo}}", deptCo);
body.replaceText("{{FirstName}}", firstName);
body.replaceText("{{LastName}}", lastName);
doc.saveAndClose();
var id = doc.getId();
var subject = "Welcome to ResponseMaster!";
var message = title + " " + lastName + "," + "\n\n" + "Thank you for choosing ResponseMaster as your dedicated software for your fire department.";
var costRecoveryForm = DriveApp.getFileById();
MailApp.sendEmail(userEmail, subject, message, { attachments: [costRecoveryForm] });
I am already have the e.values set up properly further above the script but this is all the script that deals with the issue.
By putting the Google Doc URL in the email body, Gmail will show it as an attachment (if the recipient has access to the file).
Like in the following image.
So here is my approach:
let templateFile = DriveApp.getFileById("1hNJ8SUybJn8nnJg87Pm22dzI0_3L0N17ZbYhV1HeUrM");
let templateResponseFolder = DriveApp.getFolderById("1Xzs1k-e8q2NYCTHg-4yit7zFWTF7L33h");
let copy = templateFile.makeCopy(`${deptName} Cost Recovery Agreement`, templateResponseFolder);
let copyId = copy.getId();
// Here I give the user permission to view the file I'm sending him
DriveApp.getFileById(copyId).addViewer(userEmail);
let doc = DocumentApp.openById(copyId);
let copyUrl = doc.getUrl();
let body = doc.getBody();
body.replaceText("{{DeptName}}", deptName);
body.replaceText("{{DeptCo}}", deptCo);
body.replaceText("{{FirstName}}", firstName);
body.replaceText("{{LastName}}", lastName);
doc.saveAndClose();
let subject = "Welcome to ResponseMaster!";
let message = `${title} ${lastName},\n\nThank you for choosing ResponseMaster as your dedicated software for your fire department.\n\n${copyUrl}`;
MailApp.sendEmail(userEmail, subject, message);
I would like to create a list of emails, which are listed in the column of a sheets.
how can I do this?
example:
column A
email 1
email 2
email 3
mailling = column A
MailApp.sendEmail({
to: mailling,
subject: "test",
body: "Test message",
if your emails are in column A starting from row 2:
function getEmails() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet1');
const emails = sh.getRange(2,1,sh.getLastRow() - 1, 1).getValues().flat();
return emails.join(',');
}
function sendEmails() {
MailApp.sendEmail({to: getEmails(),subject: "test",body: "Test message"});
}
I think you should check the documentation of the class like suggested in the comments, it has really good features that can improve the way you email. Anyway, here is an example that can help you.
function sendMail() {
//Each numer means the column of the sheets thats going to grab the value
var first = 0;
var second = 1;
var third = 2;
//In the Column D must have the emails
var fourth =3;
//Specifies the HTML document that going to give the structure of the email
var emailTemp = HtmlService.createTemplateFromFile("email");
//Tells wich is the sheet to take information
//in this case the sheets name is "Data Base"
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data Base");
//Gives the range of the columns that the information is going to be
var data = ws.getRange("A1:E" + ws.getLastRow()).getValues();
//This is an optional filter in the Column F so you can filter wich rows to run
data = data.filter(function(r){ return r[5] == true });
//To use the variables in between the HTML file your going to use the value after "emailTemp." as <?= fr ?>
data.forEach(function(row){
emailTemp.fr = row[first];
emailTemp.se = row[second];
emailTemp.th = row[third];
var htmlMessage = emailTemp.evaluate().getContent();
GmailApp.sendEmail(row[fourth], "HEEERE GOES THE SUBJECT OF THE EMAIL", "Your email doesn't support HTML.", {name: "Email", htmlBody: htmlMessage})
});
Here I used a html template to send emails with variables extracted from other columns. You can check out this github
The below script runs without any visible error, but no emails are sent. Any ideas as to why?
function sendEmailLoop() {
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
sheets.forEach(function(sheet) {
var range = sheet.getDataRange();
if (sheet.getName() == "Summary") //Disregard tab named 'Summary'
{
}
else {
var range = sheet.getDataRange(); //to set the range as array
var values = range.getDisplayValues(); //to get the value in the array
var lastRow = range.getLastRow();
var ss = SpreadsheetApp.getActiveSpreadsheet(); //declare the spreadsheet
var sheet = ss.getSheetByName("Sheet1");
var Title = values[0][0]; //[Title] cell A1
var URL = values[0][1]; //[URL] cell B1
var i;
var logContent = '';
for (i = 3; i < lastRow; i++) {
var Name = values[i][0]; //[Name] cell A++
var Email = values[i][1]; // [Email] cell B++
Logger.log('to: ' + Email);
Logger.log('subject: ' + Name + Title + 'Test');
Logger.log('message: ' + 'This is a test message for the training that can be found at ' + URL);
/*
MailApp.sendEmail({
to: Email,
subject: Name + Title + 'Test',
message: 'This is a test message for the training that can be found at ' + URL});
*/
}; //end for loop - email tab data
}; // end 'else'
}); // end function(sheet)
} // end SendEmailLoop()
Here is the Stackdriver log of a successful execution (success meaning no errors, but still no emails are sent):
The structure of the spreadsheet associated with the script:
Note - an earlier version of this script didn't include the sheets.forEach() method call (ie, to loop through each tab of the spreadsheet) and the emails were sent fine.
Could the lack of emails being sent or received be related to the fact that I have many sheets and this function is looping through them?
function sendEmailLoop() {
var exclA=['Summary'];
var ss=SpreadsheetApp.getActive();
var sheets=ss.getSheets();
sheets.forEach(function(sheet) {
if (exclA.indexOf(sheet.getName())==-1) {
var range=sheet.getDataRange();
var values=range.getDisplayValues();
var lastRow=range.getLastRow();
var Title=values[0][0];
var URL=values[0][1];
var logContent='';
for (var i=3; i <values.length; i++) {
var Name=values[i][0];
var Email=values[i][1];
Logger.log('to: %s\nsubject: %s %s Test\nmessage: %s This is a test message for the training that can be found at %s',Email,Name,Title,URL);
/*
MailApp.sendEmail({
to: Email,
subject: Name + Title + 'Test',
message: 'This is a test message for the training that can be found at ' + URL});
*/
}
}
});
}
Answer:
You need to uncomment your MailApp code.
Code changes:
I tested your code and it seems to run without issue for me, including the receipt of the emails, only that the code comments around your MailApp call need to be removed (the /* and the */).
I would also suggest adding a conditional line before you send the email in the event .getDataRange() obtains seemingly empty rows:
if (Email == "") {
continue;
};
MailApp.sendEmail({
to: Email,
subject: Name + Title + 'Test',
message: 'This is a test message for the training that can be found at ' + URL});
References:
JavaScript Comments
I need to modify this code to email the people in a list held on a sheet named "Data" under column 1 (A),
Is this possible while still being able to email out the charts?
function
emailCharts(sheet,emails,emailSubject){
var targetspreadsheet = SpreadsheetApp.getActiveSpreadsheet(); // Active spreadsheet of the key file
var sheet = targetspreadsheet.getSheetByName('Overview'); // Change the sheet name
var emailSubject = 'absence review ';
var emails = ""; // your email ID
var charts = sheet.getCharts();
if(charts.length==0){
MailApp.sendEmail({
to: emails,
subject: "ERROR:"+emailSubject,
htmlBody: "No charts in the spreadsheet"});
return;
}
var chartBlobs=new Array(charts.length);
var emailBody="Charts<br>";
var emailImages={};
for(var i=0;i<charts.length;i++){
var builder = charts[i].modify();
builder.setOption('vAxis.format', '#');
var newchart = builder.build();
chartBlobs[i]= newchart.getAs('image/png');
emailBody= emailBody + "<p align='center'><img src='cid:chart"+i+"'> </p>";
emailImages["chart"+i]= chartBlobs[i];
}
MailApp.sendEmail({
to: emails,
subject: emailSubject,
htmlBody: emailBody,
inlineImages:emailImages});
}
Any help please
var email = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data").getRange(1,1).getValue();
I'm sending a spreadsheet in the body of an email everyday. I completed the email portion, but now im trying to program the trigger to set off at 1:15pm everyday. I'm not sure how to implement the code to trigger with the email?
'function nearMinute(minute) {
var sendRead = ScriptApp.newTrigger("sendRead1pm")
.timeBased()
.atHour(13)
.everyDays(1) // Frequency is required if you are using atHour() or atMinute()
.create();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Totals");
var subjecttable = UrlFetchApp.fetch("https://docs.google.com/spreadsheet/pub?
key=XXXXXXXXXXXXXXXXXXXXXXXXXXX=true&gid=1&output=html");
var htmltable = subjecttable.getContentText();
var fromName = "DoNotReply - email";
var rowData = ss.getRange("B16").getValues()[0];
var emailAddress = "emailaddress#gmail.com"; // First column
var message = {htmlBody: htmltable, name: fromName}; // Second column
var subject = "TEST $" + rowData;
MailApp.sendEmail(emailAddress, subject, "", message);
}`
You don't have to code your trigger. Make your function to do the email part and set up the trigger manually. In your script, go to Resources --> Current Project's Triggers and then add a trigger. This is the easiest.