adachsoft / mailbox-gmail
Gmail API adapter for the AdachSoft provider-independent mailbox contract.
Requires
- php: ^8.3
- adachsoft/mailbox-contracts: ^0.2
- egulias/email-validator: ^4.0
- psr/clock: ^1
- psr/http-client: ^1
- psr/http-factory: ^1
- symfony/mime: ^7.3 || ^8.0
Requires (Dev)
- adachsoft/mailbox-contract-tests: ^0.2
- adachsoft/php-code-style: ^0.7.4
- friendsofphp/php-cs-fixer: ^3.95
- guzzlehttp/guzzle: ^7
- guzzlehttp/psr7: ^2.13
- phpstan/phpstan: ^2.3
- phpunit/phpunit: ^13.4
- rector/rector: ^2.9
- symplify/phpstan-rules: ^14.19
Suggests
- guzzlehttp/guzzle: PSR-18 client used by the authorization command and examples
Provides
None
Conflicts
None
Replaces
None
README
adachsoft/mailbox-gmail implements the provider-independent mailbox contract using the Gmail REST API. It supports reading, searching, message and label management, history-based synchronization, and sending mail through a user's Google account.
Requirements
- PHP 8.3 or later.
- A Google Cloud project with the Gmail API enabled and an OAuth 2.0 Desktop app client.
- A PSR-18 HTTP client and PSR-17 request and stream factories. The examples below use Guzzle.
Installation
Install the package and the HTTP implementations used in this example:
composer require adachsoft/mailbox-gmail guzzlehttp/guzzle guzzlehttp/psr7
The library itself depends on PSR-18 and PSR-17 interfaces. Applications may use any compatible HTTP client and request/stream factories; the following example uses Guzzle:
use AdachSoft\MailboxGmail\Auth\GoogleOAuthClientCredentials;
use AdachSoft\MailboxGmail\GmailFullMailbox;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\HttpFactory;
$httpClient = new Client();
$httpFactory = new HttpFactory();
$credentials = new GoogleOAuthClientCredentials(
(string) getenv('GMAIL_CLIENT_ID'),
(string) getenv('GMAIL_CLIENT_SECRET'),
);
$refreshToken = trim((string) file_get_contents('/secure/path/gmail-refresh-token'));
$mailbox = GmailFullMailbox::create(
$credentials,
$refreshToken,
$httpClient,
$httpFactory,
$httpFactory,
);
Keep the client secret and refresh token outside source control. Restrict access to the refresh-token file.
Google Cloud setup
- Create or select a Google Cloud project.
- Open APIs & Services → Library, find Gmail API, and enable it for the project.
- Configure the OAuth consent screen as External. Complete the required application details and add the Google accounts that will authorize the application under Test users.
- Open APIs & Services → Credentials, create an OAuth client ID, and select Desktop app as the application type.
- Save the OAuth client ID and client secret for the one-time authorization step below.
One-time authorization
Set the OAuth client credentials and run the package command. Google opens a consent flow in the browser; the command stores the resulting refresh token at the requested path:
GMAIL_CLIENT_ID='your-client-id' \
GMAIL_CLIENT_SECRET='your-client-secret' \
vendor/bin/mailbox-gmail-authorize --output=/path/to/gmail-refresh-token
For a token that can perform destructive integration-test cleanup, request full Gmail access explicitly:
GMAIL_CLIENT_ID='your-client-id' \
GMAIL_CLIENT_SECRET='your-client-secret' \
vendor/bin/mailbox-gmail-authorize --full-access --output=/path/to/gmail-test-refresh-token
--full-access adds the https://mail.google.com/ scope to the standard read/modify and send scopes. Re-authorize to obtain a refresh token with this scope; an existing token does not gain additional scopes automatically.
Usage
Quick start
Create a fully configured mailbox with explicit OAuth credentials and PSR-18/PSR-17 dependencies:
use AdachSoft\MailboxContracts\Model\MessageQuery;
use AdachSoft\MailboxGmail\Auth\GoogleOAuthClientCredentials;
use AdachSoft\MailboxGmail\GmailFullMailbox;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\HttpFactory;
$httpClient = new Client();
$httpFactory = new HttpFactory();
$mailbox = GmailFullMailbox::create(
new GoogleOAuthClientCredentials($clientId, $clientSecret),
$refreshToken,
$httpClient,
$httpFactory,
$httpFactory,
);
$page = $mailbox->search(new MessageQuery(unreadOnly: true));
foreach ($page->items as $summary) {
$message = $mailbox->get($summary->id);
// Process the provider-independent message DTO.
}
Capabilities
| Capability | Supported | Notes |
|---|---|---|
| Server-side search | Yes | Gmail query syntax is used, with exact local re-filtering for date boundaries. |
| Labels | Yes | Gmail labels are non-exclusive classifications. |
| Threads | Yes | Gmail thread identifiers are exposed by the contract. |
| Move to folder | Yes | Special folders map to Gmail system labels; a FolderId resolves or creates a user label by name. |
| Change tracking | Yes | Uses Gmail history IDs. |
| Flag change tracking | Yes | History changes include relevant message flag and label updates. |
| Send | Yes | Messages are submitted through Gmail messages.send. |
| Attachment retrieval | Yes | Attachment IDs are Gmail MIME partId values returned in the message metadata. |
Gmail-specific behavior
- A message can carry several Gmail labels at once; labels do not behave like exclusive IMAP folders.
moveToFolder()with aFolderIdresolves an existing user label by name or creates it when necessary. - Gmail search date operators have day-level semantics. The adapter re-filters results against the exact requested
sinceandbeforetimestamps. - Gmail's list endpoint returns message identifiers rather than full metadata, so search fetches metadata for each matching message.
- Change tracking is based on Gmail history IDs. If Gmail returns
404because a history ID is no longer available,changesSince()reportsfullResyncRequiredso the caller can rebuild its local state.
Integration tests
The integration PHPUnit suite uses the Gmail API and deletes every message in the configured account, including spam and trash, before each contract test. Use a dedicated disposable test account only; never point these variables at a personal or production mailbox.
Obtain a refresh token with the --full-access option above, then configure the test account and explicitly allow purging:
export GMAIL_TEST_CLIENT_ID='your-client-id'
export GMAIL_TEST_CLIENT_SECRET='your-client-secret'
export GMAIL_TEST_REFRESH_TOKEN_FILE='/path/to/gmail-test-refresh-token'
export GMAIL_TEST_ALLOW_PURGE=yes
vendor/bin/phpunit --testsuite integration
The integration suite is separate from the default unit suite and is not run by the default PHPUnit command. It is skipped unless all three GMAIL_TEST_* credential/file variables are set and GMAIL_TEST_ALLOW_PURGE is exactly yes.