phpmailerHow can I catch and handle a PHPMailer exception?
Catching and handling a PHPMailer exception can be done using a try/catch
statement.
For example:
try {
// code that may throw an exception
$mail->send();
} catch (Exception $e) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}
This will output:
Message could not be sent.
Mailer Error: SMTP connect() failed.
Code explanation
try
- The try block contains the code that may throw an exception.catch
- The catch block contains the code that will be executed when the exception is thrown.Exception $e
- The$e
variable is an instance of theException
class that contains information about the exception that was thrown.$mail->send()
- This is the code that may throw an exception.echo 'Message could not be sent.'
- This code is executed if an exception is thrown.echo 'Mailer Error: ' . $mail->ErrorInfo;
- This code is executed if an exception is thrown and will print the error message.
For more information, please see the PHPMailer documentation.
More of Phpmailer
- How do I use PHPMailer to attach a ZIP file?
- How do I configure the timeout settings for PHPMailer?
- How can I use PHPMailer without SMTP secure?
- How can I configure PHPMailer to support Polish characters?
- How can I configure PHPMailer to work with GoDaddy?
- How do I determine which version of PHPMailer I'm using?
- How can I configure PHPMailer to ignore TLS certificate errors?
- How can I use PHPMailer in Yii 1?
- How can I use PHPMailer to send emails with a Yahoo account?
- How can I use PHPMailer with Laravel?
See more codes...