• Customer Success

How Geogram Built A Free Group Email Service Using Yii For PHP With MySQL

Mailgun Community
5 min read
featured

This post was written by Jeff Reifman. Jeff is technology consultant and writer living in Seattle. He is also the CEO and lead developer of Geogram, a free group email service for local places. You can follow him at @reifman.

Geogram provides free group email service for your block, your neighborhood and your favorite places. Users discover groups based on their location (with a bit of HTML5 geolocation and Google Maps magic). Once they join or create groups on the Geogram website, most of their interaction with our service occurs via email.

In the past, building a scalable email service around processing and sending email was a huge undertaking. In addition to performance issues, managing your server reputation and spam require a great deal of time and specialized expertise (Geogram’s competitor has 55 employees right now). If you don’t think managing email is harder than it looks, read this (So, You’d Like to Send Some Email (through code)).

So in this tutorial, I’ll walk you step-by-step through how to build a similar service to send, receive, and track emails for hundreds or thousands of users. If you are already familiar with the basics of using Mailgun, feel try to skip ahead to the section that interests you most.

I. How Geogram is architected

II. Sending emails

III. Handling incoming emails

 

I. How Geogram is architected

Geogram uses the open source Yii Framework for PHP with MySQL. Yii is essentially an MVC framework like Ruby on Rails, but with all the simplicity and maturity of PHP. It’s fast, efficient and relatively straightforward. It also includes scaffolding/code generation, active record, transaction support, I18n localization, caching support et al. The documentation, community support and available plugins are also quite good.

In the past, it would have taken me a year to build something like Geogram and longer to properly mature it. Even though I was new to Yii, I was still was able to code Geogram in three months (including Mailgun integration) – almost entirely solo. I’m still maturing the service but Yii has been a huge part of my quick success. So, the integration examples provided use Yii, PHP and cURL. They should be understandable to most PHP developers but you may notice bits of Yii-specific code that’s new to you. The code examples hopefully are generic enough though that they should help you understand how you might integrate Mailgun into your own application. 

In addition to the excerpts below, I’ve created a public Github repository (geogram-mailgun-tutorial) with code samples from this tutorial for you to review in a more organized fashion. Keep in mind though, this tutorial does not provide you a full working codebase of your own list-based application. It’s just meant to help you understand how to work with Mailgun’s API, how you might approach common challenges to running email-based applications and to ease the process of getting started.

Configuring Mailgun

Before you begin, make sure your server has support for PHP cURL. On Ubuntu Linux, we do this:

sudo apt-get install php5-curl

Mailgun will provide you a secure API URL and API key in the control panel:

We place these in a PHP .ini configuration file outside of the Apache web directory:

mailgun_api_key="key-xx-xxxxxxxxxxxxxxxxxxxx" mailgun_api_url="https://api.mailgun.net/v2"

As part of its startup process, we ask Yii to load these keys into the Yii::app()->params array. Whenever we want to connect to Mailgun, we call this function:

public function configMailgun() { //set the project identifier based on GET input request variables $this->_api_key = Yii::app()->params['mailgun']['api_key']; $this->_api_url = Yii::app()->params['mailgun']['api_url']; }

We’ve also created a helper function for initiating the most common structure for preparing Mailgun cURL requests – (beware it varies for other API methods):

private function setup_curl($command = 'messages') { $ch = curl_init(); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($ch, CURLOPT_USERPWD, 'api:'.Yii::app()->params['mailgun']['api_key']); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ch, CURLOPT_URL, Yii::app()->params['mailgun']['api_url'].'/yourdomain.com/'.$command); return $ch; } 

II. Sending emails

The following section outlines how to programmatically process and send application generated emails. Geogram allows users to send both group and private message which each require special functionality on the back end. Additionally, Geogram itself needs to send individual messages (e.g registrations), so I rewrote the PHP mail function to use Mailgun.

Delivering email to Geogram groups

When a user posts a message via the Geogram website to send to a group, there are a couple of things that we do in sequence which might seem unusual to you.

Rather than using the API to post every message to Mailgun in real time, the first thing we do is store the message to our own database. Not only do we know our database is always available but this also provides fast visual feedback for users.

