Google Apps Script lost access rights - email

I have a Google Sheets script that emails a notification to a group of people when a form is submitted. It worked beautifully for months. Now it seems to have lost the access rights to send the emails. November 6, 2015 was the last time responses were submitted and successfully emailed. No more responses were submitted until yesterday (Sept 21, 2016) and it no longer has rights to send email. I verified that it is not listed in my Google account's security section under my "apps connected to your account".
I tried to re-authorize it by deleting all the triggers, saving and closing out the script. Then I reopened it and added the triggers back in. It didn't ask for a new authorization, but it still won't send emails.
Does anyone know why it might lose access rights? Does it get removed if it's not used periodically?
How do I force it to refresh/renew rights? Or do I just have to delete the script entirely and recreate a fresh copy?
This is just one of many similar scripts that I have so, I need to figure out how to make them work (and keep them working). Searching around I couldn't find anything except how to intentionally revoke access rights.
Here is my code so you can see what it's trying to do (I'm testing it with just my email address right now). I will admit I don't know a lot about programming scripts, so it may not be very pretty.
Thanks for any help!
function sendFormByEmail(e)
{
// Remember to replace this email address with your own email address
var email = "bjwarneke#gmail.com";
var quiz = "02.8-JLOT-D Drop-In";
var filename = "02-JLOT Exam Grading Instructions";
var s = SpreadsheetApp.getActiveSheet();
var headers = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];
var message = "Time for someone to go grade a quiz from me!" + "<br>";
var replyto = e.namedValues[headers[1]].toString();
var subject = 'Quiz: ' + replyto;
//message += headers[1] + ': '+ e.namedValues[headers[1]].toString() + "\n";
//message += headers[0] + ': '+ e.namedValues[headers[0]].toString() + "\n";
message += headers[1] + ': '+ e.namedValues[headers[1]].toString() + "<br>";
message += headers[0] + ': '+ e.namedValues[headers[0]].toString() + "<br><br>";
message += quiz + "<br>";
message += ''+filename+'<br>';
// The variable e holds all the form values in an array.
// Loop through the array and append values to the body.
//for(var i in headers)
//message += headers[i] + ': '+ e.namedValues[headers[i]].toString() + "\n\n";
// Insert variables from the spreadsheet into the subject.
// In this case, I wanted the new hire's name and start date as part of the
// email subject. These are the 3rd and 16th columns in my form.
// This creates an email subject like "New Hire: Jane Doe - starts 4/23/2013"
//subject += e.namedValues[headers[2]].toString() + " - starts " + e.namedValues[headers[15]].toString();
// Send the email
MailApp.sendEmail(email, subject, message, {htmlBody:message, name:"Quiz", replyTo:replyto});
// Based off of a script originally posted by Amit Agarwal - www.labnol.org
// Credit to Henrique Abreu for fixing the sort order
}

Do you have a Gmail account associated with your Google Account? The MailApp service will only work if you have Gmail enabled for your account.

Related

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

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
}
);

Send Mail : Intent.EXTRA_EMAIL does not work

