2

I'm using SwiftMailer (standalone).

The code below works fine but when I enter an invalid SMTP credentials, an error like this is shown with an entire stack trace:

Failed to authenticate on SMTP server with username "MYUSERNAME" using 3 possible authenticators. Authenticator CRAM-MD5 returned Swift_TransportException: Expected response code 235 but got code "535", with message "535 5.7.0 Invalid login or password
" in /var/www/tester/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php:457
Stack trace:
#0 /var/www/tester/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php(341): Swift_Transport_AbstractSmtpTransport->assertResponseCode('535 5.7.0 Inval...', Array)
#1 /var/www/tester/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/EsmtpTransport.php(305): Swift_Transport_AbstractSmtpTransport->executeCommand('NmE0ODlmMWNmOTc...', Array, Array, false, NULL)
#2 /var/www/tester/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/CramMd5Authenticator.php(39): Swift_Transport_EsmtpTransport->executeCommand('NmE0ODlmMWNmOTc...', Array)
#3 /var/www/tester/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/AuthHandler.php(177): Swift_Transport_Esmtp_Auth_CramMd5Authenticator->authenticate(Object(Swift_SmtpTransport), 'MYUSERNAME', 'MYPASSWORD')
#4 /var/www/tester/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/EsmtpTransport.php(371): Swift_Transport_Esmtp_AuthHandler->afterEhlo(Object(Swift_SmtpTransport))
#5 /var/www/tester/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php(148): Swift_Transport_EsmtpTransport->doHeloCommand()
#6 /var/www/tester/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mailer.php(65): Swift_Transport_AbstractSmtpTransport->start()
#7 /var/www/tester/public/index.php(32): Swift_Mailer->send(Object(Swift_Message))
#8 {main}. Authenticator LOGIN returned Swift_TransportException: Expected response code 250 but got an empty response in /var/www/tester/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php:445
Stack trace:
#0 /var/www/tester/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php(341): Swift_Transport_AbstractSmtpTransport->assertResponseCode('', Array)
#1 /var/www/tester/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/EsmtpTransport.php(305): Swift_Transport_AbstractSmtpTransport->executeCommand('RSET\r\n', Array, Array, false, NULL)
#2 /var/www/tester/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/LoginAuthenticator.php(40): Swift_Transport_EsmtpTransport->executeCommand('RSET\r\n', Array)
#3 /var/www/tester/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/AuthHandler.php(177): Swift_Transport_Esmtp_Auth_LoginAuthenticator->authenticate(Object(Swift_SmtpTransport), 'MYUSERNAME', 'MYPASSWORD')
#4 /var/www/tester/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/EsmtpTransport.php(371): Swift_Transport_Esmtp_AuthHandler->afterEhlo(Object(Swift_SmtpTransport))
#5 /var/www/tester/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php(148): Swift_Transport_EsmtpTransport->doHeloCommand()
#6 /var/www/tester/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mailer.php(65): Swift_Transport_AbstractSmtpTransport->start()
#7 /var/www/tester/public/index.php(32): Swift_Mailer->send(Object(Swift_Message))
#8 {main}. Authenticator PLAIN returned Swift_TransportException: Expected response code 250 but got an empty response in /var/www/tester/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php:445
Stack trace:
#0 /var/www/tester/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php(341): Swift_Transport_AbstractSmtpTransport->assertResponseCode('', Array)
#1 /var/www/tester/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/EsmtpTransport.php(305): Swift_Transport_AbstractSmtpTransport->executeCommand('RSET\r\n', Array, Array, false, NULL)
#2 /var/www/tester/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/PlainAuthenticator.php(39): Swift_Transport_EsmtpTransport->executeCommand('RSET\r\n', Array)
#3 /var/www/tester/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/AuthHandler.php(177): Swift_Transport_Esmtp_Auth_PlainAuthenticator->authenticate(Object(Swift_SmtpTransport), 'MYUSERNAME', 'MYPASSWORD')
#4 /var/www/tester/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/EsmtpTransport.php(371): Swift_Transport_Esmtp_AuthHandler->afterEhlo(Object(Swift_SmtpTransport))
#5 /var/www/tester/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php(148): Swift_Transport_EsmtpTransport->doHeloCommand()
#6 /var/www/tester/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mailer.php(65): Swift_Transport_AbstractSmtpTransport->start()
#7 /var/www/tester/public/index.php(32): Swift_Mailer->send(Object(Swift_Message))
#8 {main}.done

Sample code:

<?php

try {

    $transport = (new Swift_SmtpTransport($host, $port))
        ->setUsername($user)
        ->setPassword($pass);

    $mailer = new \Swift_Mailer($transport);

    $message = (new \Swift_Message('test'))
        ->setFrom(['[email protected]' => 'bar'])
        ->setTo(['[email protected]'])
        ->setBody('test');

    $mailer->send($message);

} catch (\Swift_TransportException $ex) {

    echo $ex->getMessage();

} catch (\Exception $ex) {

    echo $ex->getMessage();
}

Isn't it suppose to catch Exceptions?

Any ideas?

