Weird behaviour of Mailapp.sendEmail in Google apps script - google-apps-script

I have been sending emails successfully through Google apps script triggered through submission in a Google sheet. Lately (about a week back), the email sender starts behaving very weird.
If I use the following format, my emails get bounced
MailApp.sendEmail(email1, subject, message,{cc:email2,attachments:[file.next()]});
If I use the following form, the email does NOT get delivered neither does it get bounced
MailApp.sendEmail(email, subject, message);
If I use the following format, the recipient gets the message as shown
MailApp.sendEmail(email,subject,{htmlBody: message});
Revecied message
[object Object]
and the rest of the stuff blank!
I'm at my wits' end as to how to go about. Any help or a pointer will be of immense help. Regards
Madhurjya
Following is the app script, which is attached to the Google sheet. Once I run the function sendPasswd() from sheet, it gets some vital parameters from the sheet data and then send the message to the person (through the variable email2)
function sendPasswd() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var dataRange = sheet.getDataRange()
var data = dataRange.getValues();
var subject = "Example Subject";
var message = "";
var i;
var file = DriveApp.getFilesByName("some_file.pdf");
for (i in data) {
var row = data[i];
if (i == 0) continue; // Skip the first row
if (row[4] == "Sent") continue;
var first = row[0]; var last = row[1]; var email = row[2];
var passwd = row[3]; var email2 = row[7];
if (row[15] == "some condition") {
message = "Dear <b>"+first+" "+last+"</b>,<br><br>"+
"This is to inform you that your .... ";
MailApp.sendEmail(email2, subject, message);
//MailApp.sendEmail(email2,subject,{htmlBody: "message"});
//MailApp.sendEmail(email2, subject, message,{cc:"some_email#example.com",attachments:[file.next()]});
}
}
}
The surprising fact is that from the same account similar emails are being sent and are NOT affected!
Madhurjya

This might be happening because you're using htmlbody which is part of options as third argument whereas in sendEmail(recipient, subject, body, options) of class MailApp, body should be third argument, that's is the reason of getting [object Object].
Try following modification:-
MailApp.sendEmail(email2,subject,"",{htmlBody: message});
Reference:
sendEmail

You could also use this way (its really more practical):
const email 'yourEmail#outlook.com'
const cc ='copyEmail#hotmail.com'
const bcc = 'blindCarbonCopy#gmail.com'
MailApp.sendEmail({
to:email,
cc: cc,
bcc: bcc,
subject: 'Whatever you want, even template strings' ,
htmlBody: `
You could just create your HTML IN HERE (using template strings)
Or create before and add here as variable as well.
`
})

Related

Google Sheet - Send Email

I need my google sheet to send emails every time a condition becomes true.
In this case, every time value of C2 is lower than value of J2.
On the cell L2 there is the email address.
The code (found online and just edited)
function CheckPrice() {
var LastPriceRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Alerts").getRange("C2");
var LastPrice = LastPriceRange.getValue();
var EntryLimitRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Alerts").getRange("J2");
var EntryLimit = LastPriceRange.getValue();
var StockNameRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Alerts").getRange("B2");
var StockName = LastPriceRange.getValue();
// Check totals sales
if (LastPrice < EntryLimit){
// Fetch the email address
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Alerts").getRange("L2");
var emailAddress = emailRange.getValues();
// Send Alert Email.
var message = 'Ticker ' + StockName + ' has triggered the alert';
var subject = 'Stock Alert';
MailApp.sendEmail(emailAddress, subject, message);
}
}
With this code I don't receive any error, but I don't even receive the email.
I granted permissions as requested when I run the script for the first time.
On L2 I put the same email address I granted permission (I send email to myself).
I did a try even putting a secondary email address I have.
Can you please show me what's wrong ?
Issues:
See the first lines of your code where you define LastPrice,
EntryLimit and StockName. All of them are coming from the same
range: LastPriceRange.
I also removed all the unnecessary calls in your script. There is no
need to call
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Alerts") so
many times when you can just put it in a variable and use that
variable instead.
Also, you don't need to define unnecessary
variables. For example, you can get the value of a cell with one line:
sh.getRange("B2").getValue().
Solution:
function CheckPrice() {
const sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Alerts");
const LastPrice = sh.getRange("C2").getValue();
const EntryLimit = sh.getRange("J2").getValue();
const StockName = sh.getRange("B2").getValue();
// Check totals sales
if (LastPrice < EntryLimit){
// Fetch the email address
const emailAddress = sh.getRange("L2").getValue();
// Send Alert Email.
const message = 'Ticker ' + StockName + ' has triggered the alert';
const subject = 'Stock Alert';
MailApp.sendEmail(emailAddress, subject, message);
}
}
If you want an email to be sent when you edit a particular cell, then you need to transform the aforementioned solution to an onEdit(e) trigger. If you want a time basis trigger then you can just use the solution above directly.

