Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate SMTP credentials before sending email in PHP?

Since it's so hard to find an answer, I'm thinking this might be impossible. If so, I'd like confirmation that it's impossible.

like image 736
Farzher Avatar asked Feb 19 '23 03:02

Farzher


1 Answers

There's a very simple way of doing it using recent versions of PHPMailer.

require_once 'phpmailer/class.phpmailer.php';
require_once 'phpmailer/class.smtp.php';

$mail = new PHPMailer(true);
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'my_awesome_password';
$mail->Host = 'smtp.example.com';
$mail->Port = 465;

// This function returns TRUE if authentication
// was successful, or throws an exception otherwise
$validCredentials = $mail->SmtpConnect();

You might need to change the port number and enable SSL depending on the targeted SMTP service. Gmail, for instance, requires a SSL connection.

To enable SSL, add $mail->SMTPSecure = 'ssl';


Notice: PHPMailer throws exceptions on failure. A username/password mismatch, for example, might trigger an exception. To avoid error messages getting printed all over your page, wrap the function inside a try/catch block.

$validCredentials = false;

try {
    $validCredentials = $mail->SmtpConnect();
}
catch(Exception $error) { /* Error handling ... */ }
like image 189
caiosm1005 Avatar answered Apr 06 '23 11:04

caiosm1005