What are common issues when sending HTML forms via email with PHP?
Common issues when sending HTML forms via email with PHP include formatting inconsistencies, missing form data, and potential security vulnerabilities. To solve these issues, it is recommended to properly sanitize and validate user input, ensure that all form fields are included in the email, and use a library like PHPMailer to securely send the email.
// Example PHP code using PHPMailer to send HTML form data via email
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php'; // Include PHPMailer library
// Sanitize and validate form data
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
// Create a new PHPMailer instance
$mail = new PHPMailer();
// Set up the email parameters
$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($email, $name);
$mail->addAddress('recipient@example.com');
$mail->isHTML(true);
// Compose the email message
$mail->Subject = 'New message from contact form';
$mail->Body = "<p>Name: $name</p><p>Email: $email</p><p>Message: $message</p>";
// Send the email
if ($mail->send()) {
echo 'Message has been sent';
} else {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}