I get no error but the mail-to will not be showed ! it stays empty
public void Send_Mail(View view) {
String txt_context = "My comment about the App : \n The App is good but does not support v3";
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setData(Uri.parse("mailto:"));
intent.setType("message/rfc822"); //
intent.putExtra(Intent.EXTRA_EMAIL,"receiver#gmail.com"); // **this will not displayed** """
intent.putExtra(Intent.EXTRA_SUBJECT,"Comment about the APP");
intent.putExtra(Intent.EXTRA_TEXT,txt_context);
startActivity(intent);
I know this post is old but I encountered the same issue and I found the solution (in the official documentation):
As explained, Intent.EXTRA_EMAIL is:
A String[] holding e-mail addresses that should be delivered to.
So to fix your issue, instead of:
intent.putExtra(Intent.EXTRA_EMAIL,"receiver#gmail.com");
do:
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"receiver#gmail.com"});
This is how you correctly send an email via an intent. The URI arguments are required if not you will have problems getting Gmail to receive your emails.
Intent send = new Intent(Intent.ACTION_SENDTO);
String uriText = "mailto:" + Uri.encode("email#gmail.com") +
"?subject=" + Uri.encode("the subject") +
"&body=" + Uri.encode("the body of the message");
Uri uri = Uri.parse(uriText);
send.setData(uri);
startActivity(Intent.createChooser(send, "Send mail..."));
The disadvantage of doing it your way is that it gives gmail issues retrieving the address to send the mail to, and so many apps support message/rfc822so your user can get drowned in different clients. I advice you use
Intent sendMail = new Intent(Intent.ACTION_SENDTO);
String uriText = "mailto:" + Uri.encode("example#gmail.com") +
"?subject=" + Uri.encode("subject") +
"&body=" + Uri.encode("body);
Uri uri = Uri.parse(uriText);
sendMail.setData(uri);
startActivity(Intent.createChooser(sendMail, "Choose a client"));
as this is a bit more specific than specifying with intent.setType("message/rfc822"); and solves the issue with gmail. Good Luck.
For kotlin
The emial must be an arrayOf, nos just a string.
intent.putExtra(Intent.EXTRA_EMAIL, arrayOf("receiber#gmail.com"))

Google Form - One form submission sends two (unique) emails

Please excuse my possibly "lame" question here. I have searched everywhere and have not been able to find a solution.
Google forms -
I have one form that collects two email addresses.
I need to have each email entered into the form receive a "unique" response when the form is submitted.
Below is an example of the code I've been "trying" to make work. (Where I only get the latter email to send)
I thank you in advance for your time.
Oliver
// this would be the first email sent to e.values[3] - the first email on the form
function formSubmitReply(e) {
var userEmail = e.values[3];
MailApp.sendEmail(
userEmail,
"Help Desk Ticket1",
"Thanks for submitting your issue. \n\nWe'll start " +
"working on it as soon as possible. \n\nHelp Desk",
{name:"Help Desk"}
);
}
// this would be the second email sent to e.values[4] - the second email on the form
function formSubmitReply(e) {
var userEmail = e.values[4];
MailApp.sendEmail(
userEmail,
"Help Desk Ticket - FYI form is sent",
"The form a has been submitted. \n\nWe need to start " +
"working on it as soon as possible. \n\nThe Reger Group",
{name:"The Reger Group"}
);
}
This is a blind shot (haven't tested), but here is my guess: you are creating the same function twice, thus the second replaces the first one. Functions are unique, if you can only have one function as callback of the form submission, you should adapt it to do everything you need within the one function call.
Here's what you could do:
// Sends distinct messages for each recipient
function formSubmitReply(e) {
// First mail recipient and message
MailApp.sendEmail(
e.values[3],
"Help Desk Ticket1",
"Thanks for submitting your issue. \n\nWe'll start " +
"working on it as soon as possible. \n\nHelp Desk",
{name:"Help Desk"}
);
// Second mail recipient and message
MailApp.sendEmail(
e.values[4],
"Help Desk Ticket - FYI form is sent",
"The form a has been submitted. \n\nWe need to start " +
"working on it as soon as possible. \n\nThe Reger Group",
{name:"The Reger Group"}
);
}

setting up script to include google docs form data in email notification

I've setup a form using googledocs. I just want to have the actual data entered into the form emailed to me, as opposed to the generic response advising that the form has been completed.
I have no skill or experience with code etc, but was sure i could get this sorted. I've spent hours+hours and haven't had any luck.
My form is really basic.it has 5 fields. 4 of which are just text responses, and one multiple choice.
I found this tute online (http://www.labnol.org/internet/google-docs-email-form/20884/) which i think sums up what i'm trying to do, but have not been able to get it to work.
from this site i entered the following code:
function sendFormByEmail(e)
{
var email = "reports.mckeir#gmail.com";
var subject = "Google Docs Form Submitted";
var s = SpreadsheetApp.getActiveSheet();
var headers = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];
var message = "";
for(var i in headers)
message += headers[i] + ' = '+ e.namedValues[headers[i]].toString() + "\n\n";
MailApp.sendEmail(email, subject, message);
}
To this, i get the following response: ->
Your script, Contact Us Form Mailer, has recently failed to finish successfully. A summary of the failure(s) is shown below. To configure the triggers for this script, or change your setting for receiving future failure notifications, click here.
The script is used by the document 100% Club.
Details:
Start Function Error Message Trigger End
12/3/12 11:06 PM sendFormByEmail TypeError: Cannot call method "toString" of undefined. (line 12) formSubmit 12/3/12 11:06 PM
Is anyone able to help shed some light on this for me? I'm guessing i'm not including some data neeeded, but i honestly have no clue.
Workaround http://www.labnol.org/internet/google-docs-email-form/20884/
You have to setup app script to forward the data as email.
I'll point to the comment above that solved it for me: https://stackoverflow.com/a/14576983/134335
I took that post a step further:
I removed the normal notification. The app script makes that generic text redundant and useless now
I modified the script to actually parse the results and build the response accordingly.
function sendFormByEmail(e)
{
var toEmail = "changeme";
var name = "";
var email = "";
// Optional but change the following variable
// to have a custom subject for Google Docs emails
var subject = "Google Docs Form Submitted";
var message = "";
// The variable e holds all the form values in an array.
// Loop through the array and append values to the body.
var s = SpreadsheetApp.getActiveSheet();
var headers = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];
// Credit to Henrique Abreu for fixing the sort order
for(var i in headers) {
if (headers[i] = "Name") {
name = e.namedValues[headers[i]].toString();
}
if (headers[i] = "Email") {
email = e.namedValues[headers[i]].toString();
}
if (headers[i] = "Subject") {
subject = e.namedValues[headers[i]].toString();
}
if (headers[i] = "Message") {
message = e.namedValues[headers[i]].toString();
}
}
// See https://developers.google.com/apps-script/reference/mail/mail-app#sendEmail(String,String,String,Object)
var mailOptions = {
name: name,
replyTo: email,
};
// This is the MailApp service of Google Apps Script
// that sends the email. You can also use GmailApp here.
MailApp.sendEmail(toEmail, subject, message, mailOptions);
// Watch the following video for details
// http://youtu.be/z6klwUxRwQI
// By Amit Agarwal - www.labnol.org
}
The script utilized in the example is extremely generic but very resilient to change because the message is built as a key/value pair of the form fields submitted.
If you use my script you'll have to tweak the for loop if statements to match your fields verbatim. You'll also want to edit the toEmail variable.
Thanks again for the question and answers. I was about to ditch Google Forms as the generic response was never enough for what I was trying to do.
Lastly, in response to the actual problem above "toString of undefined" specifically means one of the form fields was submitted as blank. If I had to guess, I would say the author only used this for forms where all the fields were required or a quick undefined check would've been put in place.
Something like the following would work:
for(var i in headers) {
var formValue = e.namedValues[headers[i]];
var formValueText = "";
if (typeof(formValue) != "undefined") {
formValueText = formValue.toString();
}
message += headers[i] + ' = '+ formvalueText + "\n\n";
}
I haven't tested this precisely but it's a pretty standard way of making sure the object is defined before trying methods like toString() that clearly won't work.
This would also explain Jon Fila's answer. The script blindly assumes all of the header rows in the response are sent by the form. If any of the fields aren't required or the spreadsheet has fields that are no longer in the form, you'll get a lot of undefined objects.
The script could've been coded better but I won't fault the author as it was clearly meant to be a proof of concept only. The fact that they mention the replyTo correction but don't give any examples on implementing it made it perfectly clear.
If this is a Google Form, do you have any extra columns in your spreadsheet that are not on the form? If you delete those extra columns then it started working for me.
You don't need to use a script. Simply go to Tools >> Notification Rules on your Google Spreadsheet. There you can change the settings to receive an email with your desired information every time the document is changed.