How can PHP developers troubleshoot SMTP connection issues with PHPMailer?
To troubleshoot SMTP connection issues with PHPMailer, PHP developers can check the SMTP settings, ensure the server is reachable, and verify the port and encryption settings. Additionally, checking for any firewall restrictions or network issues can help resolve the problem.
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$mail = new PHPMailer(true);
try {
// Server settings
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your_email@example.com';
$mail->Password = 'your_password';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
// Recipient
$mail->setFrom('your_email@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
// Content
$mail->isHTML(true);
$mail->Subject = 'Subject';
$mail->Body = 'Email body content';
$mail->send();
echo 'Email sent successfully';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}