How can I get and send to the last row submitted?

I've built a script that will get the issue with a form submission (D2) then output the text with the information in an email. Right now the Email address location (B2) and issue (D2) are hard coded. How can I work the code to get the email and issue from only the last row submitted?
function SendNot() {
// Fetch the Issue
var reasonRange =
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("TriggerSettings").getRange("D2");
var reason = reasonRange.getValue();
// Check for Issue
if (reason==="nogps"){
// Fetch the email address
var emailRange =
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("PlayerInfo").getRange("B2");
var emailAddress = emailRange.getValues();
// Send Alert Email.
var message = 'No GPS...';
var subject = 'Latest VDGL Entry...';
GmailApp.sendEmail(emailAddress, subject, message);
}
else if (reason==="nobarcode"){
// Fetch the email address
var emailRange =
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("PlayerInfo").getRange("B2");
var emailAddress = emailRange.getValues();
// Send Alert Email.
var message = 'No Barcode...';
var subject = 'Latest VDGL Entry...';
GmailApp.sendEmail(emailAddress, subject, message);
}
}
You can calculate the last row with content using the following method:
sheet.getLastRow()
In your example you can calculate this as follows:
var d_size = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("TriggerSettings").getLastRow();
var b_size = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("PlayerInfo").getLastRow();
and then you can use d_size to grab the last row reason elements:
var reasonRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("TriggerSettings").getRange("D"+d_size);
and b_size to grab the last row email elements:
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("PlayerInfo").getRange("B"+b_size);
You can also use a different syntax to get the desired range:
Instead of getRange("D"+d_size) -> getRange(d_size,4)
Instead of getRange("B"+b_size) -> getRange(b_size,2)
References:
Sheet.getLastRow()

Prevent text wrapping using MailApp.sendEmail google sheets? google script