As the number of messages passing between Geogram and Mailgun scales, having the ability to asynchronously manage posting and receiving messages will be critical.

Here’s a sample database schema migration for our Post table and an example of how Yii’s Active Record implementation saves form data to it.

We run two different background processes that operate on the sent messages. Yii supports running console daemons with full ActiveRecord support. Although, you can also use a CRON job or write a script in your favorite language e.g. Python, NodeJS.

Determining the Recipient list

The first process looks for pending messages and completes pre-processing. During this phase, we determine the exact recipient list.

Some group members have blocked users, others have requested to receive email via daily or weekly digests, some have asked to unsubscribe from a thread, while others have asked to receive no updates via email. Generating the recipient list requires some processing time – so it’s best done in the background. The final recipient list is stored in a second table.

This process takes pending messages in the Outbox and creates records in two related Outbound Mail tables. You can see an example of us processing messages from the initial outbox to the outbound messages table here.

Handing off messages to Mailgun for sending

The second background process manages the actual transfer of the messages from the Outbound Mail tables to Mailgun via cURL.

1 $items = OutboundMail::model()->pending()->findAll($criteria);
2 foreach ($items as $i) {
3 // fetch single message
4 $message = Yii::app()->db->createCommand()
5 ->select('p.*,q.slug,q.prefix,u.eid')
6 ->from(Yii::app()->getDb()->tablePrefix.'post p')
7 ->where('p.id=:id', array(':id'=>$i['post_id']))
8 ->queryRow();
9 // get the recipient list
10 $rxList = Yii::app()->db->createCommand()
11->select('*')->from(Yii::app()->getDb()->tablePrefix.'outbound_mail_rx_list o') ->where('delivery_mode = '.Member::DELIVER_EACH,array(':outbound_mail_id'=>$i['id']))->queryAll();
12 $rx_var ='{';
13 $to_list = '';
14 foreach ($rxList as $rx) {
15 $rx_var = $rx_var.'"'.$rx['email'].'": {"id":'.$rx['id'].'}, ';
16 $to_list = $to_list.$rx['email'].', ';
17 }
18 $rx_var =trim($rx_var,', ').'}';
19 $mg = new Mailgun();
20 $fromAddr = getUserFullName($message['author_id']).' <u_'.$message['eid'].'+'.$message['slug'].'@'.yii::app()->params['mail_domain'].'>';
21 $result = $mg->send_broadcast_message($fromAddr,$message['subject'],$message['body'].$this->mail_footer.$place_url,$to_list,$rx_var,$i['post_id']);
22 $mg->recordId($result,$i['id']);
23 // change status of outbound_mail item to SENT
24 $outbox = Yii::app()->db->createCommand()->update(Yii::app()->getDb()->tablePrefix.'outbound_mail',array('status'=>OutboundMail::STATUS_SENT,'sent_at'=>new CDbExpression('NOW()')),'id=:id', array(':id'=>$i['id']));
25 }

The lines above that build $rx_var are constructing a JSON string of Mailgun’s recipient variables. These allow us to send broadcast messages without individually listing each recipient on the To: line.

Here’s how we submit the messages to Mailgun for sending:

1 public function send_broadcast_message($from='support@yourdomain.com',$subject='',$body='',$recipient_list='',$recipient_vars='',$post_id=0) {
2 $ch = $this->setup_curl('messages');
3 curl_setopt($ch,
4 CURLOPT_POSTFIELDS,
5 array('from' => $from,
6 'to' => trim($recipient_list,','),
7 'subject' => $subject,
8 'text' => $body,
9 'recipient-variables' => $recipient_vars ,
10 'v:post_id' => $post_id)
11 );
12 $result = curl_exec($ch);
13 curl_close($ch);
14 return $result;
15 }
Sending private message

One of the most important values/features of Geogram is that we never share our users’ actual email address publicly. When we send messages, each sender is given a unique anonymized FROM address combined with the place name (or slug) they are sending to. e.g. Cynthia B. <u_51b3e170ef1e4+cedarplace@geogram.com>.

If a user replies to this address with !private in the first paragraph, we know the message is meant for private delivery to Cynthia B (user 51b3e170ef1e4). Without the !private command, we send the message to all recipients at cedarplace. Users can also send private messages to each other with just Cynthia B <u_51b3e170ef1e4@geogram.com> and we also allow private messaging through the web interface.

