Allowing Users to send email with their own SMTP settings in Laravel

Published on by

Allowing Users to send email with their own SMTP settings in Laravel image

In a recent project, I needed a way to allow users to send emails with their SMTP credentials. The goal with this was to give all the outgoing emails a more personal touch and look like it came directly from an organization versus a generic one for the web app.

I started looking for options and packages that would deliver this kind of functionality since I’d only sent emails in my projects configuring the provided mail environment variables available in any Laravel project.

MAIL_DRIVER=
MAIL_HOST=
MAIL_PORT=
MAIL_USERNAME=
MAIL_PASSWORD=
MAIL_ENCRYPTION=

Setting up these environment variables with valid SMTP credentials would give you the ability to send emails in no time in your project. However, in my case, I needed to switch these credentials at runtime depending on the logged in user. The solution wasn’t a good fit because the framework configures the Mail facade once with the provided environment variables and each call to Mail::send() will use these credentials. The Mail facade configuration can be seen in the framework’s MailServiceProvider class, specifically in the registerIlluminateMailer() method where it configures a singleton instance of the Mailer class. This Mailer instance is used each time we use the Mail facade.

Laravel’s Mail facade is a joy to work with. Configuring recipients and email content is done with a simple and intuitive API. Since I wanted to achieve the same expressiveness when sending emails with runtime configured credentials, I looked into how the Mailer instance was configured by the framework and how I could get an instance of that class but with other SMTP credentials.

Digging deeper into the Mailer class, I found out that a new instance can be built with a Swift_Mailer object. In turn, the Swift_Mailer class is built with a Swift_SmtpTransport object which houses the SMTP credentials that will be used to send emails. Both Swift_Mailer and Swift_SmtpTransport are part of the SwiftMailer package Laravel uses under the hood for sending emails.

With this chain of dependencies figured out, I needed a way to build these objects to be able to specify the email credentials I wanted to use. First, we set up a new Swift_SmtpTransport object with our credentials.

$transport = new Swift_SmtpTransport('SMTP-HOST-HERE', SMTP-PORT-HERE);
$transport->setUsername('SMTP-USERNAME-HERE');
$transport->setPassword('SMTP-PASSWORD-HERE');
 
// extra configurations here if needed

Then, we use the Swift_SmtpTransport to build our Swift_Mailer object.

$swift_mailer = new Swift_Mailer($transport);

With these two objects in place, we now need a Mailer object with our new configuration. As seen in the MailServiceProvider class, the Mailer object is built using three parameters: A view factory, the Swift_Mailer and an optional Event Dispatcher. We can get the extra parameters thanks to Laravel’s Service Container via the app()->get() helper.

$view = app()->get('view');
$events = app()->get('events');
$mailer = new Mailer($view, $swift_mailer, $events);

We also set up the replyTo and from properties, so each email sent with the Mailer has these signatures.

$mailer->alwaysFrom('from-email', 'from-name');
$mailer->alwaysReplyTo('from-email', 'from-name');

With the new Mailer object, we can now send emails with our runtime configured credentials.

$mailer->to('recipient')->send(new SomeMailable());

Simplifying our custom Mailer setup

Now that we have our custom Mailer setup, we can put this code in a Service class or in a function that will return us the Mailer object ready to be used. However, a more elegant way to get our custom Mailer would be using Laravel’s Service Container to build our object every time we need it. In our project’s AppServiceProvider class, we can register a new binding with any key we would like to use to get our custom Mailer. In my case, I used user.mailer as a key.

// AppServiceProvider.class
 
public function register()
{
$this->app->bind('user.mailer', function ($app, $parameters) {
$smtp_host = array_get($parameters, 'smtp_host');
$smtp_port = array_get($parameters, 'smtp_port');
$smtp_username = array_get($parameters, 'smtp_username');
$smtp_password = array_get($parameters, 'smtp_password');
$smtp_encryption = array_get($parameters, 'smtp_encryption');
 
$from_email = array_get($parameters, 'from_email');
$from_name = array_get($parameters, 'from_name');
 
$from_email = $parameters['from_email'];
$from_name = $parameters['from_name'];
 
$transport = new Swift_SmtpTransport($smtp_host, $smtp_port);
$transport->setUsername($smtp_username);
$transport->setPassword($smtp_password);
$transport->setEncryption($smtp_encryption);
 
$swift_mailer = new Swift_Mailer($transport);
 
$mailer = new Mailer($app->get('view'), $swift_mailer, $app->get('events'));
$mailer->alwaysFrom($from_email, $from_name);
$mailer->alwaysReplyTo($from_email, $from_name);
 
return $mailer;
});
}

