Sending emails through Mailgun using Codeigniter (and using Mailgun campaigns)

As a developer and startup founder, I occasionally find myself looking at web apps and thinking either “This is too expensive” or “This doesn’t do exactly what I want.” My solution (for better or worse) is to build what I want myself. And when I’m building a quick app that I’m going to be the primary user of, my framework of choice is Codeigniter. It’s fast to develop in. It’s easy. And, most importantly, it’s stable (so I don’t have to worry about keeping up-to-date with weekly version releases… I’m looking at you, Node.JS).

The past few days I’ve been working on an emailing app. After all, why use something as simple and beautiful as Mailchimp when you can build your own clunky, ugly, Frankenstein version, right?

Anyway, a friend suggested Mailgun, and the free 10,000 emails a month sounded like a good deal, so I figured I’d leave SendGrid behind for a few days.

Overall, I’m unbelievably pleased with Mailgun. It’s a solid system. I might even switch RocketBolt to it. However, troubleshooting it with Codeigniter was a bit more tricky than I’m used to. Turns out not too many people are talking about how to make Mailgun and Codeigniter play nicely together. It’s not difficult. It’s just more difficult than it should be because no one has posted instructions. So I thought I’d give a quick write-up. Future spammers of the world… you’re welcome!

Integrating Mailgun into Codeigniter:

The best way to hook Mailgun into Codeigniter is by using Mailgun’s SMTP integration. Start by creating an email.php file in your application’s “config” folder (if you don’t already have one). In the body, you can paste something like this:

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

  $config['mailtype'] = 'html';
  $config['charset'] = 'utf-8';

  $config['protocol'] = 'smtp';
  $config['smtp_host'] = 'ssl://smtp.mailgun.org';
  $config['smtp_port'] = 465;
  $config['smtp_user'] = '[your Mailgun SMTP username]';
  $config['smtp_pass'] = '[your Mailgun SMTP password]';
  $config['smtp_timeout'] = '4';
  $config['crlf'] = '\n';
  $config['newline'] = '\r\n';

Here’s a little note to future me: the “$config[‘crlf’]” line is needed to fix a Codeigniter bug that prevents subject lines from being more than 75 characters. (Hey… I said Codeigniter is quick, but I didn’t say it was perfect.)

Once you’ve done that, you’re good to go. Send emails through Codeigniter as normal, and you’ll be burning through those 10,000 free Mailgun emails in no time!

Creating Mailgun campaigns with Codeigniter:

This turned out to be a bit more tricky. Mailgun has a slick campaign tracking system. But, in order to use it, you need to add a custom email header. Turns out Codeigniter doesn’t have a pre-built way of doing that, so you’ll need to extend CI’s email class. As I mentioned at the beginning of this post, the Interwebs are a bit lacking for direct answers about sending campaign headers for Mailgun, but I was able to adapt the solution from an answer about how to do a similar thing for Sendgrid. Here’s what you need to know:

Step 1:

Create a file in your application’s “libraries” folder called “MY_Email.php” and then add the following code:

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

  class MY_Email extends CI_Email {

      public function __construct($config = array())
      {
          if (count($config) > 0)
          {
              $this->initialize($config);
          }
          else
          {
              $this->_smtp_auth = ($this->smtp_user == '' AND $this->smtp_pass == '') ? FALSE : TRUE;
              $this->_safe_mode = ((boolean)@ini_get("safe_mode") === FALSE) ? FALSE : TRUE;
          }

          log_message('debug', "Email Class Initialized");
      }

      // this will allow us to add headers whenever we need them
      public function set_header($header, $value)
      {
          $this->_headers[$header] = $value;
      }
  }

Step 2:

Once you’ve done that, adding a Mailgun campaign header is as simple as including the following line of code when you first start constructing your email:

  $this->email->set_header('X-Mailgun-Campaign-Id', [Your Mailgun Campaign ID]);

And that’s it. Just make sure to include that line before setting anything else in the email (for example… if you want an HTML email and are loading a View), otherwise it’ll throw a pleasant “headers already sent” error.

That’s it for today. By the way… how’d you like my first coding tutorial? Not nearly as fun as everything else I write, huh? I also learned that my original theme was terrible for showing code, but I think I’ve finally fixed that. Lucky you!

Share

I teach in Duke University’s Innovation & Entrepreneurship program and founded RocketBolt. I write about startups, pedagogy, entrepreneurship, engineering, and poetry. They’re all related, I promise.

Leave a Reply

Your email address will not be published. Required fields are marked *

Instagram

  • Today, I lead the first meeting of a @dukeinnovation faculty committee about creating a methodology for teaching #entrepreneurship that can apply to any type of #venture.
.
Mind you, by “lead the meeting” I mostly just mean I was lucky to be in the same room with an amazing group of #scholars and #entrepreneurs who didn’t need any help from me to have a fascinating debate about how to accomplish a nearly impossible task.
.
But at least I got to take a picture from the head of the table 😁
.
#mycolleaguesarebrilliant #innovation #entrepreneur #wholetmein
  • Brought my daughter with me to watch my @dukeinnovation students graduate. She got to see dozens of examples of the kind of person I hope she becomes: brilliant, kind, thoughtful, articulate, talented, caring, confident, and really good at producing high quality work despite a propensity for procrastination 😁
.
Thanks, #duke2018 #graduates for making me love going to school every day. I hope your journeys beyond @dukeuniversity take you into jobs as amazing and rewarding as mine.
.
#graduation #innovation #entrepreneurship #classof2018 #bluedevils
  • Drinks at the @thelakewooddurham with the @dukeuniversity Junior Faculty Association to celebrate the end of another great semester.
  • Congrats to all my @dukeinnovation seniors who gave their final Capstone presentations yesterday.
.
No more #homework. Now it’s time for the #realworld.
.
#duke2018
.
.
.
#innovation #entrepreneur #entrepreneurship
  • Threw an LMOC (Last Monday of Classes) party in my #learningtofail class.
.
The students had to convince their friends to bring food, and they earned points based on how many calories they got delivered to class.
.
Lots of cookies and candies. But the winner was the student who convinced his friend to deliver 30 pounds of flour. 🤣
.
#innovation #entrepreneur #entrepreneurship #startup #ldoc #partytime
  • Asked my #learningtofail students to sell a @jollyrancher for $100 today. For the first time ever, everyone #failed.
.
In related news, I heard a report from a campus tour guide that dozens of prospective students and their families were continuously being solicited to buy absurdly expensive candy during their campus visits.
.
What a strange coincidence. Must have been someone else selling candy today, too...😒
.
#innovation #entrepreneur #entrepreneurship #sweettooth #collegevisits
  • Finally had a freshman discover the Duke-sponsored free lunch opportunity.
.
I forgot to ask Julia about the most important thing she’s learned in my class, but she’s taking another one with me next semester, so I feel like that’s a good sign she’s not just using me to get free food ☺️
.
#innovation #entrepreneur #entrepreneruship #socialmediamarketing #teaching #freelunch
  • The end-of-semester FLUNCH parade continues... this time with Thomas, one of my soon-to-be-graduating seniors in the @dukeinnovation capstone who’s heading off to work @txinstruments.
.
When asked to share the most important thing I’ve taught him about #entrepreneurship, Thomas had trouble coming up with an answer. Sounds about right 🤔
.
.
.
#entrepreneur #innovation #teaching #freelunch #duke2018
  • “When you go into a company, whatever you decide to do, you want to be closest to the money. That’s the safest place to be in every business.” - @cleithe, VP of Sales for @adwerxre, who I conned into speaking to both my @dukeinnovation capstone classes.
.
.
.
.
.
#sales #marketing #startups #entrepreneur #entrepreneurship #innovation
  • Doing a little FLUNCH with @adam_kershner,  Ben Lee, and Adam’s freshman roommate who was just there for the free lunch ☺️
.
Adam says the most important thing I taught him was: “How to think differently and approach problems in an unorthodox way, and how that approach to problem solving is one of the most valuable lessons from Duke.”
.
Honestly, I don’t think I taught him that. I think he already knew it when he showed up as a freshman in my very first class @dukeuniversity. Now he’s a graduating senior in my @dukeinnovation capstone, and it’s been a privilege to watch his Duke journey. I’m sure he’s going to do great things, and I look forward to following his post-college journey via Instagram.
.
P.S. Adam, tell Ben to follow me here so I can keep tabs on him, too 😉
.
.
.
#innovation #entrepreneur #entrepreneurship #startups #teaching #duke2018
  • “I’m not tasked with trying to sell you anything. Thankfully. There’s nothing more boring. What we’re looking to do is be magnetic. Pull you into our orbit. Be interesting.” -  @gavinohara, the global social creative lead for @lenovo, talking with my @dukeinnovation class about the importance of sharing good content online instead of trying to “sell.”
.
.
.
.
.
#entrepreneur #entrepreneurship #innovation #socialmediamarketing #socialmarketing #startups #corporatemarketing
  • Here’s the final viral #meme  video created by my @dukeinnovation #learningtofail class: #piggybackchallenge
.
Would you randomly take a ride on a stranger’s back? 😁
.
.
.
.
.
.
#innovation #entrepreneur #entrepreneurship #startups #socialmediamarketing #viralvideos #memes #memestagram

Follow Me!