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


April 26th, 2019

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

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.


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.

1$transport = new Swift_SmtpTransport('SMTP-HOST-HERE', SMTP-PORT-HERE);
5// extra configurations here if needed

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

1$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.

1$view = app()->get('view');
2$events = app()->get('events');
3$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.

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

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

1$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.

1// AppServiceProvider.class
3public function register()
5 $this->app->bind('user.mailer', function ($app, $parameters) {
6 $smtp_host = array_get($parameters, 'smtp_host');
7 $smtp_port = array_get($parameters, 'smtp_port');
8 $smtp_username = array_get($parameters, 'smtp_username');
9 $smtp_password = array_get($parameters, 'smtp_password');
10 $smtp_encryption = array_get($parameters, 'smtp_encryption');
12 $from_email = array_get($parameters, 'from_email');
13 $from_name = array_get($parameters, 'from_name');
15 $from_email = $parameters['from_email'];
16 $from_name = $parameters['from_name'];
18 $transport = new Swift_SmtpTransport($smtp_host, $smtp_port);
19 $transport->setUsername($smtp_username);
20 $transport->setPassword($smtp_password);
21 $transport->setEncryption($smtp_encryption);
23 $swift_mailer = new Swift_Mailer($transport);
25 $mailer = new Mailer($app->get('view'), $swift_mailer, $app->get('events'));
26 $mailer->alwaysFrom($from_email, $from_name);
27 $mailer->alwaysReplyTo($from_email, $from_name);
29 return $mailer;
30 });

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.

1$configuration = [
2 'smtp_host' => 'SMTP-HOST-HERE',
3 'smtp_port' => 'SMTP-PORT-HERE',
4 'smtp_username' => 'SMTP-USERNAME-HERE',
5 'smtp_password' => 'SMTP-PASSWORD-HERE',
6 'smtp_encryption' => 'SMTP-ENCRYPTION-HERE',
8 'from_email' => 'FROM-EMAIL-HERE',
9 'from_name' => 'FROM-NAME-HERE',
12$mailer = app()->makeWith('user.mailer', $configuration);
14// Use $mailer here...


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.


1class SomeMailable extends Mailable implements ShouldQueue
3 // Mailable code here


1class SomeMailable extends Mailable
3 // 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.

1class UserMailerJob implements ShouldQueue
3 use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
5 public $configuration;
6 public $to;
7 public $mailable;
9 /**
10 * Create a new job instance.
11 *
12 * @param array $configuration
13 * @param string $to
14 * @param Mailable $mailable
15 */
16 public function __construct(array $configuration, string $to, Mailable $mailable)
17 {
18 $this->configuration = $configuration;
19 $this->to = $to;
20 $this->mailable = $mailable;
21 }
23 /**
24 * Execute the job.
25 *
26 * @return void
27 */
28 public function handle()
29 {
30 $mailer = app()->makeWith('user.mailer', $this->configuration);
31 $mailer->to($this->to)->send($this->mailable);
32 }

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

1$configuration = [
2 'smtp_host' => 'SMTP-HOST-HERE',
3 'smtp_port' => 'SMTP-PORT-HERE',
4 'smtp_username' => 'SMTP-USERNAME-HERE',
5 'smtp_password' => 'SMTP-PASSWORD-HERE',
6 'smtp_encryption' => 'SMTP-ENCRYPTION-HERE',
8 'from_email' => 'FROM-EMAIL-HERE',
9 'from_name' => 'FROM-NAME-HERE',
12UserMailerJob::dispatch($configuration, 'recipient', new SomeMailable());


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.

Filed in:

Andrés Santibáñez

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