Tuesday, December 11, 2018

Laravel Check if SMTP Connection is valid

Hello,

While working with Laravel we often add SMTP credentials to send mail. It's important to check SMTP connection before sending mail or else it may give you error and throw run time exception. Here in this blog I am going to explain how to check SMTP connection before sending mail.

Below is the code you can use to check.

try {
$security = ($request->get('mail_encryption') != 'None') ? request()->get('mail_encryption') : null;
$transport = new \Swift_SmtpTransport($request->get('mail_host'), $request->get('mail_port'), $security);
$transport->setUsername($request->get('mail_username'));
$transport->setPassword($request->get('mail_password'));
$mailer = new \Swift_Mailer($transport);
$mailer->getTransport()->start();
}
catch (\Swift_TransportException $e) {
return redirect('mailSettings')->withInput()->with(array('message'=>'Can not connect to SMTP with given credentials.'));
}

As you can see in above code, first we are setting security config and create Swift_SmtpTransport class. After this we add add username and password. After that we create Swift_Mailer class and check it, if it throws an exception that means credentials are wrong or else credentials are correct.

No comments:

Post a Comment