Google Script: MailApp.sendEmail to multiple addresses? - email

I have a script that is using the following script:
MailApp.sendEmail(row.shiftManager, "Holiday Approval Request", "", {htmlBody: message});
row.state = STATE_PENDING;
Howeverm I would like to also send the same mail to row.shiftSupervisor, this is probably something really simple that I've overlooked, but I figured someone here would know straight away what it was.
Cheers for your help :)
Edit - I tried to use:
MailApp.sendEmail(row.shiftManager, row.shiftSupervisor, "Holiday Approval Request", "", {htmlBody: message});
row.state = STATE_PENDING;
But no joy.
Edit 2 - I got it working with:
MailApp.sendEmail(row.shiftManager, "Holiday Approval Request", "", {htmlBody: message});
MailApp.sendEmail(row.shiftSupervisor, "Holiday Approval Request", "", {htmlBody: message});
row.state = STATE_PENDING;
Not the most graceful looking piece of code, but it does the job...

The email addresses can be concatenated (joined together) using the plus sign with a comma in between each email address. In JavaScript the plus sign can be used for addition OR joining strings. The plus sign is both an addition operator and a string operator in JavaScript. Strings are text, and if you use the plus sign to concatenate text strings then it's a string formula.
One solution would be:
var recipient = row.shiftManager + "," + row.shiftSupervisor;
MailApp.sendEmail(recipient, "Holiday Approval Request", "", {htmlBody: message});
In the above example, there are 4 parameters. But MailApp.sendEmail() has multiple possible parameter structures. The following example shows all of the settings put into an object, where the "to" key in the object is for the recipient.
MailApp.sendEmail({
to: recipient,
cc: recipientsCC,
subject: Subject,
htmlBody: html
});
A complete example:
function sendToMultiple() {
var message = "This is a test of HTML <br><br> Line two";
var recipientsTO = "example#gmail.com" + "," + "example#yahoo.com";
var recipientsCC = "example#gmail.com";
var Subject = "Vacation Approval Request";
var html = message;
MailApp.sendEmail({
to: recipientsTO,
cc: recipientsCC,
subject: Subject,
htmlBody: html
});
}
Documentation with an example is at the following link:
Google Documentation - MailApp.sendEmail

Here is how I'm doing it:
//check quota and log
const emailsLeft = MailApp.getRemainingDailyQuota();
console.log( emailsLeft + " emails left in quota");
//get list of emails from spreadsheet itself
//filter out empty rows
const emails = getTab("Config").getRange("D2:D").getValues().map(function(el){ return el[0]; }).filter(function(el){ return el != '' });
//send emails from NO_REPLY email, subject and HTML body
MailApp.sendEmail({
to: emails.join(","),
subject: subject,
htmlBody: html,
noReply: true
});
function getTab(name) {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
return sheet.getSheetByName(name);
}
getTab() and other helper functions can be found here
https://github.com/tim-kozak/google-spreadsheet-helpers

Related

Google Sheets App Script- Add signature when sending e-mail

I'm working on a script that will save my Google Sheet spreadsheet as a pdf and email it as an attachment. The code I'm using works, but I don't know how to add a signature to the email I'm sending. Is this possible, and if so; what would be the cleanest way to do it? Here's the code I'm working with. I know, it's not pretty.
function displayPrompt() {
var ss=SpreadsheetApp.getActiveSpreadsheet();
var sheetName = ss.getActiveSheet().getName();
var ui = SpreadsheetApp.getUi();
var result = ui.prompt("Please enter email body");
//Get the button that the user pressed.
var button = result.getSelectedButton();
var message = {
to: "someone#somewhere.com",
subject: sheetName,
body: "Hi team,\n\nPlease find attached the quote that you requested.\n" +
result.getResponseText() + "\nThank you,\nMe",
name: "My Name",
attachments:
[SpreadsheetApp.getActiveSpreadsheet().getAs(MimeType.PDF).setName("Quote")]
}
if (button === ui.Button.OK) {
Logger.log("The user clicked the [OK] button.");
Logger.log(result.getResponseText());
MailApp.sendEmail(message);
} else if (button === ui.Button.CLOSE) {
Logger.log("The user clicked the [Cancel] button.");
}
}
I believe your goal as follows.
You want to add the signature to the message of Gmail using MailApp.sendEmail
In this case, I think that there are 2 patterns.
Pattern 1:
In this pattern, by declaring the signature as the variable, the signature is added.
Sample script:
Please modify message in your script as follows.
var signature = "\nsample signature"; // Added
var message = {
to: "someone#somewhere.com",
subject: sheetName,
body: "Hi team,\n\nPlease find attached the quote that you requested.\n" + result.getResponseText() + "\nThank you,\nMe" + signature, // Modified
name: "My Name",
attachments: [SpreadsheetApp.getActiveSpreadsheet().getAs(MimeType.PDF).setName("Quote")]
}
Pattern 2:
In this pattern, by retrieving the sigunature of Gmail, the signature is added.
Sample script:
In this sample, Gmail API is used. So, before you use this script, please enable Gmail API at Advanced Google services. And, please modify message in your script as follows.
var signature = "<br>" + Gmail.Users.Settings.SendAs.list("me").sendAs[0].signature; // Added
var message = {
to: "someone#somewhere.com",
subject: sheetName,
htmlBody: ("Hi team,\n\nPlease find attached the quote that you requested.\n" + result.getResponseText() + "\nThank you,\nMe").replace(/\n/g, "<br>") + signature, // Added
name: "My Name",
attachments: [SpreadsheetApp.getActiveSpreadsheet().getAs(MimeType.PDF).setName("Quote")]
}
The signature retrieved from Gmail is HTML. So in this pattern, htmlBody is used instead of body.
References:
Method: users.settings.sendAs.list

