How can PHPMailer be integrated with an HTML form?
To integrate PHPMailer with an HTML form, you need to create a PHP script that processes the form data and sends an email using PHPMailer. This script should include the necessary PHPMailer library and configure it with your SMTP server details. You can then call this script from your HTML form's action attribute to handle the form submission and send the email.
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php'; // Include PHPMailer library
// Initialize PHPMailer
$mail = new PHPMailer(true);
// Set SMTP server details
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your_smtp_username';
$mail->Password = 'your_smtp_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
// Set email content
$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('to@example.com', 'Recipient Name');
$mail->Subject = 'Subject of the email';
$mail->Body = 'Body of the email';
// Process form data and send email
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
// Add form data to email body
$mail->Body .= "\n\nName: $name\nEmail: $email\nMessage: $message";
// Send email
if ($mail->send()) {
echo 'Email sent successfully';
} else {
echo 'Error sending email: ' . $mail->ErrorInfo;
}
}
?>