I am trying to use a service account that has domain wide delegation so I can impersonate a user and do work on their G-Suite account (specifically trash emails). It seems like I can authenticate using the service account but when I go to run the code, I tells me that my account (not the service account) does not have domain wide delegation and fails. I don't know where I am going wrong or maybe this isn't possible on App Script. Code and Error message are below.
function run() {
var service = getService();
if (service.hasAccess()) {
var url = 'https://www.googleapis.com/gmail/v1/users/' + '[impersonation_email]' + '/threads';
var response = UrlFetchApp.fetch(url, {
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
},
muteHttpExceptions: true
});
Gmail.Users.Threads.trash(userId=[impersonation_email], id=[specific_email_id]);
} else {
Logger.log(service.getLastError());
}
}
function getService() {
return OAuth2.createService('Gmail:' + '[impersonation_email]')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setPrivateKey([service_account_PRIVATE_KEY_location])
.setIssuer([service_account_CLIENT_EMAIL])
.setSubject([impersonation_email ])
.setPropertyStore(PropertiesService.getScriptProperties())
.setScope('https://mail.google.com/')
}
Error Message:
API call to gmail.users.threads.trash failed with error: Delegation denied for [my email account]