Cover Image for Laravel Mailgun Setup
283 views

Laravel Mailgun Setup

Setting up Mailgun with Laravel involves configuring your Laravel application to use the Mailgun email service for sending emails. Mailgun provides a reliable and powerful email delivery platform. Here’s how you can set up Mailgun with Laravel:

  1. Create a Mailgun Account: If you haven’t already, sign up for a Mailgun account at https://www.mailgun.com/ and create a domain. Mailgun provides a sandbox domain for testing purposes.
  2. Install Required Packages: In your Laravel project, you need to install the Mailgun and Guzzle HTTP packages, if they are not already installed. Open your terminal and navigate to your project directory, then run:
PHP
 composer require guzzlehttp/guzzle
 composer require illuminate/mail
  1. Configure Mailgun in .env: Open your .env file and set the Mailgun configuration variables:
PHP
 MAIL_MAILER=mailgun
 MAIL_HOST=smtp.mailgun.org
 MAIL_PORT=587
 MAIL_USERNAME=your-mailgun-smtp-username
 MAIL_PASSWORD=your-mailgun-smtp-password
 MAIL_ENCRYPTION=tls
 MAIL_FROM_ADDRESS=your-email@example.com
 MAIL_FROM_NAME="${APP_NAME}"
 MAILGUN_DOMAIN=your-mailgun-domain
 MAILGUN_SECRET=your-mailgun-api-key

Replace the placeholders with your Mailgun SMTP credentials (username and password), domain, and API key.

  1. Configure Mailgun in config/services.php: Open the config/services.php file and add your Mailgun configuration:
PHP
 'mailgun' => [
     'domain' => env('MAILGUN_DOMAIN'),
     'secret' => env('MAILGUN_SECRET'),
 ],
  1. Create and Configure a Mailgun Driver: Open the config/mail.php configuration file and set the mailgun driver as the default driver and specify the mailgun transport:
PHP
 'default' => env('MAIL_MAILER', 'mailgun'),

 'mailers' => [
     'mailgun' => [
         'transport' => 'mailgun',
     ],
 ],
  1. Send a Test Email: With the setup complete, you can now send a test email using Laravel’s built-in Mail facade. For example, you can send an email from a controller:
PHP
 use Illuminate\Support\Facades\Mail;
 use App\Mail\YourMailClass; // Replace with your mail class

 public function sendMail()
 {
     Mail::to('[email protected]')->send(new YourMailClass());
     return "Email sent!";
 }

Remember to replace YourMailClass with the actual class that defines your email content and template.

  1. Testing in the Development Environment: During development, you might want to use the Mailgun sandbox domain for testing. The sandbox domain has some limitations but is great for testing without affecting real recipients. Check the Mailgun documentation for details on using the sandbox domain.

That’s it! Your Laravel application should now be set up to send emails through Mailgun. Remember to test thoroughly, and consider implementing error handling and logging for your email sending processes.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS