What are the best practices for handling undeliverable emails in PHP?
Undeliverable emails can occur for various reasons such as invalid email addresses or full mailboxes. To handle undeliverable emails in PHP, it is recommended to use a try-catch block when sending emails and catch any exceptions that may occur. Additionally, you can use the returned value from the mail function to check if the email was successfully sent or not.
try {
$to = 'recipient@example.com';
$subject = 'Test Email';
$message = 'This is a test email';
$headers = 'From: sender@example.com';
if (mail($to, $subject, $message, $headers)) {
echo 'Email sent successfully';
} else {
echo 'Failed to send email';
}
} catch (Exception $e) {
echo 'An error occurred: ' . $e->getMessage();
}