• Email DIY

Inbound Email Routing In PHP

Orlando Kalossakas
5 min read

Sending email is certainly the most known feature to Mailgun’s users but Mailgun can do much more than just sending emails and tracking analytics. When people ask me what I love most about Mailgun, I almost always say how intuitive and well documented the API is. There is this one particular feature, however, I like to tell people about and that’s the inbound email routing and parsing system, also known as “Routes” in the control panel.

Inbound email routing means that you can set up Mailgun to receive emails on your behalf. You can set it up with a whole domain or a sub-domain of your choice. I think using a subdomain is the way to go because you can only set up one service to receive your emails at one time. This means that you cannot use your email client and Mailgun’s inbound feature on the same domain. For this reason, I have a set up like the following:

  • orlando@domain.com: That I use with a normal email client

  • robots@inbound.domain.com: That handles other emails workflows through the Mailgun inbound API.

Once an email is received, Mailgun can do a few things with it – send it to another endpoint of your choice, redirect it to another email, store it so you can process it later.

Cool! What do I use it for?

Process all attachments!

What if you could use emails to build an app that received attachments and automatically sent them to your online storage account (like Dropbox, google drive or similar)?

What if this email could understand who is sending you the attachments, what they contained and sort them accordingly?

Well, good news, with Mailgun’s email routing you can!

You do this by specifying a filter on a domain or sub-domain. To get started visit the routes in the control panel and remember you’re going to need to change your domain’s DNS settings accordingly so that your MX records point to Mailgun.

A route is composed of a filter, an action, a description to make it easier for humans to understand what the route does and a priority.

filter is one of the following types:

  • match_recipient(pattern): Where patterns is a regular expression of an email address

  • match_header(header, pattern): Where the header is a (MIME header) and the pattern a regular expression

  • catch_all(): Usually lowest priority as it will forward on any incoming email

You can specify the above filter to have actions dynamically if the filter matches an address specified a resulting action will occur. A list of actions can be found below, keep in mind you can have more than one action at any given time:

  • Forward(): Forwards the email to another email address or URL

  • Store(): Saves the matched email on Mailgun’s server for up to 3 days for later or delayed usage.

  • Stop(): Simply halts the chain of actions. It is required to prevent the message from being processed further by other actions. (Will get to this later in more details)

Prioritize routes by giving them priority accordingly.

  • Low number = High Priority

  • High number = Low Priority

Routes with the same priority are given priority based on creation date.

After setting up your domain or sub-domains DNS to forward emails to Mailgun as explained in the documentation with the settings given on your domain page you can begin the fun part!

Creating, editing, deleting routes in PHP

After installing the PHP library we can create a new file called createRoutes.php

1<?php
2# Uses the autoloader provider by Composer
3require 'vendor/autoload.php';
4# Defines the namespace we're going to use
5use MailgunMailgun;
6# Define some constants such as APIKEY
7$CONST_APIKEY = "key-a65gfd4gdf65gd4fgdfgf196";
8$CONST_RECIPIENTEXP = "*@sampleprovider.com";
9$CONST_PRIORITY = 0;
10$CONST_FORWARDTO = "http://samplewebsite.com/webhook";
11$CONST_DESCRIPTION = "Sample-Description";
12
13# Starts the client
14$mgClient = new Mailgun($CONST_APIKEY);
15
16# Configure the variables to be passed on to Mailgun through a POST request that creates a route
17 $result = $mgClient->post("routes", array(
18 'priority' => $CONST_PRIORITY,
19 'expression' => 'match_recipient("'. $CONST_RECIPIENTEXP.'")',
20 'action' => array('forward("'.$CONST_FORWARDTO.'")', 'stop()'),
21 'description' => $CONST_DESCRIPTION
22));
23?>

How about listing all the routes to investigate which ones you’ve have already created, programmatically, and eventually editing them.

1<?php
2# Uses the autoloader provider by Composer
3require 'vendor/autoload.php';
4# Defines the namespace we're going to use
5use MailgunMailgun;
6# Define some constants such as APIKEY
7$CONST_APIKEY = "key-a8qsdfgds45gdfgdf9f91d17b7f196";
8
9# Starts the client
10$mgClient = new Mailgun($CONST_APIKEY);
11
12# Configure the variables to be passed on to Mailgun through a POST request that creates a route
13$result = $mgClient->get(
14"routes", array('skip' => 0, 'limit' => 10)
15);
16#Let's print some output, ofcourse you can iterate the object $result to find more information regarding the routes!
17print "<strong>The whole object:</strong>";
18print "<br>";
19print_r($result);
20print "<br>";
21print "<strong>The expression assigned to the first route:</strong>";
22print "<br>";
23print $result->http_response_body->items[0]->expression;
24print "<br>";
25
26?>

At this point, we’ve successfully created a route. Every time Mailgun receives an email from someone *@sampleprovider.com – Mailgun will take its message and send a web-hook with its content to http://samplewebsite.com/webhook.

Now on my side (assuming http://samplewebsite.com/webhook is my server) I want to capture the content of the webhook that has been sent when a filter catches an incoming email.

Mailgun sends all kind of headers, most are listed below:

1Content-Type
2Date
3From
4In-Reply-To
5Message-Id
6Mime-Version
7Received
8References
9Subject
10To
11X-Envelope-From
12X-Mailgun-Incoming
13X-Received
14body-html
15body-plain
16domain
17from
18message-headers
19message-url
20recipient
21sender
22signature
23stripped-html
24stripped-signature
25stripped-text
26subject
27timestamp
28token

Let’s assume we want to write to a file the body of the message stripped from all HTML, newlines, and returns.

The following code will be executed by PHP when the webhook sent by Mailgun is received and will write the content of the request body (in this case I picked stripped-text but it could have been any of the above) to a file called output.txt

1<?php
2$content = $_POST['stripped-text'];
3$file = 'output.txt';
4file_put_contents($file, $content, LOCK_EX);
5?>

As you can see, the options from here are endless!

If you are interested in learning more about the inbound email routing functionalities, head to the documentation page or feel free to ask questions or comment here or on Twitter.

Happy Sending!

sign up

It's easy to get started. And it's free.

What will you accomplish with 10,000 free emails and a 100 free validations every month?

Sign Up For Free

Last updated on August 27, 2019

  • Related posts
  • Recent posts
  • Top posts
View all

Always be in the know and grab free email resources!

No spam, ever. Only musings and writings from the Mailgun team.

Mailgun is committed to protecting your privacy. Please read ourPrivacy Policybefore providing us with your details.

sign up

It's easy to get started. And it's free.

What will you accomplish with 10,000 free emails and a 100 free validations every month?
Sign up for Free