I have the following working code to send an email based on the content of one cell. This cell contains the values of other cells to create the email.
The emails send to 2 recipients and it works fine.
However, upon receiving the email, the text is wrapped after 74 characters.
Sample sheet replicates issue:
https://docs.google.com/spreadsheets/d/1PDSHbrhxiJliTGNx2rlJRAJIrjITADVuGWqTuvpjrgw/edit?usp=sharing
How can i prevent the wrapping? I want the email to send as it appears in the 'body' cell:
=G2&char(10)&E9&char(10)&E10&char(10)&E11&char(10)&E12&char(10)&E13&char(10)&E14&char(10)&E15&char(10)&E16&char(10)&E17&char(10)&E18&char(10)&E19&char(10)&E20&char(10)&E21&char(10)&E22&char(10)&E23&char(10)&E24&char(10)&E25&char(10)&E26&char(10)&E27&char(10)&E28&char(10)&E29&char(10)&E30&char(10)&E31&char(10)
Send email function:
var EMAIL_SENT = 'EMAIL_SENT';
function SendEmailACC() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("EmailACC");
var startRow = 2;
var numRows = 2;
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 message = row[1]; // Second column
var subject = row[2];
var emailSent = row[5];
var EMAIL_SENT = "Email Processed";
var EMAIL_FAIL = "Email Not Sent";
if (emailSent !== EMAIL_SENT) {
MailApp.sendEmail(emailAddress, subject, message);
sheet.getRange(startRow + i, 5).setValue(EMAIL_SENT);
SpreadsheetApp.flush();
}
}
Utilities.sleep(3000);// pause in the loop
DeleteStatus();
}
How Sample email should look:
Good Morning,
The following claim may have had an incorrect or missing ACC number or was not submitted by the referrer at time of request.
The claim has since been amended or submitted for the release of $50. Updated details are as below.
Vendor ID: ABC123
Invoice number: ABCDE12345
Service Date: 11/10/2019
Patient: John Smith
Service Code(s): COD88
First supplied ACC Number: BTT123
Exam Type: Exam Abc
Amended or updated ACC Number: COD123
Please let me know if any further information is required.
How the email actually comes out:
Good Morning,
The following claim may have had an incorrect or missing ACC number or was
not submitted by the referrer at time of request.
The claim has since been amended or submitted for the release of $50.
Updated details are as below.
Vendor ID: G0A368
Invoice number: ABCDE12345
Service Date: 11/10/2019
Patient: John Smith
Service Code(s): COD88
First supplied ACC Number: BTT123
Exam Type: Exam Abc
Amended or updated ACC Number: COD123
Please let me know if any further information is required.
Any suggestions appreciated
How about this answer? Please think of this as jut one of several possible answers.
Pattern 1:
In this pattern, Class GmailApp is used.
From:
MailApp.sendEmail(emailAddress, subject, message);
To:
GmailApp.sendEmail(emailAddress, subject, message);
Pattern 2:
In this pattern, Gmail API is used. In this case, please enable Gmail API at Advanced Google services.
From:
MailApp.sendEmail(emailAddress, subject, message);
To:
var raw = Utilities.base64EncodeWebSafe("Subject: " + subject + "\r\n" + "To: " + emailAddress + "\r\n" + "Content-Type: text/plain; charset=UTF-8\r\n\r\n" + message + "\r\n\r\n");
Gmail.Users.Messages.send({raw: raw}, "me");
If the characters which are more than the version of Unicode 6.0 are included in the email, Gmail API is required to be used. Please be careful this. Ref
Note:
In my experience, also I had the same issue. At that time, the issue could be resolved by using Class GmailApp. But unfortunately, I couldn't find the detail explanation about this at the official document. I apologize for this.
References:
MailApp.sendEmail(recipient, subject, body)
GmailApp.sendEmail(recipient, subject, body)
Advanced Google Services
Gmail API

GmailApp not sending emails to gmail account every time

