Oliver Davies

Building Gmail Filters with PHP

15th July 2016

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:example@test.com')
    ->labelAndArchive('Test')
    ->neverSpam();

new Builder($filters);

In this case, an email from example@test.com 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.

Resources

Questions? Comments? I’m @opdavies on Twitter, or send me an email.

Tags

About the Author

Picture of Oliver

Oliver Davies is a full-stack Web Developer and System Administrator based in the UK. He is a Senior Developer at Microserve and a part-time freelancer specialising in Drupal, Symfony and Laravel development and Linux systems administration.