What are the best practices for handling SMTP authentication errors in PHP mailer?
SMTP authentication errors in PHP mailer can occur when the credentials provided are incorrect or when the server does not support the authentication method being used. To handle these errors, it is important to catch and log any exceptions thrown by the mailer class and provide appropriate error messages to the user.
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$mail = new PHPMailer(true);
try {
// SMTP settings
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your_username';
$mail->Password = 'your_password';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
// Recipient
$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
// Content
$mail->isHTML(true);
$mail->Subject = 'Subject';
$mail->Body = 'Message body';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}
Keywords
Related Questions
- What are the potential issues when using multiple submit buttons in a PHP form?
- What potential issue could arise if the conditional statement for checking the file field is not correctly written in PHP?
- How can file reading in PHP be optimized to avoid potential issues like in the provided code snippet?