How to Set Up Mailgun for Sending Emails in Laravel 11


Step 1 :
Mailgun Quick Setup
Sign Up: Go to mailgun.com and create an account.
Verify: Confirm your email and phone.
Add Domain: In Sending > Domains, add your domain or use sandbox.
DNS Setup: Add Mailgun's DNS records to your domain host and wait for verification.
Get Credentials: Copy your SMTP login or API key from the domain settings.
Step 2 :
Configure Mailgun on a Laravel project. Install Guzzle (if not installed):
composer require guzzlehttp/guzzle
Step 3 :
Set .env
values:
MAIL_MAILER=mailgun
MAILGUN_DOMAIN=your-domain.com
MAILGUN_SECRET=your-mailgun-private-api-key
MAILGUN_ENDPOINT=api.mailgun.net
MAIL_FROM_ADDRESS=your-email@your-domain.com
MAIL_FROM_NAME="${APP_NAME}"
Step 4 :
config/mail.php
'mailgun' => [
'transport' => 'mailgun',
],
config/service.php
'mailgun' => [
'domain' => env('MAILGUN_DOMAIN'),
'secret' => env('MAILGUN_SECRET'),
'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'),
],
Step 5 :
php artisan opimitze:clear
php artisan optimize
Using MailGun Api sending mail process:
<?php
// API-key and URL
$apiKey = 'your api key here';
$domain = 'your domain here';
$url = "https://api.eu.mailgun.net/v3/$domain/messages";
// Emailsettings
$postFields = [
'from' => 'your form address',
'to' => 'your to address',
'subject' => 'Mail subject',
'text' => 'This is a test email for Mr x! Is this email received?'
];
// cURL-init
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, 'api:' . $apiKey);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
// Execute and get result
$result = curl_exec($ch);
// Error logging
if (curl_errno($ch)) {
echo 'Error at cURL: ' . curl_error($ch);
} else {
echo 'Result: ' . $result;
}
// Close connection
curl_close($ch);
?>
Subscribe to my newsletter
Read articles from Jalis Mahamud directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Jalis Mahamud
Jalis Mahamud
๐จโ๐ป Laravel Developer | PHP | MySQL | REST APIs Hi, I'm a Laravel developer with experience in building web applications using PHP and modern development practices. I work on backend systems, RESTful APIs, and database structures. I enjoy writing clean code, integrating third-party services, and improving workflows for better performance. ๐ง Tools I often use: Laravel, MySQL, Git, Composer, REST APIs ๐ Focused on: Simplicity, performance, and maintainability