Google Form mail notification script. Emails always have "me" as sender

I have tried to use the search function, but did not find a solution for my problem, or I do not understand enough yet.
I have written a script for google forms, that sends an automatic email to two email addresses, when an user submits the form. I have build in some information that should show in the email subject and puts the input from the forms into the email, with some simple HTML formatting.
My problem is, that the emails always have my Email address as the sender (the account I used for creating the form)
I would like to have the senders email, the one that is submitting the form.
How is that possible?
Here is the code:
function sendFormByEmail(e)
{
// Sent to Email address
var email1 = "123#abc.com";
var email2 = "345#abc.com";
// Variables
var s = SpreadsheetApp.getActiveSheet();
var headers = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];
var txt = "";
var subject = "Example text: ";
// Var e = form input as array.
// Loop through the array.
for(var i in headers){
txt += "<b>" + headers[i] + '</b>' + ': '+
e.namedValues[headers[i]].toString() + '<br><br>';
}
// Insert variables from the spreadsheet into the subject.
// Create email subject
subject += "Example text " + e.namedValues[headers[2]].toString();
// Send the email
MailApp.sendEmail(email1, subject, "", {htmlBody:txt});
MailApp.sendEmail(email2, subject, "", {htmlBody:txt});
}
It is not possible to send the mail as the user who submitted the form as the script is running from the user account and the mailapp will send the mail from that account only. you can change the display name according to the user name who submiited the form by the parameter name. Also you can change the email to noreply#domainName.com by adding the parameter noReply in mailApp syntax. However you cannot change it to the user who submitted the form
You can refer this documentation for the above parameters : https://developers.google.com/apps-script/reference/mail/mail-app
Hope this could help

GmailApp.sendEmail() doesn't parse plain text when sending HTML mail. How can I make it to show plain text?

I have a document with email body content. I am using Apps Script to fetch the document from URL and send it as an HTML mail.
var url = "address of the document";
var param = {method : "get",
headers : {"Authorization": "Bearer " +ScriptApp.getOAuthToken()}, muteHttpExceptions:true,
};
var html = UrlFetchApp.fetch(url,param).getContentText();
MailApp.sendEmail(
emailId, // recipient
tempSubject, // subject
body,
{ // body
htmlBody: html, // advanced options
});
However, if my document has text like this for example:
Hi
username: rml#gmail.com
password : <aSrD9nn
Happy browsing!
In the resultant email, the text after password: is blank. It does not show in the mail body of the email sent. Apparently, it considers < as an opening tag, I think.
Is there a way to solve this? I tried with other text and it works fine.
How do I overcome this problem? Any help will be much appreciated.

How to insert an emoji into an email sent with GmailApp?

