In this tutorial, you will learn to add and configure a custom domain in Mailgun to send email in Laravel.
- A domain ownership.
- Mailgun account.
- CPanel access.
- Laravel Framework (5.2, 5.3 or 5.4) installed.
Mailgun: Adding a custom domain
In your account dashboard, go to custom domains section and click on add new domain.
Mailgun recommends using a subdomain e.g. mg.mydomain.com. Using a subdomain still, allows us to send emails from the root domain e.g “email@example.com”.
If you decide to follow this recommendation, ensure that the domain is not already pointed to an Email provider such as Gmail, outlook, etc. Then add the MX records, to warranty the email delivery.
CPanel: Adding a subdomain
Within the domains section, click on the adding a new domain button. For the purposes of this tutorial, I will use the helloselene.com. domain as example:
CPanel: Adding DNS Records for email sending and delivery
In your Cpanel, go to the Advanced Zone Editor and add the TXT Records provided by Mailgun at the very start, give them a lifetime of 4 hours.
Just as you have added the TXT Records, add the CNAME Record provided by Mailgun and set its lifetime to 4 hours. This record tracks email opening and subscriptions canceled.
Additional Information: TTL is called your Zone File’s Time To Live, or TTL, and is set in seconds. This indicates to all clients and caching nameservers how often it should check back with the authoritative nameserver for updated information.
Mailgun: Subdomain verification
To verify the subdomain click on continue with domain verification.
Once the verification has been succeeded your domain panel should looks like below:
Mailgun: Laravel Configuration
Laravel official documentation tells us that any email driver based on API (as Mailgun) requires Guzzle library. To install it, in the command line:
composer require guzzlehttp/guzzle
Once installed, a best practice is to define the email configuration global vars within the .env file.
A copy of my .env file:
Continuing with the email configuration, in the mail.php file (located in the config folder), replace the default configuration by the previously defined in the .dev file.
By last, open the services.php file (located in config folder) to ensure that domain and secret mailgun configuration vars refer to MAILGUN_DOMAIN and MAILGUN_SECRET.
At this point, our application is ready to send an Email.
IMPORTANT: A basic Mailgun account needs you to verify each email address where you will send mail to.
Another caveat is that you can only verify up to 5 email addresses. One way to avoid this is adding your card information. Mailgun won’t make any charges if you don’t send more than 10,000 emails per month.
Did you like the tutorial? I would like to know your opinion, please let me know in the comments section.