What are the best practices for ensuring email delivery from a PHP contact form?

To ensure email delivery from a PHP contact form, it is important to properly configure the email settings in your PHP code. This includes setting the correct SMTP server, port, username, password, and ensuring that the "From" address is a valid email address. Additionally, using a reliable email service provider can help improve deliverability rates.

// Set the PHPMailer class
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Include the PHPMailer autoload file
require 'vendor/autoload.php';

// Create a new PHPMailer instance
$mail = new PHPMailer(true);

// Set SMTP settings
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@example.com';
$mail->Password = 'yourpassword';
$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';
$mail->Body = 'Email body content';

// Send the email
if($mail->send()){
    echo 'Email sent successfully';
} else {
    echo 'Email could not be sent';
}