When we receive a request to send a private message, we do the following:

1 public function sendPrivateMessage($from,$subject,$body,$to) {
2 $this->init();
3 $mg = new Mailgun();
4 // check that either user is not blocked
5 if (!Block::model()->isBlocked($to->id,$from['id'])) {
6 // remove !private command if present
7 $body= ltrim(str_ireplace('!private','',$body)).$this->private_mail_footer;
8 // anonymize the from address
9 $fromAddr = getUserFullName($from['id']).' <u_'.$from['eid'].'@'.yii::app()->params['mail_domain'].'>';
10 $mg->send_simple_message($to->email,$subject,$body,$fromAddr);
11 } else {
12 // send error message
13 $mg->send_simple_message($from['email'],'Sorry, we're not able to deliver that message.','We are unable to deliver private messages to this recipient. If you have any questions, please contact us '.Yii::app()->baseUrl.'/site/contact');
14 }
15}

And, here’s the generic sendsimplemessage function we use to talk to Mailgun:

1 public function send_simple_message($to='',$subject='',$body='',$from='') {
2 if ($from '')
3 $from = Yii::app()->params['supportEmail'];
4 $ch = $this->setup_curl('messages');
5 curl_setopt($ch, CURLOPT_POSTFIELDS, array('from' => $from,
6 'to' => $to,
7 'subject' => $subject,
8 'text' => $body,
9 'o:tracking' => false,
10 ));
11 $result = curl_exec($ch);
12 curl_close($ch);
13 return $result;
14 }
Sending individual messages

Sometimes you just want to send individual email messages immediately. When we send new users their activation link, we want to do this without any delay. Or, emails from our web-based contact form can just be forwarded to our support queue directly. Obviously, this is easy in Mailgun as well.

The Yii-User module extension uses the standard PHP mail function. We’ve replaced it with a version that sends via Mailgun:

1/**
2 * Send to user mail
3 */
4public static function sendMail($email,$subject,$message) {
5 $supportEmail = Yii::app()->params['supportEmail'];
6 $headers = "MIME-Version: 1.0rnFrom: $supportEmailrnReply-To: $supportEmailrnContent-Type: text/html; charset=utf-8";
7 $message = wordwrap($message, 70);
8 $message = str_replace("n.", "n..", $message);
9 $mailgun = new Mailgun();
10 return $mailgun->php_mail($email,'=?UTF-8?B?'.base64_encode($subject).'?=',$message,$headers);
11 // old yii user-module standard code
12 //return mail($email,'=?UTF-8?B?'.base64_encode($subject).'?=',$message,$headers);
13}

and

1public function php_mail($email ='',$subject='',$message='',$headers='') {
2 $ch = $this->setup_curl('messages');
3 curl_setopt($ch, CURLOPT_POSTFIELDS, array('from' => Yii::app()->params['supportEmail'],
4 'to' => $email,
5 'subject' => $subject,
6 'text' => $message,
7 'o:tracking' => false
8 ));
9 $result = curl_exec($ch);
10 curl_close($ch);
11 return $result;
12} 

III. Receiving incoming messages

One of Mailgun’s powerful value-added features is its processing and parsing of inbound email. Parsing inbound email successfully into its component parts requires sophisticated code written to specific standards (as well as properly handling inevitable non-standard messages). I’m much happier letting Mailgun write this code and have them post the parsed results to my website.

Furthermore, Mailgun’s spam filtering prevents my website from having to do the work of spam detection and filtering. For a group-oriented email service like Geogram which uses a catch-all mailbox, this is a great benefit. Their spam filtering prevents me from having to process a large volume of invalid requests.

Setting Up Your Route to forward emails to the app

Mailgun provides programmable routes for receiving different types of email:

For example, any email to support@geogram.com forwards to our Tender App inbox and any email to jeff@geogram.com can forward to my work address.

More importantly, we have a catch-all rule – any email to unknown mailboxes is forwarded to our website as a posted form. In this case, you set up your forwarding address as a URL for your production environment e.g.

http://yourdomain/messages/inbound

Mailgun will post the data from incoming messages to that URL.

Receiving and storing inbound posts

Again, for scalability reasons, when Mailgun posts inbound messages to Geogram, we first just store them unprocessed in the database. As mail traffic on Geogram increases, this point of contact must be always available and fast. We simply serialize the POSTed data from Mailgun and store it as a BLOB:

1 /* Receives posted form from Mailgun with inbound commands
2 Places data into inbox table in serialized form
3 */
4 public function actionInbound()
5 {
6 $mg = new Mailgun;
7 // verify post made by Mailgun
8 if ($mg->verifyWebHook($_POST['timestamp'],$_POST['token'],$_POST['signature'])) {
9 $bundle = serialize($_POST);
10 $inboxItem = new Inbox;
11 $inboxItem->addBundle($bundle);
12}
13 }

The verifyWebHook call ensures that the message was POSTed by Mailgun and is not malicious. Here is the code for verifying POSTs:

1// this verifies that the post was actually sent from Mailgun and is not malicious
2// seehttp://documentation.mailgun.com/user_manual.html#events-webhookspublic function verifyWebHook($timestamp='', $token='', $signature='') {
3 // Concatenate timestamp and token values
4 $combined=$timestamp.$token;
5 // Encode the resulting string with the HMAC algorithm
6 // (using your API Key as a key and SHA256 digest mode)
7 $result= hash_hmac('SHA256', $combined, Yii::app()->params['mailgun']['api_key']);
8 if ($result $signature)
9 return true;
10 else
11 return false;
12}

