Configuring Mailgun for Laravel

Mail

Committed to the LaraBrain by: wjgilmore (@wjgilmore) at October 19, 2015 1:56 pm

Configuring Mailgun for Laravel applications is easy but is best explained with an example

Ever since Mandrill removed their free mail delivery tier for I've recommended Laravel developers instead use Mailgun. In fact LaraBrain uses Mailgun for delivering both messages sent through the contact form and the tip submission notifications, and so far the experience been great.

To configure Mailgun you'll first need to create a free Mailgun account. Their entry-level tier is free for up to 10,000 emails a month, which should be plenty for most applications. After creating the account you'll need to make a few changes to your domain's DNS settings; even if you're completely new to mail-related DNS settings this should be pretty easy because Mailgun provides ample documentation and tutorials explaining the process.

With the account created and DNS settings in place, it's time to configure your Laravel application. Login to your Mailgun account and copy your secret Mailgun API key. Open your project's .env file and add this line:

MAILGUN_SECRET=YOUR_SECRET_KEY_GOES HERE

Next, update the MAIL_DRIVER setting (also found in .env) to mailgun:

MAILGUN_DRIVER=mailgun

Finally, add these lines to your .env file:

MAILGUN_DOMAIN=YOUR_DOMAIN_GOES_HERE  
MAIL_TO=YOUREMAIL@EXAMPLE.COM
MAIL_NAME=SENDER NAME

For instance, here is what the LaraBrain .env file looks like:

MAIL_DRIVER=mailgun
MAILGUN_DOMAIN=larabrain.com
MAIL_TO=support@larabrain.com
MAIL_NAME=Larabrain Support
MAILGUN_SECRET=YOUR_SECRET_KEY_GOES_HERE

When the MAIL_DRIVER setting is set to mailgun, Laravel will know to refer to the config/services.php configuration file's mailgun setting. If you open this file you'll see the mailgun setting requires two configuration variables named MAILGUN_DOMAIN and MAILGUN_SECRET, both of which were previously set in .env.

With the configuration in place, you can use the Mail::send method within your controllers like so:

\Mail::send('emails.contact', $data, function($message)
{
  $message->from(env('MAIL_USERNAME'));
  $message->to(env('MAIL_TO'), env('MAIL_NAME'));
  $message->subject('LaraBrain.com Inquiry');
});

Try sending an email to yourself and after a few minutes it should arrive in your inbox!