D T
D T

Reputation: 3746

Why can't get current email outside domain?

I want get email of user opening file:

This is my code getting email, but this code only can get email of users have domain the same with my domain, other domain will return empty:

function onOpen(e) {
 Browser.msgBox("hi " +Session.getActiveUser().getEmail());  
}

Why can't get current email outside domain?

Can get email of outside domain?

Upvotes: 0

Views: 87

Answers (1)

Andres Duarte
Andres Duarte

Reputation: 3340

You can get the email but not inside an onOpen() function and neither in other circumstances that are well explained in the documentation [1]:

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 runs the script themselves or belongs to the same G Suite domain as the user.

A possible workaround in your case, would be to create a menu [2] that when clicked will call the function you want, but previously it'll present the consent screen to allow the permissions needed. Example:

function onOpen() {
  SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
  .createMenu('Actions')
  .addItem('Welcome', 'showEmail')
  .addToUi();  
}

function showEmail() {
 Browser.msgBox("hi " + Session.getActiveUser().getEmail());  
}

[1] https://developers.google.com/apps-script/reference/base/user

[2] https://developers.google.com/apps-script/guides/menus

Upvotes: 2

Related Questions