Creates a custom "from" send-as alias with GAS and APIs - google-apps-script

hello I would like to add and send as parameter on gmail settings. for all my users, and change this to make a default account to send mail.
I know hot to do with the GUI, but I wold like to do with GAS.
the code for know is jus ¿t testing for a specific user.
Reference for Gmail API
var JSON = {
"private_key": "-----BEGIN PRIVATE KEY-----\\n-----END PRIVATE KEY-----\n",
"client_email": "client..#project-id-XXXXX.gserviceaccount.com",
"client_id": "12345800",
"user_email": "mainaccount#dominio.com"
};
function getOAuthService(user) {
return OAuth2.createService('Service Account')
.setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setPrivateKey(JSON.private_key)
.setIssuer(JSON.client_email)
.setSubject(JSON.user_email)
.setPropertyStore(PropertiesService.getScriptProperties())
.setParam('access_type', 'offline')
.setParam('approval_prompt', 'force')
.setScope('https://www.googleapis.com/auth/gmail.settings.sharing')
.setScope('https://www.googleapis.com/auth/gmail.settings.basic');
}
function createAlias() {
var userEmail = 'mainaccount#dominio.com';
var alias = {
alias: 'makealiasdefault#dominio.com'
};
alias = AdminDirectory.Users.Aliases.insert(alias, userEmail);
Logger.log('Created alias %s for user %s.', alias.alias, userEmail);
var service = getOAuthService();
service.reset();
if (service.hasAccess()) {
var url = 'https://www.googleapis.com/gmail/v1/users/'+userEmail+'/settings/sendAs'
var headers ={
"Authorization": 'Bearer ' + service.getAccessToken()
};
var options = {
'method':'post',
'headers': headers,
'method': 'GET',
'muteHttpExceptions': true
};
var response = UrlFetchApp.fetch(url, options);
}
Logger.log(response.getContentText());
var resource ={'sendAs':[
{'isDefault':true,
'verificationStatus':'accepted',
'sendAsEmail':alias.alias,
'treatAsAlias':true}]};
Logger.log(resource);
var sendas = Gmail.Users.Settings.SendAs.create(resource,alias.alias);
Logger.log(sendas);
}
function reset() {
var service = getOAuthService();
service.reset();
}
ANd I get an error Delegation denied for mainaccount#dominio.com
If i chagen this line var sendas = Gmail.Users.Settings.SendAs.create(resource,alias.alias);
for this
var sendas = Gmail.Users.Settings.SendAs.create(resource,userEmail);
I get a different error
Access restricted to service accounts that have been delegated domain-wide authority
The domain-wide was made follow this guide Domain-wide Delegation
Some knows how to create an send as wiht this proccess? or if something is bad with the code!

