✉️ Easily setup OhMySMTP for your Laravel application

lv_

LV

Posted on December 2, 2021

✉️ Easily setup OhMySMTP for your Laravel application

When I was launching my new website, I was looking for an email provider. That's when I came across OhMySMTP, a simple and privacy-friendly transactional email service. My web framework of choice, Laravel, unfortunately doesn't support OhMySMTP by default. Luckily, OhMySMTP does provide a swiftmailer transport plugin! This can be installed in any Laravel project, and can be configured like official transports.

Example setup

First, open up or create your project:

$ laravel new ohmysmtp_demo
Enter fullscreen mode Exit fullscreen mode

And install the swiftmailer transport:

$ composer require ohmysmtp/ohmysmtp-swiftmailer
Enter fullscreen mode Exit fullscreen mode

Configure Laravel

Create OhmysmtpServiceProvider.php under app/Providers:

<?php

namespace App\Providers;

use Illuminate\Mail\MailManager;
use Illuminate\Mail\MailServiceProvider;
use Ohmysmtp\OhmysmtpSwiftmailer\OhmysmtpSwiftmailerTransport;

class OhmysmtpServiceProvider extends MailServiceProvider
{
    protected function registerIlluminateMailer()
    {
        $this->app->singleton('mail.manager', function ($app) {
            $manager = new MailManager($app);
            $this->registerOhMySmtpTransport($manager);
            return $manager;
        });
    }

    protected function registerOhMySmtpTransport(MailManager $manager) {
        $manager->extend('ohmysmtp', function ($config) {
            if (! isset($config['token'])) {
                $config = $this->app['config']->get('services.ohmysmtp', []);
            }
            return new OhmysmtpSwiftmailerTransport($config['token']);
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

Remove Laravel's own MailServiceProvider from config/app.php, and add our own:

'providers' => [
        //Illuminate\Mail\MailServiceProvider::class,
        App\Providers\OhmysmtpServiceProvider::class,
],
Enter fullscreen mode Exit fullscreen mode

Now add our custom transport to the mailers array in config/mail.php:

'ohmysmtp' => [
    'transport' => 'ohmysmtp',
],
Enter fullscreen mode Exit fullscreen mode

And add our OhMySMTP API token field to config/services.php:

'ohmysmtp' => [
    'token' => env('OHMYSMTP_API_TOKEN'),
],
Enter fullscreen mode Exit fullscreen mode

Environment variables

To enable the OhMySMTP transport, configure the following variables in your .env file:

MAIL_MAILER=ohmysmtp
OHMYSMTP_API_TOKEN=<Add your token from the OhMySMTP dashboard>
Enter fullscreen mode Exit fullscreen mode

And that's it! 🎉 Laravel will pick up the mailer variable automatically, and route all emails through the custom transport.

💖 💪 🙅 🚩
lv_
LV

Posted on December 2, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related