When searching through GMail messages, you have two options: connect using the IMAP protocol, or use the Google GMail API.
Unfortunately, the IMAP protocol is often a non-starter, as the C extension installed may not support IMAP4, which GMail uses. This makes it impossible to query a gmail mail list.
However, where there is a will, there is a way! Using a PHP extension and package, it is possible to connect to GMail, search through, and read your messages.
This article is going to assume a working knowledge of the basic PHP Google API, including setting up API credentials and connecting an account via OAuth2.
Firstly, we need the Mail Parse extension for PHP. You can install this by running pecl install mailparse
. Ensure this extension is then enabled in PHP.
Next up is the mail parser package, which you can install by running composer require "php-mime-mail-parser/php-mime-mail-parser:^2.8.0"
.
After these are installed, and you are authenticated with Google and GMail, searching through and retrieving messages is a simple task.
The $rawData
array will consist of a list of Base 64 encoded data. This is where the real “gotcha” comes in — this is not the same as PHP’s inbuilt base64_encode($data)
, rather, it is base 64 URL encoded. If you run base64_decode
on the raw data provided, you will end up with unreadable and unparseable garbage.
To overcome this, you need to replace a couple of characters in the encoded data, mainly —
and _
with +
and /
respectively.
You can now run base64_decode
on the string and get a readable, parseable string of data, that php-mime-mail-parser
can handle.
More documentation on the mail parser is available on its GitHub repository, located at https://github.com/php-mime-mail-parser/php-mime-mail-parser#readme.
As well as the creator of the mailparse extension and the parser package, I would like to thank the unknown user3788724 who detailed the difference between base 64 encoding, and base 64 URL encoding here.
Hopefully this will help someone figure out how to read gmail messages using the PHP API quicker than I did!