Search code examples
phpgoogle-apigmail-apigoogle-api-php-client

Gmail API with Multiple Accounts/Email Addresses


I would like to write one function in php that opens a different Gmail mailbox based on an email address that is passed to the function.

I can do this for one account using the PHP QuickStart code and the instructions on the website. I need help accessing multiple accounts with no human interaction for authorization. It would be OK to establish the authorization once for the life of the application if that is required. Ultimately Gmail_Open() will become a custom API that is used only by our organization for email in our domain.

I saw the following code in the QuickStart:

// Print the labels in the user's account.
$user = 'me';
$results = $service->users_labels->listUsersLabels($user);

I tried changing 'me' to an email address but this did not work.

A push in the right direction would be helpful. Thanks!


Solution

  • I assume you are an admin for your domain, and you're okay with your application having the ability to access everyone's mailbox. If that's the case, the best approach to use is described here: Using OAuth 2.0 for Server to Server Applications.

    There isn't a PHP specific example on that page, but it's important to read through to understand the process. Then see the PHP client library docs for specific syntax: Authentication with Service Accounts.

    You will need to pass the user whose mailbox you want to access as the subject of your JWT during the auth flow, then you can use 'me' to read their labels (or whatever you want to do).