What are common pitfalls when sending emails with PHP and how can they be avoided?
Common pitfalls when sending emails with PHP include not properly setting headers, not sanitizing user input, and not handling errors effectively. To avoid these pitfalls, always ensure that headers are correctly set, validate and sanitize user input before using it in the email, and implement error handling to catch any issues that may arise.
// Set proper headers to avoid emails being marked as spam
$headers = "From: sender@example.com\r\n";
$headers .= "Reply-To: sender@example.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
// Sanitize user input before using it in the email
$subject = filter_var($_POST['subject'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
// Send the email and handle any errors
if (mail('recipient@example.com', $subject, $message, $headers)) {
echo 'Email sent successfully';
} else {
echo 'Error sending email';
}