GmailApp not sending emails to gmail account every time - google-apps-script

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.

Related

Weird behaviour of Mailapp.sendEmail in 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.
`
})

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

Sending Autoreponse Email Script on Form Submit

I've used a script in another spreadsheet that emails me whenever someone submits a form. It emails me with a few answers to important questions as well as a link to to view the full response on the spreadsheet.
Here is my original code that works:
function Outreach_FormMailer(e) {
var recipient = "email#gmail.com";
var timestamp = e.values[0];
var name = e.values[1];
var subject = e.values[1]+" completed a Report for "+e.values[3]
var dates = e.values[7];
var goalMet = e.values[9]
var goalFocus = e.values[10]
var hyperlink = "myawesomelink.com"
htmlBody = name+' just completed the O/R Report for these dates: '+dates+'<br><br>Form completed on: '+timestamp+'<br>Was the goal met? '+goalMet+'<br>What was the goal focus? '+goalFocus+
'<br><br>View the Form:Click Here';
MailApp.sendEmail(recipient, subject, htmlBody, {htmlBody:htmlBody});
}
I wanted to use this code for a new form with different questions, so I edited the code to just correspond to the correct qeustions.
This is the code that doesn't work:
function Team_ApplicationMailer(e) {
var recipient = "email#gmail.com";
var timestamp = e.values[0];
var name = e.values[3];
var subject = e.values[1]+' filled out the Teams Application Form!' ;
var startdate = e.values[12];
var enddate = e.values[13]
var Focus = e.values[19]
var hyperlink="myawesomelink.com"
htmlBody = name+' from: '+e.values[1]+'just completed the Teams Application Form for these dates: '+startdate+' to '+enddate+'<br><br>Form completed on: '+timestamp+'<br><br>View the Form:Click Here';
MailApp.sendEmail(recipient, subject, htmlBody, {htmlBody:htmlBody});
}
I've done several test emails and for some reason, this version of the script will not work. I am adding this script to a form that already has responses on the spreadsheet. Would that make a difference? Really not sure what I did wrong in transferring the code to a different spreadsheet.
Thanks for the comments guys. I actually realized the above code does work as is. I forgot that I setup a filter in Gmail that was sending the autoresponse email to a folder I didn't see instead of the inbox. No problem with the code, I just forgot to check the right place the email was sent to.

Google Forms Complex Email Send on Form Submit with Script

I have this right now as a script to send an email to myself as a test showing that there is a new application submitted, but I am looking to have a full-fledged email sent to our HR department giving the name of every field following by a : and a space then what their answer was. I know you can do this and have found a script that I tried to get to work, but it kept failing and the developer was no help in trying to help me fix it. I really would love to get this done for my HR department so that we can move on from creating a new application. Here is my code so far, I removed my email for privacy issues:
function sendFormByEmail(e){
var email = "emailgoeshere";
var subject = "A New Employment Application has been Submitted";
var message = "A New Application Has Been Submited. Please go to the spreadsheet for more details.";
MailApp.sendEmail(email, subject, message);
}
Thanks again!
Or you could try this very simple one :(read carefully comments in the script)
function sendFormByEmail(){
var email = "email adress comes here";
var subject = "A New Employment Application has been Submitted";
var message = "A New Application Has Been Submited. Please find the details below :";
var row = SpreadsheetApp.getActiveSpreadsheet().getLastRow();// assuming data is on the last row of the spreadsheet
var messagebody=createmessage(row);
MailApp.sendEmail(email, subject, message+messagebody);
}
//
function createmessage(row){
var sh = SpreadsheetApp.getActiveSheet();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var lastCol = ss.getLastColumn();
var LF= "\r\n"
var body = LF
var headers = sh.getRange(1,1,1,lastCol).getValues();
var data = sh.getRange(row,1,1,lastCol).getValues();
for(nn=0;nn<headers[0].length;++nn){
body+=headers[0][nn]+" : "+data[0][nn]+LF
}
Logger.log(body)
return body
}
//
//eof
As mentionned, data coming from the form must be on last row of data in the sheet and there must be some data to check how it works otherwhise answers=questions.
I've developed a script that might help you, it's called FormEmailer. You can find it in the Script Gallery or grab the code on its site.