Anand Singh
Posted on December 16th
Laravel 10+: Send Email Using Custom SMTP Server
"Use custom SMTP servers to send emails with Laravel."
Today, I will be showing you how to use a custom SMTP server to send email in Laravel.
Laravel lets you set the primary SMTP server for all emails in the .env file. However, you might want to use an SMTP server defined in your database or taken from user input to send an email.
This is also helpful when you let users send an email on your application using their own SMTP server.
Here is how to do it.
Create a Mailable
First, create a Mailable class by running the following artisan command
php artisan make:mail ExampleMail
Create a View
Then create a view file named ‘test.blade.php’ inside resources/views to hold the content of the email.
Now edit the ExampleMail.php class inside app/Mail, modify the “content” function to look like the following
public function content()
{
return new Content(
view: 'test',
);
}
Now you can use the following code to send the ExamplMail using a custom SMTP server
use App\Mail\ExampleMail;
use Illuminate\Console\Command;
use Illuminate\Mail\Mailer;
use Symfony\Component\Mailer\Transport\Smtp\EsmtpTransportFactory;
use Symfony\Component\Mailer\Transport\Dsn;
$factory = new EsmtpTransportFactory;
$transport = $factory->create(new Dsn(
'tls',
'mail.pie.host', //host
'SMTP_USER',
'SMTP_PASSWORD',
587
));
$view = app()->get('view');
$events = app()->get('events');
$mailer = new Mailer (
"piemail", //name
$view,
$transport,
$events
);
$mailer->alwaysFrom('piesocket@mail.pie.host', 'PieMail');
$mailer->to('RECEIVER_EMAIL')->send(new ExampleMail());
Hope this helps!
Conclusion
If you are looking for a bulk email-sending SMTP server, please give PieMail a try, thanks.