5
  • Can you share the stacktrace? Probably, sending mails is delayed through a spooler as documented at symfony.com/doc/4.1/email/spool.html?
    – Nico Haase
    Feb 4, 2019 at 16:21
  • @NicoHaase I've now include the whole stack trace. I don't know about that spooler, I'm not using Symfony, this is standalone SwitftMailer. How can I configure that without Symfony?
    – IMB
    Feb 4, 2019 at 16:29
  • Okay, I've overlooked that in the first place. Sorry, according to the stack trace, the spooler is not active
    – Nico Haase
    Feb 4, 2019 at 16:30
  • A light google (I joke, it wasn't light) suggests that you should create a new subclass of AbstractSmtpTransport.php and overload the offending method and handle the errors with try-catch in your new custom class. This would also apply to any other methods that throw seemingly uncatchable errors. Feb 4, 2019 at 16:41
  • @Tim Do you mean to say exceptions doesn't work at all by default in Swiftmailer? That workround if it works isn't enticing at all, that looks like a lot of work.
    – IMB
    Feb 4, 2019 at 16:46

2 Answers 2

2

After some long digging, I can concur that I reached the same conclusion as @gere.

Shocking as it is, $ex->getMessage(); has a stackTrace appended to it.

I found that you can disable that by commenting out foreach() loop that adds all of that additional information to the message in one of the SwiftMailer core files. This may be problematic in the future if you decide to update your SwiftMailer files but as an interim fix, assuming your file structure is the same as mine, navigate to (it was line 187 for me):

/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Authhandler.php

and locate the function public function afterEhlo(Swift_Transport_SmtpAgent $agent)

Towards the end, the code looks like this:

$message = 'Failed to authenticate on SMTP server with username "' . $this->username . '" using ' . $count . ' possible authenticators.';
foreach ($errors as $error) {
    $message .= ' Authenticator ' . $error[0] . ' returned ' . $error[1] . '.';
}

throw new Swift_TransportException($message);

and comment out the foreach() loop or even just the inner expression:

$message = 'Failed to authenticate on SMTP server with username "' . $this->username . '" using ' . $count . ' possible authenticators.';
/*foreach ($errors as $error) {
    $message .= ' Authenticator ' . $error[0] . ' returned ' . $error[1] . '.';
}*/

throw new Swift_TransportException($message);

Edit: I forgot to mention, this code iterates over each of the authenticators that are used in auth attempts and spits out the error(s) they encounter in the form of a stack trace, that is the additional data you are seeing. Just to clarify.

Edit 2: This was fixed 24 days ago by replacing line 182:

$errors[] = [$authenticator->getAuthKeyword(), $e];

with:

$errors[] = [$authenticator->getAuthKeyword(), $e->getMessage()];

As shown by the commit message on git, here

2
  • Thanks for the effort but because @gere pointed out the issue first, I would have to give it him. Anyhow I still up-voted your answer. Thanks again, I appreciate it.
    – IMB
    Feb 5, 2019 at 16:30
  • @IMB Doesn’t post the solution. Feb 5, 2019 at 16:59
1
+50

You could try to do what the manual suggests:

If you need to know early whether or not authentication has failed and an Exception is going to be thrown, call the start() method on the created Transport.

So the resulting code could be:

$transport = (new Swift_SmtpTransport($host, $port))
    ->setUsername($user)
    ->setPassword($pass); 
$try {
    $transport->start();
} catch (\Swift_TransportException $ex) {
    echo $ex->getMessage();
    return; //whatever you want to do.
}
....

UPDATE: After further analysis I think I got it. You may believe that you are not catching the exception, but actually you are. The problem is that the getMessage() method on the Swift_TransportException returns the full stack trace (at least on my env with SwiftMailer 6)... Try do do something like this in your catch block echo "Message start" . $ex->getMessage() . "Message End"; And you should see the texts you added.

UPDATE 2: If what you want to achieve is to get rid of the stack trace in the message, the only solution I can think of is to subclass the Swift_SmtpTransport, catch the exception earlier and throw a new one with a shorter message. A possibile solution could look like this

class Better_SwiftSmtpTransport extends  Swift_SmtpTransport
{
    public function __construct(string $host = 'localhost', int $port = 25, ?string $encryption = null)
    {
        parent::__construct($host, $port, $encryption);
    }

    public function start()
    {
        try {
            return parent::start();
        }
        catch (Swift_TransportException $ex) {
            throw new Better_SwiftSmtpTransportException(
                $ex->getMessage(), 
                $ex->getCode(), 
                $ex
            );
        }
    }
}

class Better_SwiftSmtpTransportException extends Swift_TransportException
{
    public function __construct(string $message, int $code = 0, Exception $previous = null)
    {
        $message = strtok($message, "\n"); // get only the first line of the message
        parent::__construct($message, $code, $previous);
    }
}

$transport = (new Better_SwiftSmtpTransport($host, 25))
    ->setUsername($user)
    ->setPassword($password)
;
try {
    $mailer = new \Swift_Mailer($transport);
    $message = (new \Swift_Message('test'))
        ->setFrom(['[email protected]' => 'bar'])
        ->setTo(['[email protected]'])
        ->setBody('test');
    $mailer->send($message);

} catch (Swift_TransportException $ex) {
    echo  $ex->getMessage();
}
4
  • I just ran your code as it is but same issue, exception still not catched.
    – IMB
    Feb 4, 2019 at 17:28
  • Just updated my answer with a possible reason / solution.
    – gere
    Feb 4, 2019 at 17:56
  • Wow it appears you are right. That is a mouthful of getMessage(). Things like that could mess your brain. So real my problem is actually how to suppress that stack trace from getMessage(). I need a simpler getMessage(). Why would they put a stack tracer there when there's getTraceAsString(). If no one answers how to get rid of that stack trace, I'll accept your answer by tomorrow.
    – IMB
    Feb 4, 2019 at 18:07
  • I updated a possible solution to get rid of the stack trace. I am not really sure it is really worth it, but there are no cleaner ways I think.
    – gere
    Feb 5, 2019 at 9:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.