Below is a working example cleaned up from your source. A few issues with your original code:
The code seems to be trying to both make the raw UrlFetchApp.fetch HTTP call and use the Gmail library. The Gmail library is not designed to work with service accounts, it will only work against the current user which is not what you want, thus I've removed the Gmail library and I'm only using the Url Fetch.
You can only call setScope() once otherwise you overwrite the original scopes. If you have more than one scope to use, use a string with spaces between scopes.
I'm not really sure what you were trying to do with AdminDirectory, I've removed that entirely. If you want to make Admin SDK Directory API calls to create the alias email address for the user (receive mail) you'll need to add Directory scopes.
Naming your service account values to JSON is a bad idea as it overrides the JSON class of Apps Script, I've renamed the variable to service_account. Always a good idea to be specific with your variable names to avoid these kind of errors.
var service_account = {
"private_key": "-----BEGIN PRIVATE KEY...",
"client_email": "sa-email#example.com",
"client_id": "1234569343",
"user_email": "useraccount#example.com"
};
function getOAuthService(user) {
return OAuth2.createService('Service Account')
.setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setPrivateKey(service_account.private_key)
.setIssuer(service_account.client_email)
.setSubject(service_account.user_email)
.setPropertyStore(PropertiesService.getScriptProperties())
.setScope('https://www.googleapis.com/auth/gmail.settings.sharing https://www.googleapis.com/auth/gmail.settings.basic')
}
function createAlias() {
var userEmail = 'useraccount#example.com';
var alias = 'myalias#example.com';
var alias_name = 'Alias User';
var service = getOAuthService();
service.reset();
if (service.hasAccess()) {
var url = 'https://www.googleapis.com/gmail/v1/users/me/settings/sendAs'
var headers ={
"Authorization": 'Bearer ' + service.getAccessToken(),
"Accept":"application/json",
"Content-Type":"application/json",
};
var resource ={
'sendAsEmail': alias,
'displayName': alias_name
};
var options = {
'headers': headers,
'method': 'POST',
'payload': JSON.stringify(resource),
'muteHttpExceptions': true
};
Logger.log(options);
var response = UrlFetchApp.fetch(url, options);
Logger.log(response.getContentText());
}
}
function reset() {
var service = getOAuthService();
service.reset();
}
'''

Related

Using the BigQuery API on APP Scritps with a Service Account

I'm trying execute a job on BigQuery on a VPC project using App Scripts.
My goal is store the result in an array to create a dynamic prompt for DataStudio using community connectors
Using the following code:
function runQuery() {
var sql = "SELECT Distinct ss_cd FROM `vf-pt-ngbi-dev-gen-03.AEAD_DataSet_test.d_customer` WHERE end_dttm IS NOT NULL";
var queryResults;
var projectNumber = 'projectNumber'
// Inserts a Query Job
try {
var queryRequest = BigQuery.newQueryRequest();
queryRequest.setQuery(sql).setTimeoutMs(100000);
queryResults = BigQuery.Jobs.query(queryRequest, projectNumber);
}
catch (err) {
Logger.log(err);
return;
}
Since this is a VPC project I need to use a Service Account to perform this request?
However, I would like to know how to add this authorization?
Or exists another approach to execute a BigQuery job on a VPC project and store the results in an array?
You can get the service account token in apps script (see reference) then use that token for the REST API via UrlFetchApp.
Sample:
function runQuery() {
// ...
var service = getService();
if (service.hasAccess()) {
sendQuery(service);
}
// ...
}
function sendQuery(service){
var projectId = 'projectID';
var url = 'https://bigquery.googleapis.com/bigquery/v2/projects/' + projectId + '/queries';
// see request body for reference
// https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/query#QueryRequest
var body = {
// ...
}
var options = {
"method": "post",
"headers": {
"Authorization": "Bearer " + service.getAccessToken()
},
"contentType": "application/json",
"payload": JSON.stringify(body)
};
var response = UrlFetchApp.fetch(url, options);
}
// direclty copied from https://github.com/googleworkspace/apps-script-oauth2/blob/master/samples/GoogleServiceAccount.gs
function getService() {
return OAuth2.createService('BigQuery:' + USER_EMAIL)
// Set the endpoint URL.
.setTokenUrl('https://oauth2.googleapis.com/token')
// Set the private key and issuer.
.setPrivateKey(PRIVATE_KEY)
.setIssuer(CLIENT_EMAIL)
// Set the name of the user to impersonate. This will only work for
// Google Apps for Work/EDU accounts whose admin has setup domain-wide
// delegation:
// https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority
.setSubject(USER_EMAIL)
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getScriptProperties())
// Set the scope. This must match one of the scopes configured during the
// setup of domain-wide delegation.
.setScope('https://www.googleapis.com/auth/bigquery');
}
References:
BigQuery REST API
Creation of Service Account
Get Service Account Token
Note:
See a question containing a code what yours should look like.

Is it possible to access a deployed Protected Google Web App via URL without logging in from browser each time?

I've deployed a protected web app, and I'd like to trigger it without logging in each time:
I'd like to access the web app URL without logging in:
Based on this document, it's not possible without logging in from browser:
https://github.com/tanaikech/taking-advantage-of-Web-Apps-with-google-apps-script/blob/master/README.md
If the script of Web Apps uses some scopes, client users have to
authorize the scopes by own browser.
I'm assuming scopes means the web app is protected.
I've tried this: https://github.com/gsuitedevs/apps-script-oauth2/blob/master/samples/GoogleServiceAccount.gs but it asks for "request access"
If I click on request access, then it shows me this:
At this point, I'm thinking it's not possible to setup a service account with scope to trigger a protected deployed web app without authenticating through a browser each time. Can anyone confirm this?
My assumption is that the web app scope is https://www.googleapis.com/auth/drive since it has access to all drive's files.
Update: (What I tried but didn't work)
I matched the scope from the script:
To the service account:
The blurred area above is the client id i got from:
I've generated the access token using this script:
function accessTokens(){
var private_key = "-----BEGIN PRIVATE KEY-----*****\n-----END PRIVATE KEY-----\n"; // private_key of JSON file retrieved by creating Service Account
var client_email = "****#****.iam.gserviceaccount.com"; // client_email of JSON file retrieved by creating Service Account
var scopes = ["https://www.googleapis.com/auth/documents","https://www.googleapis.com/auth/forms","https://www.googleapis.com/auth/script.external_request","https://www.googleapis.com/auth/spreadsheets","https://www.googleapis.com/auth/userinfo.email"]; // Scopes
var url = "https://www.googleapis.com/oauth2/v3/token";
var header = {
alg: "RS256",
typ: "JWT",
};
var now = Math.floor(Date.now() / 1000);
var claim = {
iss: client_email,
scope: scopes.join(" "),
aud: url,
exp: (now + 3600).toString(),
iat: now.toString(),
};
var signature = Utilities.base64Encode(JSON.stringify(header)) + "." + Utilities.base64Encode(JSON.stringify(claim));
var jwt = signature + "." + Utilities.base64Encode(Utilities.computeRsaSha256Signature(signature, private_key));
var params = {
method: "post",
payload: {
assertion: jwt,
grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
},
};
var res = UrlFetchApp.fetch(url, params).getContentText();
Logger.log(res);
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sheet1");
sheet.getRange(1, 3).setValue(JSON.parse(res)['access_token']);
}
And still has the same error, it asks for request access.
After a couple days into this, I've figured it out (with help of course).
Get the scope from your deployed web app script: File > Project Properties > Scopes
Add the scope along with https://www.googleapis.com/auth/drive in page Manage API client access https://admin.google.com/AdminHome?chromeless=1#OGX:ManageOauthClients (use comma delimited to add multiple scopes: http...,http..., etc.)
For the client name, get the client id from the service account page in your admin console: https://console.developers.google.com
Deploy your script Publish > Deploy as Web App
After generating access token(instruction below), append the access token with your deployed web app url &access_token=YOURTOKENHERE
Use this script with a google sheet, it will generate the access_token in cell A1 of Sheet1 (Replace the 4 variables with the info relevant to you):
function accessTokens(){
var private_key = "-----BEGIN PRIVATE KEY-----n-----END PRIVATE KEY-----\n"; // private_key of JSON file retrieved by creating Service Account
var client_email = "*****#****.iam.gserviceaccount.com"; // client_email of JSON file retrieved by creating Service Account
var scopes = ["https://www.googleapis.com/auth/documents","https://www.googleapis.com/auth/forms","https://www.googleapis.com/auth/script.external_request","https://www.googleapis.com/auth/spreadsheets","https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/drive"]; // Scopes
var impersonate_email = "" //impersonate email
var url = "https://www.googleapis.com/oauth2/v4/token";
var header = {
alg: "RS256",
typ: "JWT",
};
var now = Math.floor(Date.now() / 1000);
var claim = {
iss: client_email,
sub: impersonate_email,
scope: scopes.join(" "),
aud: url,
exp: (now + 3600).toString(),
iat: now.toString(),
};
var signature = Utilities.base64Encode(JSON.stringify(header)) + "." + Utilities.base64Encode(JSON.stringify(claim));
var jwt = signature + "." + Utilities.base64Encode(Utilities.computeRsaSha256Signature(signature, private_key));
var params = {
method: "post",
payload: {
assertion: jwt,
grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
},
};
var res = UrlFetchApp.fetch(url, params).getContentText();
Logger.log(res);
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sheet1");
sheet.getRange(1, 1).setValue(JSON.parse(res)['access_token']);
}

0Auth2 problem to get my google photos libraries in a google sheet of mine

I am trying to follow documentation but never get the 0Auth2 to connect.
Btw I'm running the script manually from the google sheets scripting page, where should I get prompting for allowing access?
(I don't understand all this 0Auth2 scheme and I have already gave authorization to run the script and got client id and secret)...
See below my log and script routines (the first get to photo is still minimalistic as I didn't yet get through the 0Auth2 step ;-) .
Thanks in advance for any hint. I thought it would be trivial as it is my own sheet and google photo account...
Log:
[19-01-06 17:50:05:809 CET] starting
[19-01-06 17:50:05:810 CET] getPhotoService
[19-01-06 17:50:05:849 CET] false
[19-01-06 17:50:05:850 CET] redirectURI=https://script.google.com/macros/d/[REMOVED]/usercallback
[19-01-06 17:50:05:864 CET] Open the following URL and re-run the script: https://accounts.google.com/o/oauth2/auth?client_id=[removed].apps.googleusercontent.com&response_type=code&redirect_uri=https%3A%2F%2Fscript.google.com%2Fmacros%2Fd%2F[removed]%2Fusercallback&state=[removed]&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fphotoslibrary.readonly&login_hint=[removed]&access_type=offline&approval_prompt=force
Script:
function getPhotoService() {
// Create a new service with the given name. The name will be used when
// persisting the authorized token, so ensure it is unique within the
// scope of the property store.
Logger.log('getPhotoService');
return OAuth2.createService('gPHOTOfj')
// enable caching on the service, so as to not exhaust script's PropertiesService quotas
.setPropertyStore(PropertiesService.getUserProperties())
.setCache(CacheService.getUserCache())
// Set the endpoint URLs, which are the same for all Google services.
.setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
// Set the client ID and secret, from the Google Developers Console.
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
// Set the name of the callback function in the script referenced
// above that should be invoked to complete the OAuth flow.
.setCallbackFunction('authCallback')
//.setCallbackFunction('https://script.google.com/macros/d/'+SCRIPT_ID+'/authCallback')
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getUserProperties())
// Set the scopes to request (space-separated for Google services).
.setScope('https://www.googleapis.com/auth/photoslibrary.readonly')
// Below are Google-specific OAuth2 parameters.
// Sets the login hint, which will prevent the account chooser screen
// from being shown to users logged in with multiple accounts.
.setParam('login_hint', Session.getActiveUser().getEmail())
// Requests offline access.
.setParam('access_type', 'offline')
// Forces the approval prompt every time. This is useful for testing,
// but not desirable in a production application.
.setParam('approval_prompt', 'force');
}
function authCallback(request) {
Logger.log('Called back!');
var photoService = getPhotoService();
var isAuthorized = photoService.handleCallback(request);
if (isAuthorized) {
Logger.log('Authorisation Success!');
} else {
Logger.log('Authorisation Denied...!');
}
}
// Modified from http://ctrlq.org/code/20068-blogger-api-with-google-apps-script
function photoAPI() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var albums_sh = ss.getSheetByName("albums") || ss.insertSheet("albums", ss.getSheets().length);
albums_sh.clear(); var nrow = new Array(); var narray = new Array();
Logger.log("starting");
var service = getPhotoService();
Logger.log(service.hasAccess());
Logger.log('redirectURI='+service.getRedirectUri());
if (service.hasAccess()) {
var api = "https://photoslibrary.googleapis.com/v1/albums";
var headers = {
"Authorization": "Bearer " + service.getAccessToken()
};
var options = {
"headers": headers,
"method" : "GET",
"muteHttpExceptions": true
};
var response = UrlFetchApp.fetch(api, options);
var json = JSON.parse(response.getContentText());
for (var i in json.items) {
nrow = []; nrow.push(json.items[i].id); nrow.push(json.items[i].name); nrow.push(json.items[i].url); narray.push(nrow);
}
albums_sh.getRange(1,1,narray.length,narray[0].length).setValues(narray);
} else {
var authorizationUrl = service.getAuthorizationUrl();
Logger.log("Open the following URL and re-run the script: " + authorizationUrl);
}
}
So it works, if others want to use it. But it is quite slow (I have 500 albums...):
function photoAPI() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var albums_sh = ss.getSheetByName("albums") || ss.insertSheet("albums", ss.getSheets().length);
albums_sh.clear();
var narray = [];
var api = "https://photoslibrary.googleapis.com/v1/albums";
var headers = { "Authorization": "Bearer " + ScriptApp.getOAuthToken() };
var options = { "headers": headers, "method" : "GET", "muteHttpExceptions": true };
var param= "", nexttoken;
do {
if (nexttoken)
param = "?pageToken=" + nexttoken;
var response = UrlFetchApp.fetch(api + param, options);
var json = JSON.parse(response.getContentText());
json.albums.forEach(function (album) {
var data = [
album.title,
album.mediaItemsCount,
album.productUrl
];
narray.push(data);
});
nexttoken = json.nextPageToken;
} while (nexttoken);
albums_sh.getRange(1, 1, narray.length, narray[0].length).setValues(narray);
}

Create a Custom Send as in Gmail using Apps Script

I do apologise for asking this here as there is already an existing thread but I was unsure of the correct protocol.
I need to use apps script to add a custom sendas address for my users in Gmail.
The thread here appears to do what I need: Creates a custom "from" send-as alias with GAS and APIs.
However I am new to Apps Script (especially advanced APIs) and am unsure which sections of Jay's script that I would need to update to make this work for me.
I know that I will need to update:
function createAlias() {
var userEmail = 'useraccount#example.com';
var alias = 'myalias#example.com';
var alias_name = 'Alias User';
But I am unsure what to update the following with or where to find it:
var service_account = {
"private_key": "-----BEGIN PRIVATE KEY...",
"client_email": "sa-email#example.com",
"client_id": "1234569343",
"user_email": "useraccount#example.com"
};
I was unable to comment on the existing post and it didn't seem appropriate to add my question as an answer. For convenience, I have pasted Jay's code here.
If anyone could please let me know which variables I will need to update with my specific information (and if necessary, where to find it) that would be much appreciated.
Kind Regards,
Brett
var service_account = {
"private_key": "-----BEGIN PRIVATE KEY...",
"client_email": "sa-email#example.com",
"client_id": "1234569343",
"user_email": "useraccount#example.com"
};
function getOAuthService(user) {
return OAuth2.createService('Service Account')
.setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setPrivateKey(service_account.private_key)
.setIssuer(service_account.client_email)
.setSubject(service_account.user_email)
.setPropertyStore(PropertiesService.getScriptProperties())
.setScope('https://www.googleapis.com/auth/gmail.settings.sharing
https://www.googleapis.com/auth/gmail.settings.basic')
}
function createAlias() {
var userEmail = 'useraccount#example.com';
var alias = 'myalias#example.com';
var alias_name = 'Alias User';
var service = getOAuthService();
service.reset();
if (service.hasAccess()) {
var url = 'https://www.googleapis.com/gmail/v1/users/me/settings/sendAs'
var headers ={
"Authorization": 'Bearer ' + service.getAccessToken(),
"Accept":"application/json",
"Content-Type":"application/json",
};
var resource ={
'sendAsEmail': alias,
'displayName': alias_name
};
var options = {
'headers': headers,
'method': 'POST',
'payload': JSON.stringify(resource),
'muteHttpExceptions': true
};
Logger.log(options);
var response = UrlFetchApp.fetch(url, options);
Logger.log(response.getContentText());
}
}
function reset() {
var service = getOAuthService();
service.reset();

Google Apps Script to add an alias to Gmail

I have a Google Apps Script that gives me the error "Delegation denied for jasonjurotich#school.edu.mx", and is not working in order to add an alias (another email) to an account within a domain. It may be because of Token headers or some URL that is missing that authorizes something, but I cannot find enough documentation that clarifies how to add it.
This should not be confused with creating an alias in the Google Admin console for the same email. Rather, this is adding another separate account to the first account so as to send emails on behalf of the second account.
All the necessary permissions have been activated (OAuth2, a Google Service account with domain-wide delegation, necessary APIs are activated, etc.)
The script I have is the following:
var JSON = {
"private_key": "key",
"client_email": "email",
"client_id": "ID",
"user_email": "teststudent#school.edu.mx"
};
function getOAuthService(user) {
return OAuth2.createService('Service Account')
.setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setClientId('ID')
.setPrivateKey(JSON.private_key)
.setIssuer(JSON.client_email)
.setSubject(JSON.user_email)
.setPropertyStore(PropertiesService.getScriptProperties())
.setParam('access_type', 'offline')
.setParam('approval_prompt', 'force')
.setScope('https://www.googleapis.com/auth/script.external_request https://www.googleapis.com/auth/gmail.settings.sharing');
}
function changeEmail() {
var service = getOAuthService();
service.reset();
if (service.hasAccess()) {
var userEmail = 'teststudent#school.edu.mx';
var alias = {
sendAsEmail: 'aliastest1#school.edu.mx',
displayName: 'TS',
replyToAddress : 'aliastest1#school.edu.mx',
treatAsAlias: true
};
Gmail.Users.Settings.SendAs.create(alias, userEmail);
}
}
It seems that you are using the older version of OAuth2 library for Google Apps Script. Please check the source code and make sure it doesn't invoke ScriptApp.getProjectKey(). For example, the version below utilizes ScriptApp.getScriptId() instead of the deprecated method:
https://github.com/gsuitedevs/apps-script-oauth2/blob/master/dist/OAuth2.gs
Try connecting the new version to your GAS project as a library or manually add the files to your script and see if that fixes things.
UPDATE
I believe what happens is that you override a permissive authorization scope with a more restrictive one. Looking at the source code of the 'setScope()' method, it doesn't look like you can call it in succession.
Service_.prototype.setScope = function(scope, optSeparator) {
var separator = optSeparator || ' ';
this.params_.scope = Array.isArray(scope) ? scope.join(separator) : scope;
return this;
};
Rather, you must provide the list of scopes and the optional separator (the default one is space). As a result, the only authorization scope your script ends up using is https://www.googleapis.com/auth/gmail.settings.basic.
Bottom line: call 'setScope()' once, passing the space-separated list of required scopes.
Instead of 2 separate calls, try this:
setScope('https://www.googleapis.com/auth/gmail.settings.basic https://www.googleapis.com/auth/gmail.settings.sharing');
A colleague of mine posted something similar to this question here: Creates a custom "from" send-as alias with GAS and APIs. The following modified code is what finally worked taking into account what was put here and what they put there.
var service_account = {
"private_key": "-----BEGIN PRIVATE KEY-----",
"client_email": "changealiastest4#project-id-[].iam.gserviceaccount.com",
"client_id": "ID",
"user_email": "teststudent#school.edu.mx"
};
function getOAuthService(user) {
return OAuth2.createService('Service Account')
.setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setClientId('ID')
.setPrivateKey(service_account.private_key)
.setIssuer(service_account.client_email)
.setSubject(service_account.user_email)
.setPropertyStore(PropertiesService.getScriptProperties())
.setParam('access_type', 'offline')
.setParam('approval_prompt', 'force')
.setScope('https://www.googleapis.com/auth/script.external_request https://www.googleapis.com/auth/gmail.settings.sharing https://www.googleapis.com/auth/gmail.settings.basic');
}
function changeEmail() {
var userEmail = 'teststudent#school.edu.mx';
var aliasEmail = 'aliastest1#school.edu.mx';
var aliasName = 'TS';
var service = getOAuthService();
service.reset();
if (service.hasAccess()) {
var url = 'https://www.googleapis.com/gmail/v1/users/me/settings/sendAs'
var headers ={
"Authorization": 'Bearer ' + service.getAccessToken(),
"Accept":"application/json",
"Content-Type":"application/json",
};
var resource ={
sendAsEmail: aliasEmail,
displayName: aliasName,
replyToAddress : aliasEmail,
treatAsAlias: true,
verificationStatus: 'accepted'
};
var options = {
'headers': headers,
'method': 'POST',
'payload': JSON.stringify(resource),
'muteHttpExceptions': true
};
Logger.log(options);
var response = UrlFetchApp.fetch(url, options);
Logger.log(response.getContentText());
}
}