I am using this code to send emails (composing email content getting text from the sheet named ranges:
//compose issue emails to student and admin
function composeIssueEmail() {
//student's name, last name and email
var email = ss.getRangeByName("CourseProgressEmail").getValue()
var name = ss.getRangeByName("CourseProgressName").getValue()
var lastName = ss.getRangeByName("CourseProgressStudentLastName").getValue()
var subj = ss.getRangeByName("SetUpIssueTitle").getValue()
var subject = subj.replace("*imya*", name)
var bodyText = ss.getRangeByName("SetUpIssueBody").getValue()
var body = bodyText.replace("*imya*", name)
var link = getChecksheetURL()
var text = body.replace("*link*", link)
//send email to student
var studentEmail = sendEmail(email, subject, text)
var adminEmail = "AGcourseSup#gmail.com"
var adminSubj = ss.getRangeByName("SetUpAdminIssueTitle").getValue()
var adminSubject = adminSubj.replace("*imya*", name)
var adminSubjectFinal = adminSubject.replace("*familia*", lastName)
var adminText = ss.getRangeByName("SetUpAdminIssueBody").getValue()
var adminTextReplace = adminText.replace("*imia*", name)
var adminBody = adminTextReplace.replace("*familia*", lastName)
var adminText = adminBody.replace("*link*", link)
//send email to admin
sendEmail(adminEmail, adminSubjectFinal, adminText)
}
//gets current checksheet URL
function getChecksheetURL() {
var Url = ss.getUrl()
var linkMiddle = "#gid="
var sheetID = sheet.getSheetId()
var shecksheetURL = Url + linkMiddle + sheetID
return shecksheetURL
}
//sends emails
function sendEmail(email, subject, body) {
GmailApp.sendEmail(email, subject, body)
}
Execution transcript:
[19-06-12 16:39:43:396 EEST] Execution succeeded [2.399 seconds total runtime]
It sends stably to the gmail account that is the same as spreadsheet's one.
But to another gmail account it sends about every other time.
Details:
This code is executed (I log the line after this code)
The emails are visible in my outbound box but not arriving to any of the boxes of the recepient gmail.
Not in spam etc.
I don't get any messages, error or bounce notifications.
I tried MailApp instead - it's even worse and sometimes doesn't send even to my own email.
I tried to change things in settings config, but didn't find anything to work.
I set up a filter "never send to spam" and "always star it" - didn't work.
I deleted a link from it so it has no link - didn't work.
What can be a solution?
I handled this issue. The issue is about anti-spam filters not about the code.
I gained more trust to the email account by adding "Reply To" option within GmailApp.sendEmail method. It magically solved the problem so each email reaches target now.

How to send email based on cell contents in Google Sheets using custom function

I have a spreadsheet where data will be continuously inputted (through Google Forms and user input), and I would like to have code that will send out a single email for a single row, which I can call multiple times as rows get completed. Currently, I created a custom function that is supposed to do this but when I run it I get an error which reads "You do not have permission to call MailApp.sendEmail. Required permissions: https://www.googleapis.com/auth/script.send_mail (line 6)."
function sendDirectiveResponse(name, message, response, emailAddress) {
var sheet = SpreadsheetApp.getActiveSheet();
var emailSent = "Email Sent";
var message = "Received: " + message + "\n\n Response: " + response;
var subject = "Message Response";
MailApp.sendEmail(emailAddress, subject, message);
return emailSent
}
I expect an email to be sent out and the cell to show "Email Sent" but, instead, it says "#ERROR" and no email is sent.
Sending emails based upon cell contents
function sendMyEmails() {
var ss=SpreadsheetApp.getActive();
//the next few commands create a newsheet and load it with sample data so that you do not have to. You will want to remove this and use a spreadsheet of your own choosing
var sh=ss.insertSheet();//setup
var init=[['Email','Subject','Message','Status'],['sample1#gmail.com','Email Testing','Have a great day.',''],['sample2#gmail.com','Email Testing','Have a great day.',''],['sample3#gmail.com','Email Testing','Have a great day.',''],['sample4#gmail.com','Email Testing','Have a great day.','']];//setup
sh.getRange(1,1,init.length,init[0].length).setValues(init);//setting up data
var rg=sh.getDataRange();//get data
var vA=rg.getValues();
var hObj=[];
var html='';
for(var i=0;i<vA.length;i++) {
for(var j=0;j<vA[i].length;j++) {
hObj[vA[0][j]]=vA[i][j];//this loads the object with all of the data for this row. And you can now refer to it with hObj.headertitle
}
if(!hObj.Status) {//When you supply your own data this will prevent function from sending emails more than once
html+=Utilities.formatString('<br />Email: <strong>%s</strong> Subject: <strong>%s</strong> Message: <strong>%s</strong>', hObj.Email,hObj.Subject,hObj.Message)
sh.getRange(i+1,vA[0].indexOf('Status') + 1).setValue('Done')
//MailApp.sendEmail(hObj.Email, hObj.Subject, hObj.Message);//removed for testing you will have to uncomment this line to actually send email
}
}
var ui=HtmlService.createHtmlOutput(html).setWidth(1000);
SpreadsheetApp.getUi().showModelessDialog(ui, 'Email Testing');//this provides a dialog to show you what would have been sent if everything were enabled.
}