What steps can be taken to troubleshoot SMTP errors when using PHPmailer in a PHP script?
SMTP errors when using PHPmailer in a PHP script can be troubleshooted by checking the SMTP server settings, ensuring proper authentication credentials are used, verifying the email addresses and domains are correct, and checking for any firewall or security settings blocking the connection.
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@example.com';
$mail->Password = 'your_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('your@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$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 is the significance of the error "Fatal error: Call to a member function on a non-object" in PHP programming?
- How can PHP developers troubleshoot and identify errors related to HTML templates not generating as expected?
- How can headers already sent errors be avoided when setting cookies in PHP?