I came across this article that explains exactly what i need https://laravel-news.com/allowing-users-to-send-email-with-their-own-smtp-settings-in-laravel .However the code uses Swift_SmtpTransport way back in L5 and i'm currently on L10. How can I recreate the custom mailer that's in the AppServiceProvider in the article to suit my current Laravel version [ 10.8 ]?
#Allowing Users to send email with their own SMTP settings.
13 messages · Page 1 of 1 (latest)
That article just completely over-complicates things in my opinion. All you need to do is define a custom mailer, and then use it when sending mails:
config([
'mail.mailers.tenant' => [
'transport' => 'smtp',
'host' => $tenant->smtp_host,
'port' => $tenant->smtp_port,
'username' => $tenant->smtp_username,
'password' => $tenant->smtp_password,
],
]);
Mail::mailer('tenant')->to($user)->send(new FooMail($args));
No need for messing about with underlying classes like the now-removed SwiftMailer at all.
Sorry to ask but could you elaborate a little bit. It's kind of my first encounter with thus.
Elaborate on what? I gave you complete code examples on dynamically creating a mailer configuration, and then using that mailer config when sending a mailable.
Okay so this goes into the AppServiceProvider.
It goes where ever you fetch the custom SMTP details from your database.
I just used “tenant” as an example, as that’s usually when people want user-configurable connections like this.
Oh yeap got it .Thank you for the help.
If you are wanting it for a multi-tenanted application, then you could have a method on your tenant model that returns this mailer using the settings from the database:
class Tenant extends Model
{
public function mailer()
{
config([
'mail.mailers.tenant' => [
'transport' => 'smtp',
'host' => $this->smtp_host,
'port' => $this->smtp_port,
'username' => $this->smtp_username,
'password' => $this->smtp_password,
],
]);
return Mail::mailer('tenant');
}
}
You could then use it to send mails using the tenant’s configuration like this:
$tenant->mailer()->to($user)->send(new FooMail($args));
Woow this is an awesome approach.Let me use this `cause it's a multitenancy app.
@patent patrol Does this work even for queued mails? Say if you have multiple "tenants" where we configure the tenant, queue a mail, reconfigure tenant, queue another mail, etc.. Would it always use the correct tennant then?
Not sure to be honest. I don’t know off the top of my head when the configuration is used: when the mail is dispatched, or when the mail comes to be sent.