Another background process actually looks in our database and processes each message.

Processing inbound messages

Inbound messages to Geogram are often new messages or replies to existing messages. We post these to the outbox table and they get sent via the processing described earlier. We receive other kinds of messages which include email commands such as: !private (send a private reply), !leave (resign from this group/place) !favorite (mark this message as a favorite) !spam (mark this message as spam).

Our inbox processing is actually quite detailed but here are a few aspects of it to guide your own implementation.

First, we find all the unprocessed messages starting with the oldest first. This is the framework for our processing loop:

1public function process($count=100) {
2 // processes commands in the inbox
3 $this->configMailgun();
4 $criteria = new CDbCriteria();
5 $criteria->limit = $count;
6 $criteria->order = "created_at ASC";
7 $inboxItems = Inbox::model()->pending()->findAll($criteria);
8 foreach ($inboxItems as $i) {
9 echo 'inbox item id: '.$i['id'].'
10';
11 $commandRequest=false;
12 $cmd = unserialize($i['bundle']);
13 // Lookup sender from $cmd['sender']
14 $sender_email = $cmd['sender'];
15 $sender = User::model()->findByAttributes(array('email'=>$sender_email));
16 if ($sender = null) {
17 // send alert - we don't know that address
18 OutboundMail::alertUnknownSender($sender_email);
19 } else {
20 // do all of our processing per message (described below)
21 }
22 // change status of inbox item
23 Inbox::model()->updateAll(array( 'status' => self::STATUS_PROCESSED,'processed_at'=> new CDbExpression('NOW()') ), 'id = '.$i['id'] );
24 // end of loop thru inbox items
25 }
26}
27

We’re unserializing the POSTed fields from the database, then verifying the sender. If the sender isn’t a registered user, we send them an error message.

Here’s how we look for commands at the top of the message body:

1$msgLead = substr($body,0,200);
2 if (stripos($msgLead,'!nomail')!false) {
3 $this->log_item('nomail request'.$sender->id.' '.$sender->email);
4 // set nomail
5 $sender->no_mail = true;
6 $sender->save();
7 $commandRequest=true;
8 }

Here are the basics for how we match the incoming To: address to the known Places in our Geogram world. Basically, we’re matching the place part of the To: field to the slugs for Places in our database. We’re checking that the place exists and that the user is a member authorized to post:

