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