With the binding in place, every time we need our customer Mailer we can use Service Container to build an instance for us passing the necessary configuration.

$configuration = [
'smtp_host' => 'SMTP-HOST-HERE',
'smtp_port' => 'SMTP-PORT-HERE',
'smtp_username' => 'SMTP-USERNAME-HERE',
'smtp_password' => 'SMTP-PASSWORD-HERE',
'smtp_encryption' => 'SMTP-ENCRYPTION-HERE',
 
'from_email' => 'FROM-EMAIL-HERE',
'from_name' => 'FROM-NAME-HERE',
];
 
$mailer = app()->makeWith('user.mailer', $configuration);
 
// Use $mailer here...

Caveats

In Laravel, Mailables can be queued to be sent later by our project’s configured queue system. Queued Mailables are always dispatched with the Mail facade meaning that if we queued an email with our custom Mailer, it would be sent with the project’s mail credentials instead of our custom ones. To prevent this from happening, we can set up each Mailable that will use our custom credentials to not be queueable by default. To do this, we should remove the ShouldQueue implementation from our Mailable classes.

Change

class SomeMailable extends Mailable implements ShouldQueue
{
// Mailable code here
}

to

class SomeMailable extends Mailable
{
// Mailable code here
}

Next, we will create a Job class that will be queuable and internally uses our custom Mailer. We will call this class UserMailerJob which will receive our custom configuration, the email recipients and the Mailable object to be sent.

class UserMailerJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
 
public $configuration;
public $to;
public $mailable;
 
/**
* Create a new job instance.
*
* @param array $configuration
* @param string $to
* @param Mailable $mailable
*/
public function __construct(array $configuration, string $to, Mailable $mailable)
{
$this->configuration = $configuration;
$this->to = $to;
$this->mailable = $mailable;
}
 
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$mailer = app()->makeWith('user.mailer', $this->configuration);
$mailer->to($this->to)->send($this->mailable);
}
}

With this job in place, we can dispatch our UserMailerJob job to send Mailables with our project’s queue system.

$configuration = [
'smtp_host' => 'SMTP-HOST-HERE',
'smtp_port' => 'SMTP-PORT-HERE',
'smtp_username' => 'SMTP-USERNAME-HERE',
'smtp_password' => 'SMTP-PASSWORD-HERE',
'smtp_encryption' => 'SMTP-ENCRYPTION-HERE',
 
'from_email' => 'FROM-EMAIL-HERE',
'from_name' => 'FROM-NAME-HERE',
];
 
UserMailerJob::dispatch($configuration, 'recipient', new SomeMailable());

Conclusion

With this setup, we can send emails with custom credentials configured at runtime. What’s nice about this implementation is that we haven’t reached out for any packages that solve this particular problem and that we have used the same objects and orchestration Laravel uses under the hood to send emails.

This is one of the many possible implementations one can do to solve this type of requirement.

Andrés Santibáñez photo

Web and Mobile dev. Father of two. Married to the best wife ever. Enjoying every little moment life gives us.

Filed in:
Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate logo

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate

Build your SaaS application in hours. Out-of-the-box multi-tenancy and seamless Stripe integration. Supports subscriptions and one-time purchases, allowing you to focus on building and creating without repetitive setup tasks.

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Asymmetric Property Visibility in PHP 8.4 image

Asymmetric Property Visibility in PHP 8.4

Read article
Access Laravel Pulse Data as a JSON API image

Access Laravel Pulse Data as a JSON API

Read article
Laravel Forge adds Statamic Integration image

Laravel Forge adds Statamic Integration

Read article
Transform Data into Type-safe DTOs with this PHP Package image

Transform Data into Type-safe DTOs with this PHP Package

Read article
PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell image

PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell

Read article
Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3 image

Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3

Read article