Building Gmail Filters with PHP
Warning: This post is over a year old. I don't always update old posts with new information, so some of this information may be out of date.
Earlier this week I wrote a small PHP library called GmailFilterBuilder that allows you to write Gmail filters in PHP and export them to XML.
I was already aware of a Ruby library called gmail-britta that does the same thing, but a) I’m not that familiar with Ruby so the syntax wasn’t that natural to me - it’s been a while since I wrote any Puppet manifests, and b) it seemed like a interesting little project to work on one evening.
The library contains two classes - GmailFilter
which is used to create each
filter, and GmailFilterBuilder
that parses the filters and generates the XML
using a Twig template.
Usage
For example:
# test.php
require __DIR__ '/vendor/autoload.php';
use Opdavies\GmailFilterBuilder\Builder;
use Opdavies\GmailFilterBuilder\Filter;
$filters = [];
$filters[] = Filter::create()
->has('from:[email protected]')
->labelAndArchive('Test')
->neverSpam();
new Builder($filters);
In this case, an email from [email protected]
would be archived, never marked
as spam, and have a label of "Test" added to it.
With this code written, and the GmailFilterBuilder library installed via
Composer, I can run php test.php
and have the XML written to the screen.
This can also be written to a file - php test.php > filters.xml
- which can
then be imported into Gmail.
Twig Extensions
I also added a custom Twig extension that I moved into a separate twig-extensions library so that I and other people can re-use it in other projects.
It’s a simple filter that accepts a boolean and returns true
or false
as a
string, but meant that I could remove three ternary operators from the template
and replace them with the boolean_string
filter.
Before:
{{ filter.isArchive ? 'true' : 'false' }}
After:
{{ filter.isArchive|boolean_string }}
This can then be used to generate output like this, whereas having blank values would have resulted in errors when importing to Gmail.
<apps:property name='shouldArchive' value='true'/>
Example
For a working example, see my personal gmail-filters repository on GitHub.