How to obtain a list of email aliases

Problem

The user needs to get a list of email aliases, which is unavailable using the Admin console.

Environment

  • Apps Script

Solution

  1. Open Apps Script.
  2. Click New project.
  3. Name the script project in the title.
  4. Delete the existing code example.
  5. Add the below script:
    /**
    
     * list users that have email aliases
    
     * Usage:
    
     * 1. copy and paste this source code to your Apps Script Editor
    
     * 2. select the following function name
    
     * 3. click 'Run'.
    
     * 4. The users with email aliases will be printed in the 'Execution log'
    
     *
    
     * © 2021 xFanatical, Inc.
    
     * @license MIT
    
     * @version 1.0.2 fix a pagination issue
    
     * @version 1.0.1 print out aliases
    
     * @version 1.0.0 proof of concept
    
     */
    
    function listUsersWithEmailAliases() {
    
      let pageToken
    
      let page
    
      do {
    
        page = AdminDirectory.Users.list({
    
          customer: 'my_customer',
    
          maxResults: 100,
    
          pageToken,
    
          fields: 'users(name/fullName,primaryEmail,aliases),nextPageToken',
    
        })
    
        let users = page.users
    
        if (users) {
    
          for (let i = 0; i < users.length; i++) {
    
            const user = users[i]
    
            if (user.aliases && user.aliases.length > 0) {
    
              Logger.log(`User ${user.name.fullName} <${user.primaryEmail}> `
    
                + `has ${user.aliases.length} email alias${user.aliases.length > 1 ? 'es' : ''}: `
    
                + JSON.stringify(user.aliases))
    
            }
    
          }
    
        } else {
    
          Logger.log('No users found.')
    
        }
    
        pageToken = page.nextPageToken
    
      } while (pageToken)
    
    }
  6. Click Services in the left navigation panel
  7. Select Admin SDK API
  8. Click Add
  9. Click Save Google Apps Script project button in the toolbar.
  10. Click Run.
  11. Grant permissions in the first run.
  12. Results will be displayed in the Execution log.
If you receive any error message after executing the script:
  1. Go to the Admin console and navigate to Security > Access and data control > API controls.
  2. Make sure that Trust internal, domain-owned apps is checked.