November 22, 2017

Setting Up Mailgun With Laravel 5

We are going to setup Mailgun to work with sending emails in Laravel. Its easy enough to setup and with mailgun you can send 10,000 emails a month for free which is great.

Setting Up Mailgun Account

After sigining up to Mailgun, under Domains tab, click on add new domain. It’s best when entering your domain name to use a subdomain which I used mg.mydomain.com , because on my first attempt I used no subdomain and I ran into problems with a CNAME record i already had, but with a subdomain I was setup with in a few minutes.

Domain Verification & DNS

To use Mailgun you need to setup two TXT records(known as SPF & DKIM. Since my domain is on Namecheap I need to login to namecheap and under domain list I need to click manage next to the domain i want to setup Mailgun with, then click on advance dns and under host records click add new record and for the first record the spf, even that it says add mg.mydomain.com on Mailgun, but on Namecheap we only add the subdomain(mg in this case) and for the value we add v=spf1 include:mailgun.org ~all .

The second txt record(DKIM) which starts with k=rsa. For the hostname we only add smtp._domainkey and we leave the rest which is the subdomain and the domain and for the value we add the value Mailgun gives us which starts with k=rsa . After I added this I went back to Mailgun a few minutes and under my domains->Domain Verification & DNS I clicked check dns record now and it verified(even that it said it can take 24 to 48 hours).

This is what Mailgun gives us:

Screen-Shot-2016-10-31-at-4.40.16-PM

This is what it should What it should look like on Namecheap:

mailgun

Setting Up Mailgun On Laravel

Next we go to our .env file in laravel and we need to fill in the mail part of the .env file and also you can see i added in two extra fields at the end.

MAIL_DRIVER=mailgun MAIL_HOST=smtp.mailgun.org MAIL_PORT=587 MAIL_USERNAME=postmaster@..... MAIL_PASSWORD=...... MAILGUN_DOMAIN=mg.domainname.com MAILGUN_SECRET=key-....

All details needed can be got if you click on your domains and click on your domain you are using and it’s under domain information at the top of the page.

Send a email…

To send a test email we can do this inside of app/Http/routes.php.

Route::get('test_email', function(){ Mail::raw('This is a test email 1 ...2', function($message) { $message->to('contact@domain.com'); }); });

Then when you go to yourdomain.com/test_email it should send a test email, if it has worked you should be able to see it on Mailgun.

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket