This is a continuation of this question: How to use the Gmail API, OAuth2 for Apps Script, and Domain-Wide Delegation to set email signatures for users in a G Suite domain
It showed a way to set a signature for another account, using Oauth2, Apps Script, and domain wide delegation.
However, it was not working for me when I have this scenario: I have a domain alias in our G-Suite account where myuser@aliasdomain.com is an alias for myuser@maindomain.com. I want to set a signature for myuser@aliasdomain.com. The example from the prior question only did myuser@maindomain.com.
Is it possible?
I tried this (modified from prior question's example code):
var credentials = {
"type": "service_account",
"project_id": "project-id-4606494xxxxxxxxx3",
"private_key_id": "8481966716a20fe34615daxxxxxxxxa",
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXbOAiODt\n-----END PRIVATE KEY-----\n",
"client_email": "xxxxxxxxxxxx@project-id-46064949xxxxxxxxxxxx.iam.gserviceaccount.com",
"client_id": "112076306220190xxxxxxxxxx",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/xxxxxxxxxxxx%40project-id-4606494951xxxxxxxxxxxxxx.iam.gserviceaccount.com"
}
function setSignatureTest() {
var loginEmail = 'myuser@maindomain.com';
var sendAsEmail = 'myuser@aliasdomain.com';
var signature = 'test for awesome signature';
var test = setSignature(loginEmail, sendAsEmail, signature);
Logger.log('test result: ' + test);
}
function setSignature(loginEmail, sendAsEmail, signature) {
Logger.log('starting setSignature');
var signatureSetSuccessfully = false;
var service = getDomainWideDelegationService('Gmail: ', 'https://www.googleapis.com/auth/gmail.settings.basic', loginEmail);
if (!service.hasAccess()) {
Logger.log('failed to authenticate as user ' + loginEmail);
Logger.log(service.getLastError());
signatureSetSuccessfully = service.getLastError();
return signatureSetSuccessfully;
} else Logger.log('successfully authenticated as user ' + loginEmail);
var resource = { signature: signature };
var requestBody = {};
requestBody.headers = {'Authorization': 'Bearer ' + service.getAccessToken()};
requestBody.contentType = "application/json";
requestBody.method = "PUT";
requestBody.payload = JSON.stringify(resource);
requestBody.muteHttpExceptions = false;
var loginEmailForUrl = encodeURIComponent(loginEmail);
var sendAsEmailForUrl = encodeURIComponent(sendAsEmail);
var url = 'https://www.googleapis.com/gmail/v1/users/' + loginEmailForUrl + '/settings/sendAs/' + sendAsEmailForUrl;
var maxSetSignatureAttempts = 10;
var currentSetSignatureAttempts = 0;
do {
try {
currentSetSignatureAttempts++;
Logger.log('currentSetSignatureAttempts: ' + currentSetSignatureAttempts);
var setSignatureResponse = UrlFetchApp.fetch(url, requestBody);
Logger.log('setSignatureResponse on successful attempt:' + setSignatureResponse);
signatureSetSuccessfully = true;
break;
} catch(e) {
Logger.log('set signature failed attempt, waiting 3 seconds and re-trying');
Utilities.sleep(3000);
}
if (currentSetSignatureAttempts >= maxSetSignatureAttempts) {
Logger.log('exceeded ' + maxSetSignatureAttempts + ' set signature attempts, deleting user and ending script');
throw new Error('Something went wrong when setting their email signature.');
}
} while (!signatureSetSuccessfully);
return signatureSetSuccessfully;
}
function getDomainWideDelegationService(serviceName, scope, email) {
Logger.log('starting getDomainWideDelegationService for email: ' + email);
return OAuth2.createService(serviceName + email)
// Set the endpoint URL.
.setTokenUrl(credentials.token_uri)
// Set the private key and issuer.
.setPrivateKey(credentials.private_key)
.setIssuer(credentials.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(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(scope);
}
It works as I have loginEmail and sendAsEmail set to the loginEmail, but not when set to the one for the domain alias.
I'd appreciate any ideas/help.
Thanks.