Automatic Notification when Google Doc is opened - google-apps-script

I have a Google Apps Script that contains the following code:
function onOpen() {
var emailAddress = "jthfortyone#gmail.com";
var message = "Viewed"
var subject = "Someone Viewed Your Resume";
MailApp.sendEmail(emailAddress, subject, message);
}
I want to receive an email every time someone views my resume
But for some reason I only receive an email if I am the one open it and not when anyone else does.
What do I need to change to get the desired results?

Your container-bound script in a shared document will only run if:
Sharing has granted edit privileges. (Viewing and Commenting aren't enough.)
User is logged in with a Google account. (Only scripts run as webapps can be triggered anonymously, at which time they run as the owner. No such option, in this case.)
User agrees to authorize the script. (A script that sends emails will require authorization.)
Since this is your resume, I think you're going to need to find another solution.

The onOpen trigger should run in response to the active user opening the document.
The active user is defined as:
The user (Google account) that causes a script to execute. Depending on the execution method this may be different from the effective user. You can also think of this as the user at the keyboard
Have you tried accessing the document with a dummy account?

Related

MailApp.sendEmail -> mail coming from different accounts

I am using a script in a shared spreadsheet to send update emails to the working team.
I am using a simple call:
MailApp.sendEmail(mail_address, subject, msg);
It worked fine for some time.. But now I have a strange behavior: the script runs successfully but the emails are actually sent randomly by one of the users which the spreadhsheet is shared with..
I can't understand how that is possible since they are not shared accounts and it shouldn't be possible to send emails like that..
Edit: The script is executed by a trigger based on the editing of the spreadsheet.
Situation:
You have installed an onEdit trigger for all users which have edit access to the spreadsheet.
The function trigged by this trigger sends an email.
You are noticing that the emails are not always being sent by the user that edited the spreadsheet.
Issue:
The problem is that, as you can see here:
Installable triggers always run under the account of the person who created them.
This means the email will not be sent by the user that edited the spreadsheet, but by the one who installed the trigger. Since several users installed this trigger, your project might contain several duplicate triggers, each of which will run on behalf of a different account. Because of this, you might end up receiving multiple emails for one single spreadsheet edition, each of them sent by a different account.
Solution:
If you want to send a single email every time the spreadsheet is edited, and send this email from the account that edited the spreadsheet, you can use the methods getActiveUser() and getEffectiveUser():
Session.getActiveUser() refers to the current user, that is to say, the user that just edited the spreadsheet.
Session.getEffectiveUser() refers to the user under whose authority the script is running. That is to say, the user who installed the trigger.
The idea is to check whether the active user and the effective user are the same one, and send an email only if that's the case. This way, even if multiple functions are trigged by a single edition (one for each account that installed the trigger), only one email will be sent (the one corresponding to the user who edited the spreadsheet).
Code sample:
function onEditTrigger(e) {
var activeUser = Session.getActiveUser().getEmail();
var effectiveUser = Session.getEffectiveUser().getEmail();
if (activeUser === effectiveUser) {
// Rest of code
MailApp.sendEmail(mail_address, subject, msg);
}
}
Note:
If you have installed the trigger, you better not name your function onEdit: this name is reserved for a simple trigger.
Reference:
Installable triggers: Restrictions

What is the best practice for accessing users email addresses for Add Ons on Google Products

I'm building an add on that needs to check how many units a customer has left. This code works for me as the developer however, it doesn't work when users actually install the application.
// When someone opens the sheet for the first time
function onOpen(e) {
var ui = SpreadsheetApp.getUi()
.createAddonMenu()
.addItem('SMS', 'sms')
.addItem('EMAIL', 'email')
.addItem('SMS and EMAIL', 'emailAndSMS')
.addToUi();
}
// The function for the SMS Side Bar
// It is here I run the code for getting the users email address.
// Nothing is logged to the console at all.
function sms() {
var html = HtmlService.createHtmlOutputFromFile('sms').setTitle('Heartbeat SMS');
SpreadsheetApp.getUi().showSidebar(html);
var userEmail = Session.getActiveUser().getEmail();
Logger.log(userEmail); // Nothing gets logged to the console.
}
I expected to see users Email addresses being logged, however I get an empty string back
According to the documentation on getActiveUser():
The circumstances in which the email address is available vary: for example, the user's email address is not available in any context that allows a script to run without that user's authorization, like a simple onOpen(e) or onEdit(e) trigger, a custom function in Google Sheets, or a web app deployed to "execute as me" (that is, authorized by the developer instead of the user).
So having your app deployed will be one of these scenarios when they cannot use them. the documentation do goes on to say:
However, these restrictions generally do not apply if the developer runs the script themselves or belongs to the same G Suite domain as the user.
What this means is that if another user ran your script from, for example, the GAS editor, it would work. for your intention to work, they would need to somehow submit their address, be it in a form, a document or part of the add-on.

Google App script: You do not have permission to call prompt

I have created a google script that show me a prompt dialog to write a comment when a column is edited. For some reason this only works with my email (script's creator), but with the other users that I have shared the spreadsheet don't work. When I open the script editor with other user accounts I can see the error in the View -> Execution Transcript: Execution failed: You do not have permission to call prompt.
My script function has a name "sendManualEmail" and I already have the trigger created when Event -> From spreadsheet -> On edit
I even created a new project for only that script and asked me the permissions to send emails with my account, but still not working for other users. I have read some other similar topic with same issue but I am still not able to fix mine. So thanks in advance for any comment!
You need your users to authorize your script. To do that, create a menu that activates on onOpen(). When clicked, send a message box, ensuring your users have to authorize your scripts to see the message.
Paste the following at the top of your script:
/** #OnlyCurrentDoc */
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('myName') // your name
.addItem("Activate myName's script", 'activateMyStuff')
.addToUi();
}
function activateMyStuff() {
browser.msgBox('Script is activated! thanks.');
}
Important: when your users click the menu, they will also be prompted to authorize your scripts and all the permissions on the script's page. Make sure you clean up that script, otherwise your users may have to authorize weird things - and likely won't. Do test it with an alternate email address to see what others will see.
Lastly, consider publishing your script as an addon instead. It will make it that much easier for your users to authorize and use your work.
Are you logged into multiple Google accounts in the same browser?
Google Scripts insides may sometimes not work as expected when multiple accounts are authorized in the same browser session. Try logging out of all accounts except the one that owns the script.

onEdit trigger doesn't catch current user

I'm trying to build a simple log for sheets that makes use of cell notes.
Somehow i can't include the email of the user who triggers the onEdit-event.
function onEdit(e){
var email = Session.getActiveUser().getEmail();
var date = String(Utilities.formatDate(new Date(), 'Europe/Berlin', 'HH:mm dd/MM/yy'));
var range = e.range;
range.setNote(email + " # " + date);
}
The note appears on the cell but the email is empty. Could that have to do with missing permissions? I assume if something would be wrong with my code the note wouldn't appear at all on the edited cell in sheets...
Here's what Google documentation says about the Session class
The Session class provides access to session information, such as the
user's email address (in some circumstances) and language setting.
In regards to 'getActiveUser()' method, it states
If security policies do not allow access to the
user's identity, User.getEmail() returns a blank string. The
circumstances in which the email address is available vary: for
example, the user's email address is not available in any context that
allows a script to run without that user's authorization, like a
simple onOpen(e) or onEdit(e) trigger, a custom function in Google
Sheets, or a web app deployed to "execute as me" (that is, authorized
by the developer instead of the user). However, these restrictions
generally do not apply if the developer and the user belong to the
same G Suite domain.
Because you use the simple trigger - onEdit() - the code will not execute unless explicitly authorized by the user. For installable triggers, that would mean executing the function manually from the script editor.
You can publish the project as a sheets add-on. In this case, users will be asked to grant permissions declared in the add-on manifest.
More info https://developers.google.com/apps-script/reference/base/session

GmailApp requires the script to run as user and SpreadsheetApp requires authorization of the owner?

I have written a google apps script that captures information from my employees, and writes this in a spreadsheet which only I can access.It also mails the employee, what information they have filled.The script is embedded in my google site.
The problem is,I have to run the script as the owner to be able to edit the spreadsheet and to send the email the script has to be run as the 'user running the script'.
Probable solution is the above problem is to set the script's trigger onChnage i.e. on Change of the spreadsheet on any record / any row the Email relevant that email address on that row mail will be send.
Hope this helps
Given your scenario, you want your script to run in both modes - 'User executing the app' and as yourself which is clearly not possible. However, there are some workarounds you can use.
Set the script to run as the user accessing the app and change the permission of your spreadsheet to provide access to 'Anyone with the link'. That way, no other employee can access or discover the spreadsheet other than if they somehow know the spreadsheet id.
The other option is to set the scrip to run as yourself, keep the spreadsheet private and exploit the replyTo and name options of advanced arguments ( https://developers.google.com/apps-script/class_mailapp#sendEmail ). To the recipient, the email will 'appear' to have come from someone else.
Note, using option 2, you'll run into Issue 2004