How can PHPMailer be integrated into a PHP form submission script to handle email sending and error messages effectively?
To integrate PHPMailer into a PHP form submission script, you can use PHPMailer to handle the email sending process and error messages effectively. This involves setting up PHPMailer with your SMTP server details, configuring the email content, and handling any errors that may occur during the sending process.
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php'; // Include PHPMailer autoload file
// Initialize PHPMailer
$mail = new PHPMailer(true);
try {
// Server settings
$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;
// Recipient
$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
// Email content
$mail->isHTML(true);
$mail->Subject = 'Subject';
$mail->Body = 'Email body';
// Send email
$mail->send();
echo 'Email sent successfully';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}
?>