Convert MailApp.sendEmail code to GmailApp.sendEmail with HTML Body - google-apps-script

All, I am looking for help from someone with more experience with this. I have a cobbled together email script that works great as is. I want to specify the from: address using an alias and it's my understanding that I need to use GmailApp vs MailApp to accomplish this. The trouble is, I can't figure out how to make my htmlBody work in the GmailApp version.
Here is my working MailApp code:
function SendPreReleaseAlertEmail(row) {
var sheet = SpreadsheetApp.getActive().getSheetByName('EmailSheet');
var subject = sheet.getRange("M3").getValues(); // Change the subject as needed.
var recipients = sheet.getRange("M2").getValue(); // Change the recipient as needed.
var message = "<HTML><BODY>" + "<P>"
for (var x=6;x<14;x++) { //Loop from * to * with a +1 increment
message = message + sheet.getRange("M" + x).getValues() + "<BR>" //Add row I(x) to the message
}
message = message + "</HTML></BODY>";
MailApp.sendEmail(recipients, subject, "", {htmlBody: message});
}
And this is my FAILED attempt at converting it to GmailApp with a From address:
function SendPreReleaseAlertEmail(row) {
var sheet = SpreadsheetApp.getActive().getSheetByName('EmailSheet');
var subject = sheet.getRange("M3").getValues(); // Change the subject as needed.
var recipients = sheet.getRange("M2").getValue(); // Change the recipient as needed.
var message = "<HTML><BODY>" + "<P>"
for (var x=6;x<14;x++) { //Loop from * to * with a +1 increment
message = message + sheet.getRange("M" + x).getValues() + "<BR>" //Add row I(x) to the message
}
message = message + "</HTML></BODY>";
GmailApp.sendEmail(recipients, subject, {htmlBody: message}, {from: "moo#cow.com"});
}
The above code does in fact email from the alias. But the htmlBody just has the words "[object Object]" in the body of the email.
It's Alive! Here is the final code that solved my problem:
GmailApp.sendEmail(recipients, subject, '', {htmlBody: message, from: "moo#cow.com"});

I think you need to fix two things.
1.The syntax is
sendEmail(recipient, subject, body, options)
So you may need to include a blank placeholder for body in your code.
2.You may also need to have both the htmlBody and from in the options JavaScript object like so:
GmailApp.sendEmail(recipients, subject, '' , {
htmlBody: message,
from: "moo#cow.com"});

You can still use MailApp like that:
var email = "exampleRec#email.com";
var Subject_to_Send = "This is an automated email";
var check_body =
"Good morning team, <br/><br/>"
+"I hope this email finds you well. <br/><br/>";
MailApp.sendEmail( {to:email, subject:Subject_to_Send, body:check_body,htmlBody:check_body, from: "exampleSen#email.com"});
If you also want to send a noReply message you can adjust the last line as follows:
MailApp.sendEmail( {to:email, subject:Subject_to_Send, body:check_body,htmlBody:check_body, noReply: true});

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.
`
})

Custom Email based on Cell values in google sheets

I need help while building a Request Approval Flow in google Forms/Sheets
I have a data response sheet similar to like below, Column A to J headers are
"Timestamp" "EmailAddress" "Name" "Targets" "Account#" "Reason" "Access(Days)" "Approver" "Approved" "CaseID"
I have already setup a form submit email trigger to Approval body through formMule AddOn, Now I want to trigger email when Approval body approve or disapprove the request in Data response sheet.
Everytime when anyone select "Y" or "N" to column "I", script should suppose to trigger an email based on the data present in that row.
I am not an expert but tried to do it with following script and unfortunately not getting desired outcome, I set it up Current project trigger to OnEdit
function sendNotification1(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Form Responses 1");
if(e.range.getColumn() == 9 && e.value == "Y")
{
var name = e.range.offset(0,-6).getValue();
var comment = e.range.offset(0,-3).getValue();
var email = e.range.offset(0,-7).getValue();
var case1 = e.range.offset(0,1).getValue();
var approver1 = e.range.offset(0,-1).getValue();
var subject = "Request has been Approved";
var body = "Hi " + name + ", your Change Request number " + case1 + " has been approved by " + approver1 + " with following comments: " + "\n\r" + comment;
MailApp.sendEmail(email, subject, body);
}
if(e.range.getColumn() == 9 && e.value == "N")
{
var name = e.range.offset(0,-6).getValue();
var comment = e.range.offset(0,-3).getValue();
var email = e.range.offset(0,-7).getValue();
var case1 = e.range.offset(0,1).getValue();
var approver1 = e.range.offset(0,-1).getValue();
var subject = "Request has been Disapproved";
var body = "Hi " + name + ", your Change Request number " + case1 + " has been Dis-Approved by " + approver1 + " with following comments: " + "\n\r" + comment;
MailApp.sendEmail(email, subject, body);
}
}
StackDriver logging showed the following error, but couldn't identify where the issue exist while referring the cell addresses.
2018-09-14 08:19:06.336 PKT
The coordinates or dimensions of the range are invalid. at sendNotification1(Code:6)
I am able to trigger an email on any edit event with following code, but no luck with conditional edit event trigger.
function sendNotification1(e) {
MailApp.sendEmail("myemail#companygmail.com", "Sample subject", "Sample body");
}
While debugging the code, I can see the following error
TypeError: Cannot read property "range" from undefined. (line 6, file "Code")
Any help will be highly appreciated
You are likely running into the issue of the code not knowing what range you are referring to, because you never tell it where to look.
Add the following to the top of the function:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("YOUR SHEET NAME");
And it should work perfectly.
EDIT: Here's the email I sent to myself when I tested it.

Send e-mail with InlineImages

I've created a script to send emails to a list of e.mail addresses with a PDF attachment. Now I want to "pimp it", adding a picture taken from Drive at the beginning of the email.
I found this method on Google Developers - sendEmail(recipient, subject, body, options) - but it's not crystal clear to me on how it works.
This is the code I wrote so far, but it's not working. I keep reading only the text, without any picture. It should take the first 50 rows of a spreadsheet, send an email to the address in column 9 and update column 11 once done.
var sheet = SpreadsheetApp.setActiveSheet(source.getSheets()[2]);
var row = 3
var subject = "Subject";
var imageId = DriveApp.getFileById("0B-OVYDHfkqhXOTF6aWVSSUtSbUE");
var htmlText = "<img src = "cid:imageId" /> Dear Friend, <BR> <BR> Text";
for (var i = 0; i <= 50; i++) {
var emailAddress = sheet.getRange(row + i, 9).getValue()
var message = "Hi,\n \n" + "text";
MailApp.sendEmail(emailAddress, subject, message, {
name: "Alternative Name",
htmlbody: htmlText,
attachments: [budgetPDF],
inLineImages: imageId
})
sheet.getRange(row + i, 11).setValue("Sent");
Could you please tell me what I'm doing wrong?
Thanks for your help!
You don't get the blob of the file.
var imageId = DriveApp.getFileById("0B-OVYDHfkqhXOTF6aWVSSUtSbUE");
var imageIdBlob = imageId.getBlob();
var htmlText = "<img src = 'cid:imageIdBlob' /> Dear Friend, <BR> <BR> Text";
.....
.....
MailApp.sendEmail(emailAddress, subject, message, {
name: "Alternative Name",
htmlbody: htmlText,
attachments: [budgetPDF],
inLineImages: imageIdBlob
})
As I don't know the format of the file you can also use getAs().
Stéphane

How can i send confirmation mail send different from address?

I'm sending confirmation mail with following code in google docs scripts.
But It is sending from my personal gmail address. I need define different mail address. Cause I will use this for my company and mail need show like that sometest#companytsite.com
How can i do that?
My Code:
function Initialize() {
var triggers = ScriptApp.getScriptTriggers();
for (var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
ScriptApp.newTrigger("SendConfirmationMail")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onFormSubmit()
.create();
}
function SendConfirmationMail(e) {
try {
var ss, cc, sendername, subject, columns;
var message, value, textbody, sender;
// This is your email address and you will be in the CC
cc = Session.getActiveUser().getEmail();
// This will show up as the sender's name
sendername = "Your Name Goes Here";
// Optional but change the following variable
// to have a custom subject for Google Docs emails
subject = "Google Form Successfully Submitted";
// This is the body of the auto-reply
message = "We have received your details.<br>Thanks!<br><br>";
ss = SpreadsheetApp.getActiveSheet();
columns = ss.getRange(1, 1, 1, ss.getLastColumn()).getValues()[0];
// This is the submitter's email address
sender = e.namedValues["Email Address"].toString();
// Only include form values that are not blank
for ( var keys in columns ) {
var key = columns[keys];
if ( e.namedValues[key] ) {
message += key + ' :: '+ e.namedValues[key] + "<br />";
}
}
textbody = message.replace("<br>", "\n");
GmailApp.sendEmail(sender, subject, textbody,
{cc: cc, name: sendername, htmlBody: message});
} catch (e) {
Logger.log(e.toString());
}
}
According to the documentation: https://developers.google.com/apps-script/reference/gmail/gmail-app#sendEmail(String,String,String,Object)
You should be able to pass in a from in the options.
GmailApp.sendEmail(sender, subject, textbody, {
from: "sometest#companytsite.com",
cc: cc,
name: sendername,
htmlBody: message
});
Nb. to avoid confusion sender should really be to
Now it also says that the email address you want to send it from must be an alias, to check you can print out getAliases() to see if it exists. If not you should be able to follow these instructions:
https://support.google.com/mail/answer/22370?hl=en

Google App Script - Send Mail from Google Form (needs subject line variable)

i'm new to google app scripting, and there's a lot i'm struggling to understand here.
i'm using this script below.
i'm trying to take a line from the form submission (that states the location of where it was submitted from) and add it to the email SUBJECT line that is sent by this script. this will allow me to sort in my email box by the location they are submitted from.
here are the contents below. is there an e.value i need to use? do i need to define another variable and add it with a + to the subject string?
function sendFormByEmail(e)
{ var email = "workemails#mydomain.com";
var subject = "Maintenance Submission Form";
var message = ""; for(var field in e.namedValues) { message += field + ' :: ' + e.namedValues[field].toString() + "\n\n";
} MailApp.sendEmail(email, subject, message);
}
Just concatenate it with the existing subject like this:
function sendFormByEmail(e) {
var email = "workemails#mydomain.com";
var subject = "Maintenance Submission Form";
var message = "";
for(var field in e.namedValues) {
message += field + ' :: ' + e.namedValues[field].toString() + "\n\n";
}
//get location from field named locationFieldNameGoesHere and
//prepend it to the standard subject line
subject=e.namedValues['locationFieldNameGoesHere'].toString() + subject;
MailApp.sendEmail(email, subject, message);
}