Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing PHPMailer username and password without sending, i.e. check connection

Tags:

php

phpmailer

I am using PHPMailer with an email account that has to have its password changed every 90 days.

Is it possible to check the PHPMailer connection to the account without actually sending an email? Ideally I would like a button that the user clicks titled 'Check Connection', which then returns 'Connection Successful' or 'Connection Not Successful'.

Note, this is not to check if you can connect to the SMTP, but actually check the username and password and return a result.

I saw somewhere someone mentioned using the Connect() function, but I cannot get this working.

Thanks.

like image 987
Creekstone Avatar asked Jan 05 '23 18:01

Creekstone


1 Answers

You do know that you already have some code that shows how to do this? It's one of the examples provided with PHPMailer.

Here's the bulk of it:

require '../PHPMailerAutoload.php';
//Create a new SMTP instance
$smtp = new SMTP;
//Enable connection-level debug output
$smtp->do_debug = SMTP::DEBUG_CONNECTION;
try {
    //Connect to an SMTP server
    if (!$smtp->connect('mail.example.com', 25)) {
        throw new Exception('Connect failed');
    }
    //Say hello
    if (!$smtp->hello(gethostname())) {
        throw new Exception('EHLO failed: ' . $smtp->getError()['error']);
    }
    //Get the list of ESMTP services the server offers
    $e = $smtp->getServerExtList();
    //If server can do TLS encryption, use it
    if (is_array($e) && array_key_exists('STARTTLS', $e)) {
        $tlsok = $smtp->startTLS();
        if (!$tlsok) {
            throw new Exception('Failed to start encryption: ' . $smtp->getError()['error']);
        }
        //Repeat EHLO after STARTTLS
        if (!$smtp->hello(gethostname())) {
            throw new Exception('EHLO (2) failed: ' . $smtp->getError()['error']);
        }
        //Get new capabilities list, which will usually now include AUTH if it didn't before
        $e = $smtp->getServerExtList();
    }
    //If server supports authentication, do it (even if no encryption)
    if (is_array($e) && array_key_exists('AUTH', $e)) {
        if ($smtp->authenticate('username', 'password')) {
            echo "Connected ok!";
        } else {
            throw new Exception('Authentication failed: ' . $smtp->getError()['error']);
        }
    }
} catch (Exception $e) {
    echo 'SMTP error: ' . $e->getMessage(), "\n";
}

To connect using SMTPS rather than SMTP+STARTTLS, change this line:

if (!$smtp->connect('mail.example.com', 25)) {

to:

if (!$smtp->connect('ssl://mail.example.com', 465)) {
like image 80
Synchro Avatar answered Jan 07 '23 09:01

Synchro