< go back to home

How To Send Mail In Laravel Using Mailgun

I recently had to implement sending mail capability of a web application using API instead of SMTP-based. I had to check different resources and piece those together to make it work in my local development environment. So I am wrting this quick guide to document what I've learned and to hopefully be a help to others.

Note that since this is a quick guide, the focus will only be the mailing setup. I will not include good practices like validations and controller design. I find that by being minimal, it is easier as a reference and tutorial. With that, let's begin.

Start by creating a Mailgun account. Go to https://mailgun.com and click "Start Sending" button.

Fill up the registration form. You may unselect "Add payment info now" since we are focusing on development environment. Click "Create Account".

In the leftside navigation bar, click "Sending". Then in Domains, click your sandbox domain that was graciously provided by Mailgun. It should be the only entry named in pattern of "sandbox*.mailgun.org".

In the "Authorized Recipients" located in the left panel. Add an email address that you have an acess to. Cick "Save Recipient". This are the email addresses that can be used or testing. You are limited to 5 entries since this is just a sandbox project. Login to the email you've entered and confirm the message that Mailgun sent.

Select "API" and "PHP". You'll now see the "API Key". Take note of the api key and domain. Those two are the only needed values. Note, ignore the sample code in Mailgun because we will be using Laravel Mailables implementation. Laravel's has the advantage of being easier to test.

Next setup is in Laravel. We will use Laravel Mailables to make it easy to use and test. It is basically just configuration setups.

Add the lines below in "src/config/services.php".

src/config/services.php

In the .env file, add the following codebase or replace the value if it already exists.

.env

Next is to create a Mailable class throught Artisan command.

Fill with the following codebase:

app/Http/Mail/SendTest.php

Create the template file that will be used by the mailable that was just created. Create mail.blade.php file in resources/views

resources/views/mail.blade.php

We are now ready to send an email. We'll keep it simple and just trigger the email send when visiting rotue "/sendmail". For that, add the codebase below to web routes file.

resources/routes/web.php

Now, go to the "/sendmail" route (e.g. http://localhost/sendmail) to test. You should receive an email with message "hello, world".