I have a GAS script that sends automated emails and would like to include a couple of emojis. I've tried using shortcodes and copying/pasting, but nothing so far seems to have worked. Just wanted to see if there was anything I was missing.
Edit: Here's the code:
var title = rowData.publicationTitle;
var journal = rowData.journalTitle;
var url = rowData.publicationUrl;
//Emoji goes here in the body:
var body = "Hi " + firstName + "!<br><br>I noticed your article <a href='" + url + "'>“" + title + "”</a> was recently published in <i>" + journal + "</i>. Congratulations! This is just a friendly reminder to please upload your original document and a PDF version to our publications app when you have time.<br><br>To upload your publication, you can <a href='http://support.cpes.vt.edu/publishing'>click here</a>.<br><br>Thanks!<br><br>🤖 CB<br><br><hr style='background-color: #d8d8d8; border: 0 none; color: #d8d8d8; height: 1px;'><span style='font-size:12px'><b>CPES Publications Reminders</b> | <a href='mailto:leshutt#vt.edu' style='text-decoration:none'>Feedback</a> | <a href='http://support.cpes.vt.edu/publishing' style='text-decoration:none;'>Publication uploads</a></span>";
var emailSubject = "Just a reminder to upload your article!";
var me = Session.getActiveUser().getEmail();
var aliases = GmailApp.getAliases();
if (emailStatus == "Pending" && emailData !== "No emails found") {
GmailApp.sendEmail(email, emailSubject, body, {
from: aliases[2],
name: "CPES Bot",
htmlBody: body
});
}
I've noticed that sending a star ("⭐") works, but the normal smiley ("😊") shows up as a black-and-white, Unicode-esque icon and everything else I've tried are question marks. Can you only use emojis up to a certain Unicode release?
You want to send an email with HTML body including the emoji. If my understanding is correct, how about this modification?
About GmailApp and MailApp :
Unfortunately, GmailApp cannot use the recent emoji characters. At GmailApp
emoji less than Unicode 5.2 can be used for this situation.
emoji more than Unicode 6.0 can NOT be used for this situation.
MailApp can use all versions of emoji.
"⭐" is Unicode 5.1. But "😊" is Unicode 6.0. By this, in your script using GmailApp, you can see the former, but you cannot see the latter. At a sample script of Michele Pisani, the latter is sent using MailApp. So the character is not broken. "🤖" is Unicode 8.0.
Modification points :
So in the case of your script, the modification points are as follows.
Use MailApp instead of GmailApp.
OR
Use Gmail API.
From your comments to Michele Pisani, I worry about that MailApp might not work for your situation. So I would like to also propose the method using Gmail API.
1. Modified your script
Please modify as follows.
From :
GmailApp.sendEmail(email, emailSubject, body, {
To :
MailApp.sendEmail(email, emailSubject, body, {
2. Using Gmail API
In order to use this, please enable Gmail API at Advanced Google Services and API console as follows.
Enable Gmail API v1 at Advanced Google Services
On script editor
Resources -> Advanced Google Services
Turn on Gmail API v1
Enable Gmail API at API console
On script editor
Resources -> Cloud Platform project
View API console
At Getting started, click Enable APIs and get credentials like keys.
At left side, click Library.
At Search for APIs & services, input "Gmail". And click Gmail API.
Click Enable button.
If API has already been enabled, please don't turn off.
If now you are opening the script editor with the script for using Gmail API, you can enable Gmail API for the project by accessing this URL https://console.cloud.google.com/apis/api/gmail.googleapis.com/overview
Sample script :
function convert(email, aliase, emailSubject, body) {
body = Utilities.base64Encode(body, Utilities.Charset.UTF_8);
var boundary = "boundaryboundary";
var mailData = [
"MIME-Version: 1.0",
"To: " + email,
"From: CPES Bot <" + aliase + ">",
"Subject: " + emailSubject,
"Content-Type: multipart/alternative; boundary=" + boundary,
"",
"--" + boundary,
"Content-Type: text/plain; charset=UTF-8",
"",
body,
"",
"--" + boundary,
"Content-Type: text/html; charset=UTF-8",
"Content-Transfer-Encoding: base64",
"",
body,
"",
"--" + boundary,
].join("\r\n");
return Utilities.base64EncodeWebSafe(mailData);
}
function myFunction() {
// Please declare email and firstName.
var title = rowData.publicationTitle;
var journal = rowData.journalTitle;
var url = rowData.publicationUrl;
//Emoji goes here in the body:
var body = "Hi " + firstName + "!<br><br>I noticed your article <a href='" + url + "'>“" + title + "”</a> was recently published in <i>" + journal + "</i>. Congratulations! This is just a friendly reminder to please upload your original document and a PDF version to our publications app when you have time.<br><br>To upload your publication, you can <a href='http://support.cpes.vt.edu/publishing'>click here</a>.<br><br>Thanks!<br><br>🤖 CB<br><br><hr style='background-color: #d8d8d8; border: 0 none; color: #d8d8d8; height: 1px;'><span style='font-size:12px'><b>CPES Publications Reminders</b> | <a href='mailto:leshutt#vt.edu' style='text-decoration:none'>Feedback</a> | <a href='http://support.cpes.vt.edu/publishing' style='text-decoration:none;'>Publication uploads</a></span>";
var emailSubject = "Just a reminder to upload your article!";
var me = Session.getActiveUser().getEmail();
var aliases = GmailApp.getAliases();
if (emailStatus == "Pending" && emailData !== "No emails found"){
// Added script
var raw = convert(email, aliases[2], emailSubject, body);
Gmail.Users.Messages.send({raw: raw}, "me");
}
}
Note :
When you use this sample, Please declare email and firstName.
Please run myFunction().
References :
Emojipedia
Advanced Google Services
Gmail API
If I misunderstand your question, I'm sorry.
I tried to copy the emoji (https://www.emojicopy.com/) and paste it directly into the script editor:
and after sending the email I received it in my mailbox:
Edit:
Be careful that some emoji are one character length (like the star) but other are 2 characters (like the smile) for those with 2 characters you can think of writing immediately after the smile but instead you are writing inside the smile so you break it therefore turns in question mark.
If you try to run this code, you will see that the first has length 2 and the second one has length 1:
If you try to move the pointer (in the apps script editor) on those 2 emoticons, from before to after the emoticon, you will see that in the case of the star just one step but for the smile you need 2 steps.
The easiest complete answer that also works with SMS recipients is this:
function testNewMail() {
MailApp.sendEmail({
to: "yourphonenumbergoeshere#mymetropcs.com",
subject: "Logos",
htmlBody: "😊 hi todd happy day"
});
}
Use code points (💎) in the value of your cell and send your message as HTML:
var sheet = SpreadsheetApp.getActiveSheet();
var value = sheet.getRange("A1").getValue();
GmailApp.sendEmail(
"recipient#example.com",
"subject",
"",
{
from: "sender#example.com",
htmlBody: value
}
);

Error while trying to use the "reply-to" in google apps script

I'm using google apps script to get the responses of a specific form in an specific e-mail,
What I'm trying to do is use a google form to open support tickets, so people need fill some fields like, title, description and e-mail,
And when they submit the form, it will automatically open a ticket, but the e-mail will be always from the owner of the form, and this was a problem because we want that the person who opened the ticket receives email updates, so what I'm trying to do is this:
I put a field in the form asking the persons email, and I'm trying to put that e-mail into the reply-to...
And apparently I'm in the right way to catch that e-mail but the reply-to don't show the email that the persons filled the box, it appears an error: [Ljava.lang.Object;#34dfe075
Does any one can help me?
Here is my script:
function Initialize() {
var triggers = ScriptApp.getProjectTriggers();
for(var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
ScriptApp.newTrigger("SendGoogleForm")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onFormSubmit()
.create();
}
function SendGoogleForm(e)
{
try
{
var email = "support#email.com";
var form = e.namedValues;
var subject = form["Title"];
var s = SpreadsheetApp.getActiveSheet();
var columns = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];
var message = "";
for ( var keys in columns ) {
var key = columns[keys];
if ( e.namedValues[key] && (e.namedValues[key] != "") ) {
message += key + ' :: '+ e.namedValues[key] + "\n\n";
}
}
GmailApp.sendEmail(email, subject, message, {replyTo: form["E-mail"], from: "support#email.com"});
} catch (e) {
Logger.log(e.toString());
}
}
And here is the output of this:
from: support#email.com
reply-to: [Ljava.lang.Object;#34dfe075
to: support#email.com
date: Fri, Oct 17, 2014 at 10:55 AM
subject: New Test
The reply to, is broken :(
The values returned in the e.namedValues property are arrays, so you must access them as such.
Modify your sendEmail line as follows:
GmailApp.sendEmail(email, subject, message, {replyTo: form["E-mail"][0], from: "support#email.com"});
Note the [0] array index on the form["E-Mail"] field, indicating you want the first value in that array, which will be the email address entered.
See the example next to "e.namedValues" here: https://developers.google.com/apps-script/guides/triggers/events#google_sheets_events