How to check error mail function if failed

When using the mail() function in PHP, it's essential to check if the email was sent successfully or not. Here are a few ways to do so:

Method 1: Using the mail() function's return value

The mail() function returns true if the email is sent successfully, and false otherwise. You can use this return value to check if the email was sent:

if (mail('[email protected]', 'Subject', 'Message')) {
    echo 'Email sent successfully!';
} else {
    echo 'Error sending email!';
}

Method 2: Using the error_get_last() function

The error_get_last() function returns an array containing information about the last error that occurred. You can use this function to check if an error occurred while sending the email:

$error = error_get_last();
if ($error) {
    echo 'Error sending email: '. $error['message'];
} else {
    echo 'Email sent successfully!';
}

Method 3: Using a try-catch block

You can wrap the mail() function call in a try-catch block to catch any exceptions that may occur:

try {
    mail('[email protected]', 'Subject', 'Message');
    echo 'Email sent successfully!';
} catch (Exception $e) {
    echo 'Error sending email: '. $e->getMessage();
}

Method 4: Using a logging mechanism

You can also log the email sending process using a logging mechanism like a log file or a database. This way, you can track any errors that may occur:

$log_file = 'email_log.txt';
$log_message = 'Error sending email to [email protected]: '. error_get_last()['message'];
file_put_contents($log_file, $log_message. "\n", FILE_APPEND);

Remember to always check the email sending process to ensure that your emails are being delivered successfully.