How to check mail send or not in php

In PHP, you can use the mail() function to send an email, and then use various methods to check if the email was sent successfully or not. Here are a few ways to do it:

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:

$to = '[email protected]';
$subject = 'Test email';
$message = 'This is a test email';

if (mail($to, $subject, $message)) {
    echo 'Email sent successfully!';
} else {
    echo 'Email failed to send.';
}

Method 2: Using a try-catch block

You can use a try-catch block to catch any exceptions that may occur while sending the email. If an exception is thrown, it means the email failed to send:

$to = '[email protected]';
$subject = 'Test email';
$message = 'This is a test email';

try {
    mail($to, $subject, $message);
    echo 'Email sent successfully!';
} catch (Exception $e) {
    echo 'Email failed to send: '. $e->getMessage();
}

Method 3: Using a third-party library

You can use a third-party library like PHPMailer or SwiftMailer to send emails. These libraries often provide methods to check if the email was sent successfully or not.

For example, with PHPMailer:

require_once 'PHPMailer/PHPMailer.php';
require_once 'PHPMailer/SMTP.php';

$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'your_password';

$mail->setFrom('[email protected]', 'Your Name');
$mail->addAddress('[email protected]', 'Recipient Name');
$mail->Subject = 'Test email';
$mail->Body = 'This is a test email';

if ($mail->send()) {
    echo 'Email sent successfully!';
} else {
    echo 'Email failed to send: '. $mail->ErrorInfo;
}

Method 4: Using a log file

You can also log the email sending process to a file and check the log file to see if the email was sent successfully or not. For example:

$to = '[email protected]';
$subject = 'Test email';
$message = 'This is a test email';

$log_file = 'email_log.txt';
$log_message = 'Email sent to '. $to. ' with subject '. $subject. ' and message '. $message. "\n";

file_put_contents($log_file, $log_message, FILE_APPEND);

if (file_get_contents($log_file)!== '') {
    echo 'Email sent successfully!';
} else {
    echo 'Email failed to send.';
}

These are just a few ways to check if an email was sent successfully or not in PHP. The best method for you will depend on your specific use case and requirements.