What steps can be taken to ensure that the mail service is not running twice, causing the duplicate email issue?

To ensure that the mail service is not running twice and causing duplicate emails to be sent, you can implement a locking mechanism using a file lock. This will prevent multiple instances of the script from sending emails simultaneously.

$lockFile = fopen('mail_lock.txt', 'w');

if (flock($lockFile, LOCK_EX | LOCK_NB)) {
    // Send email code here

    flock($lockFile, LOCK_UN);
} else {
    // Handle case where another instance is already sending emails
}

fclose($lockFile);