1// Lookup place from slug / get place_id
2 $place = Place::model()->findByAttributes(array('slug'=>$slug));
3 if ($place = null) {
4 // send alert - we don't know that address
5 OutboundMail::alertUnknownPlace($sender->email);
6 } else {
7 if (!$commandRequest) {
8 // verify sender is a member of place
9 if (Place::model()->isMember($sender->id,$place->id))
10 {
11 $this->log_item('IsMember - preparing msgpost');
12 // Prepare message for sending
13 $msg=new Post;
14 $msg->subject = $cmd['subject'];
15 $msg->body = $body;
16 $msg->status = Post::STATUS_PENDING;
17 $msg->place_id = $place->id;
18 $msg->author_id = $sender->id;
19 $msg->type = $outbound_msg_type;
20 // submit to the outbox
21 $msg->save();
22 } else {
23 // send alert - you're not a member
24 OutboundMail::alertNotMember($sender->email,$place);
25 }
26 // end of commandRequest false block
27 }
28 // end of post / reply to message block
29 }

Then, we just save the message to the database as if it had been posted from the website. It will get picked up by the background process that handles outbound messages.

Tracking reply threads

Replies to emails include a header with a unique message ID identifying the thread of the conversation. When we ask Mailgun to send a message, it returns this unique thread ID to us and we store in the database.

$result = $mg->send_broadcast_message($fromAddr,$message['subject'],$message['body'].$this->mail_footer.$place_url,$to_list,$rx_var,$i['post_id']); $mg->recordId($result,$i['id']);

Here’s where we record the ID in the database:

public function recordId($result,$id) { // update outbound_mail table with external id // returned from mailgun send $resp = json_decode($result); if (property_exists($resp,'id')) { OutboundMail::model()->updateAll(array( 'ext_id' => $resp->id ), 'id = '.$id ); }

Later, when we receive messages, we look to see if they are part of an earlier conversation. Here is some example code:

1 // find thread reference id
2 $msg_headers=json_decode($cmd['message-headers']);
3 $reference_exists=false;
4 foreach ($msg_headers as $header) {
5 if (strcasecmp($header[0],'References') 0 ) {
6 $references = $header[1];
7 // lookup original post that thread refers to
8 $thread = OutboundMail::model()->findByAttributes(array('ext_id'=>$references));
9 if (!empty($thread)) {
10 $outbound_parent_id=$thread->post_id;
11 $outbound_msg_type = Post::TYPE_REPLY;
12 $this->log_item('reply to thread: '.$thread->post_id);
13 } else {
14 $outbound_parent_id=0;
15 }
16 }
17 if (strcasecmp($header[0],'In-Reply-To')==0) {
18 $inreplyto = $header[1];
19 $this->log_item('replyto: '.$inreplyto);
20 // lookup reply that inbound msg refers to
21 $thread = OutboundMail::model()->findByAttributes(array('ext_id'=>$inreplyto));
22 if (!empty($thread)) {
23 $outbound_in_reply_to=$thread->post_id;
24 $this->log_item('reply to: '.$thread->post_id);
25 $outbound_msg_type = Post::TYPE_REPLY;
26 } else {
27 $outbound_in_reply_to = 0;
28 }
29 // end reply-to ext-id search
30 }
31 // end foreach headers
32 }

Advantages of Mailgun

I hope this post has given you an idea of how powerful Mailgun and its API are. In summary, here are a few reasons I’ve chosen Mailgun for Geogram:

  • It provides a simple API that’s easy to integrate with common platforms

  • It manages the complexity of inbound and outbound email for me

  • It manages scaling most of the email-side of my application for me

  • It manages my server’s email reputation and filters spam

  • It provides super fast, reliable delivery – no more wondering if my messages will get through

  • And finally, Mailgun provides outstanding technical support

Questions? Criticisms? Feedback?

I’ll be the first to admit that our code can be optimized greatly and that it’s not perfect – it’s a one person startup at this point. But, hopefully, you now have a bit more of a feel of how to work with Mailgun’s API via PHP.

If you have any questions, please feel free to post them in the comments and I’ll do my best to respond. You can also follow my blog or @reifman.

Kudos to the Mailgun & Rackspace folks (esp. Michael & Travis) who have been super helpful and supportive in the Geogram construction / launch phase.

What are you waiting for? Invite your neighbors to Geogram and then get coding your awesome Mailgun-integrated application.

Last updated on August 28, 2020

  • 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.

By sending this form, I agree that Mailgun may contact me and process my data in accordance with its Privacy Policy.

sign up
It's easy to get started. And it's free.
See what you can accomplish with the world's best email delivery platform.
Sign up for Free