Get List of Email Aliases with Gmail API
Gmail users can send emails of behalf of any other email address that is set as an alias in their primary account. The Gmail API also supports these alias addresses for sending emails and the FROM address can either be set to your primary Gmail account or any alias.
The GmailApp service of Google Apps Script offers a simple getAliases() method that returns all the aliases of a Gmail account in an array.
However, this may not return aliases that are not set as “Treat as Alias” in the users’ Gmail setttings. If you would like to fetch all Gmail aliases, included those that are not using the ‘Treat as an alias’ setting, you need to use the Gmail API.
You should also check the verification status of an alias. If the status is set to “pending”, or any value other than “accepted”, you should not use it as it indicates that the user initiated the process for setting that email as an alias but did not complete the verification process.
function getGmailAliases() {
// Get list of email aliases via the Gmail API
// Author Amit Agarwal Website: www.ctrlq.org
var aliases = [];
Gmail.Users.Settings.SendAs.list('me').sendAs.forEach(function (e) {
if (e.verificationStatus === 'accepted') {
aliases.push({
email: e.sendAsEmail,
replyto: e.replyToAddress,
name: e.displayName,
alias: e.treatAsAlias,
});
}
});
return aliases;
}
The same method can be used to fetch the Gmail signature of authorized user. You would need to enable the Gmail API under Advanced Google Service for the code to work.
Here’s an alternate approach that uses the Gmail but without the Advanced Gmail Service of Apps Script.
JSON.parse(
UrlFetchApp.fetch('https://www.googleapis.com/gmail/v1/users/me/settings/sendAs', {
contentType: 'application/json',
headers: { Authorization: 'Bearer ' + ScriptApp.getOAuthToken() },
}).getContentText()
).sendAs.forEach(function (alias) {
if (alias.verificationStatus === 'accepted') {
aliases.push(alias.sendAsEmail);
}
});
Also see: Unable to Add Gmail Aliases
Amit Agarwal
Google Developer Expert, Google Cloud Champion
Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India.
Amit has developed several popular Google add-ons including Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory