searched this and I need this code. The problem is I dont know how to run the code and I cannot also comment due to my low reputation.
I have a button on my google sheets where I will assign the code. My data range is
var dataRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Front").getRange("C2:Q14")
function convSheetAndEmail(rng, email, subj)
{
var HTML = SheetConverter.convertRange2html(rng);
MailApp.sendEmail(emailAddress, subject, '',{htmlBody : HTML});
}
function doGet()
{
var dataRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Front-User").getRange("C2:Q14")
var emailAddress = 'test#gmail.com'
var subject = 'Test'
convSheetAndEmail(dataRange, emailAddress, subject);
}
Related
I'm having trouble with the "Email _Sent" text. It is supposed to appear next to the recipient who received the email from my spreadsheet. However, when I select certain emails to send the message to, the text "Email _Sent" starts filling out the first empty rows in my spreadsheet. In this way, the text appears beside some recipients who didn't receive the message.
I'll post the script that I'm using:
function sendGeneralEmail() {
var Email = 4;
var Name = 3;
var emailSent = 6;
var subject = "Sample Analysis Service"
var html = HtmlService.createTemplateFromFile("SUM.1");
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Test");
var data = ws.getRange("A5:G" + ws.getLastRow()).getValues();
data = data.filter(function(r){ return r[5] == true});
var Email_Sent = 'Email_Sent';
var sheet = SpreadsheetApp.getActiveSheet();
var notBlank = sheet.getRange("D5:G5");
var lastRow = notBlank.getLastRow();
data.forEach(function(row){
html.en = row[Name];
var htmlMessage = html.evaluate().getContent();
if(emailSent !=Email_Sent) {
GmailApp.sendEmail(
row[Email],
subject, "Your Email doesn't support HTML", {
name: "MASAR Team",
htmlBody: htmlMessage},
);
sheet.getRange(lastRow, 7, data.length, 1).setValue(Email_Sent);
SpreadsheetApp.flush();
}
});
}
Can someone help me to fix that?
The second issue is that, if I run the script and then stopped and came back and run it again on the same day, the text "Email_sent" stops updating to the spreadsheet. It only appears the first I run the script during the day.
Screenshot
Hope to have a solution to this
I tried to replicate your code and found some issues:
using setValue on range with multiple cells will copy the value to all cells within the range. In your example, all cells in getRange(lastRow, 7, data.length, 1) will have the value "Email_Sent". This causes the unwanted write of "Email_Sent" in your spreadsheet.
if(emailSent !=Email_Sent) will always true because '6' is not always equal to 'Email_Sent'
Based on your example, your goal is to send an email and write "Email_Sent" to the Email Status column of the recipient.
Here, I fixed some part of your code and added features.
Code:
function sendGeneralEmail() {
var subject = "Sample Analysis Service"
// var html = HtmlService.createTemplateFromFile("SUM.1");
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Test");
var data = ws.getRange("A5:G" + ws.getLastRow()).getValues();
var sheet = SpreadsheetApp.getActiveSheet();
for(var i=0; i<data.length; i++){
var selected = data[i][5];
var emailStatus = data[i][6];
if(selected && emailStatus != "Email_Sent"){
var email = data[i][4];
// html.en = row[Name];
// var htmlMessage = html.evaluate().getContent();
GmailApp.sendEmail(
email,
subject, "Your Email doesn't support HTML", {
name: "MASAR Team",
message: "ABCD",
// htmlBody: htmlMessage},
}
);
sheet.getRange(i+5, 7, 1, 1).setValue("Email_Sent");
}
}
}
Note: I commented the html parsing since I don't have the sample html and replaced the email message with a string.
Before running the script:
After running the script:
Reference:
setValue()
Need Help to create a watchdog. I'm importing a webpage with some data. and want constantly check if imported data is the same whats my reference.
So I want the script to constantly compare 2 cells and if values became different, send me (the author) the email.
Want to compare H4 and E4
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Pricechecker");
var checkprice = sheet.getRange(E2:E2);
var currentprice = sheet.getRange(H4:H4);
if (currentprice <= checkprice) {
var emailAddress = "email#example.ge";
var message = "Discount";
var subject = "There is a Discount on your item";
MailApp.sendEmail(emailAddress, subject, message);
}
}
Solution:
You would need an Installable Trigger to automatically send email upon comparison of E4 and H4.
function createSpreadsheetEditTrigger() {
var ss = SpreadsheetApp.getActive();
ScriptApp.newTrigger('compare')
.forSpreadsheet(ss)
.onEdit()
.create();
}
function compare(e) {
if (e.range == "E4" || "H4") {
var sheet = SpreadsheetApp.getActiveSheet();
var checkPrice = sheet.getRange("E4").getValue();
var currentPrice = sheet.getRange("H4").getValue();
if (currentPrice <= checkPrice) {
var emailAddress = "email#example.ge";
var message = "Discount";
var subject = "There is a Discount on your item";
MailApp.sendEmail(emailAddress, subject, message);
}
}
}
Note that you only have to run createSpreadsheetEditTrigger() in Apps Script. The created trigger will run compare() everytime you make an edit to the spreadsheet. It will automatically check E4 and H4 and send email whether the condition is satisfied.
Console Output:
Looking to attach a file (pdfName) from Google Drive to sendMail function in Apps Script. Currently not pulling with the code I have below. Everything else works perfectly. Just having trouble with the attach portion.
function send(formObj) {
var to = formObj.email;
var body = formObj.body;
var sheetName = "POTemplate";
var sourceSpreadsheet = SpreadsheetApp.getActive();
var sourceSheet = sourceSpreadsheet.getSheetByName(sheetName);
var poNo = sourceSheet.getRange("b2").getValue();
var pdfName = "Sample PO Hi Eric " + poNo;
var subject = poNo + " Good morning, Eric";
var attach = DriveApp.getFilesByName(pdfName);
MailApp.sendEmail(to, subject, body, {attachments:[attach]});
}
It looks like, according to the GAS Documentation on sendMail, the attachments argument requires a BlobSource[] (documentation). However getFilesByName() returns a FileIterator. You need to give MailApp any filetype that implements BlobSource.
So to clarify the main issue is that you are trying to give sendMail a list of files (in the form of FileIterator) instead of just one file.
So something like this should work:
function send(formObj) {
var to = formObj.email;
var body = formObj.body;
var sheetName = "POTemplate";
var sourceSpreadsheet = SpreadsheetApp.getActive();
var sourceSheet = sourceSpreadsheet.getSheetByName(sheetName);
var poNo = sourceSheet.getRange("b2").getValue();
var pdfName = "Sample PO Hi Eric " + poNo;
var subject = poNo + " Good morning, Eric";
var listOfFiles = DriveApp.getFilesByName(pdfName); //returns FileIterator of files that match name given.
if(listOfFiles.hasNext()){ //We should check if there is a file in there and die if not.
var file = listOfFiles.next(); //gets first file in list.
MailApp.sendEmail(to, subject, body, {attachments:[file]});
}else{
console.log("Error no file in listOfFiles. Email not sent.");
}
}
edit: I just did some testing and it looks like, for PDFs, the getBlob() is not necessary so I have removed it from my code!
I've clicked around for the past few days trying to find an answer but can't seem to find one that makes sense to me (forgive me, I'm fairly new to GAS). I am trying to set up a Fantasy Golf Draft sheet to be used by about 12 users, but over half of which don't have/aren't willing to use a Gmail address. Getting access to the file is no problem, where I am running into an issue is trying to run a script, where when a Button/Shape is clicked, it sends an automated email to the next person who's turn it is to pick. The functionality of the script is working, when it comes from myself or someone with a Google account who can authorize the script etc. I run into troubles when it's someone without a Google account.
My question - how can I set the script to ONLY send from my email, or the Sheet/Script Owner's email - regardless of who is modifying/clicking the button? I see links about creating the script as a webapp to do this, but I get lost quickly.
Here's a link to my sheet:
[https://docs.google.com/spreadsheets/d/16AppcmrcuhatnzcEs7eIQyD_p1swbRimRZZ4FdbhBKI/edit?usp=sharing][1]
And here is my send mail code:
function sendAlertEmails() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.setActiveSheet(ss.getSheetByName("Send Mails"));
var sheet = SpreadsheetApp.getActiveSheet();
var dataRange = sheet.getRange("A2:f2");
var data = dataRange.getValues();
for (i in data) {
var rowData = data[i];
var emailAddress = rowData[1];
var recipient = rowData[0];
var message1 = rowData[2];
var message2 = rowData[3];
var message3 = rowData[4];
var message4 = rowData[5];
var message = 'Hey ' + recipient + ',\n\n' + message1 + '\n\n' + ' The last player picked was ' + message2 + '\n\n' + message3 +'\n\n' + message4;
var subject = '*GOLF DRAFT 2018* - YOU ARE ON THE CLOCK';
MailApp.sendEmail(emailAddress, subject, message);
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.setActiveSheet(ss.getSheetByName("DRAFT"));
}
}
Any help would be greatly appreciated!
I felt interested in this issue and worked a bit more on it. I changed from it being a get request to being a post request.
Here is what I have in the Google sheet.
function sendAlertEmails() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.setActiveSheet(ss.getSheetByName("Send Mails"));
var sheet = SpreadsheetApp.getActiveSheet();
var dataRange = sheet.getRange("A2:f2");
var data = dataRange.getValues();
for (i in data) {
var rowData = data[i];
var emailAddress = rowData[1];
var recipient = rowData[0];
var message1 = rowData[2];
var message2 = rowData[3];
var message3 = rowData[4];
var message4 = rowData[5];
var message = 'Hey ' + recipient + ',\n\n' + message1 + '\n\n' + ' The last player picked was ' + message2 + '\n\n' + message3 +'\n\n' + message4;
var subject = '*GOLF DRAFT 2018* - YOU ARE ON THE CLOCK';
var data = {
'name': 'Bob Smith',
'email': 'a#b.com',
'message': message,
'subject': subject,
};
var options = {
'method' : 'post',
'contentType': 'application/json',
'payload' : data
};
var secondScriptID = 'STANDALONE_SCRIPT_ID'
var response = UrlFetchApp.fetch("https://script.google.com/macros/s/" + secondScriptID + "/exec", options);
Logger.log(response) // Expected to see sent data sent back
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.setActiveSheet(ss.getSheetByName("DRAFT"));
// Browser.msgbox("Your Pick Has Been Made");
}
}
Below is what I have in the standalone script. There are some provisos on the standalone script working:
It needs to be published under "Deploy as a webapp"
Access should be set to 'Anyone, even anonymous'
Every time you make a change to the standalone script publish again and
change the Project version to new. This is so the call from the first sheet calls to the latest code.
Standalone Script
function convertURItoObject(url){
url = url.replace(/\+/g,' ')
url = decodeURIComponent(url)
var parts = url.split("&");
var paramsObj = {};
parts.forEach(function(item){
var keyAndValue = item.split("=");
paramsObj[keyAndValue[0]] = keyAndValue[1]
})
return paramsObj; // here's your object
}
function doPost(e) {
var data = e.postData.contents;
data = convertURItoObject(data)
var recipient = data.email;
var body = data.message;
var subject = data.subject;
try {
MailApp.sendEmail(recipient, subject, body)
}
catch(e){
Logger.log(e)
}
return ContentService.createTextOutput(JSON.stringify(e));
}
No, you can't do that, because a script can be shared with a multiple users and it is always executed from their own account not from the script owners account and script uses the 'from email address' of the executing user, it is not allowed by Google to send email from another users account as a security policy.
You could use a second script that belongs to you. From your first script send a fetch request to the second script, the second script can send an email from your account to anyone. The second script would look like this:
function doGet(e) {
var recipient = e.parameter.email;
var body = e.parmeter.message
var subject = "My golf thing"
try {
MailApp.sendEmail(recipient, subject, body)
}
catch(e){
Logger.log(e)
}
}
The first script would need a fetch request something like this.
var response = UrlFetchApp.fetch("https://script.google.com/macros/s/SECOND_SCRIPT_ID/exec?email=b#b.com&message=somthing");
return response;
I have a long standing form/spreadsheet/script - that send emails triggered on spreadsheet edit. The trigger is working but the email is not sending. I have dropped the script and recreated - which authorized again.
function sendNotification() {
//Get Active spreadsheet and worksheet
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var sheet = spreadsheet.getSheetByName("Change Requests");
var sheet2 = spreadsheet.getSheetByName("Email Addresses");
//Set row for which to send notification
//get values
var lastRow = sheet.getRange(row, 1, 1, sheet.getLastColumn());
var values = lastRow.getValues();
//Other Variables
var body = "<HTML><BODY>";
var stuNumber = values[0][2];
var stuName = values[0][3].toString();
var stuHouse = values[0][5].toString();
var gradeLevel = values[0][6].toString();
var oldCourse = values[0][7].toString();
var newCourse = values[0][8].toString();
var subject = "New course change request submitted for " + stuName;
var academicAdviser;
var cc_recipients = sheet2.getRange(4, 2).getValue();
//Send notification email
try {
MailApp.sendEmail(academicAdviser, subject, body, {htmlBody: body, noReply: "True", cc: cc_recipients})
}
catch (f) {
Browser.msgBox(f.message);
}
}
In this line:
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
spreadsheet is set to the activeSheet which is not a spreadsheet
In this line:
var lastRow = sheet.getRange(row, 1, 1, sheet.getLastColumn());
row is undefined.
In this Line:
MailApp.sendEmail(academicAdviser, subject, body, {htmlBody: body, noReply: "True", cc: cc_recipients})
academicAdviser is undefined and htmlBody is set to <HTML><BODY> which will produced no output for htmlBody parameter.
Instead of Using this:
Browser.msgBox(f.message);
You might consider using SpreadsheetApp.getUi().prompt() or alert()
And I think it's a good idea to add MailApp.getRemainingDailyQuota() somewhere to keep yourself from running over your quota.
After looking at your code I'd guess that it might be a good idea for you to read this section.