Search code examples
google-apps-scriptgoogle-workspace

Google app script to check if an email exists in domain


We have Gsuite for education and email addresses are created by a separate department and our department hands out tickets to registered students, sometimes students can bring their friends and fake emails with our school's domain, it takes more than 3 hours to get email verification from the Registration department, we were thinking of having a google script web app where we could type in the email address and it would tell us if its real or fake. The emails should be checked on our domain only. We have checked the User Class and it only can get the current user's email address only Session.getActiveUser().getEmail() is there a function or class that can help us achieve this?


Solution

  • Yes, this is possible wiht the Admin directory API.

    The documentation provides a sample code that does exactly what you want - list all users of your domain:

    function listAllUsers() {
      var pageToken;
      var page;
      do {
        page = AdminDirectory.Users.list({
          domain: 'example.com',
          orderBy: 'givenName',
          maxResults: 100,
          pageToken: pageToken
        });
        var users = page.users;
        if (users) {
          for (var i = 0; i < users.length; i++) {
            var user = users[i];
            Logger.log('%s (%s)', user.name.fullName, user.primaryEmail);
          }
        } else {
          Logger.log('No users found.');
        }
        pageToken = page.nextPageToken;
      } while (pageToken);
    }
    

    Adapt the code by replacing 'example.com' through your domain name, and if you want to list ALL students, remove the line maxResults: 100,.

    Keep in mind that Admin directory API is an Advanced Google Service and needs to be enabled from the Script Editor UI through Resources->Advanced Google Services....