Email sent via PHP mail() is not sent immediately

Reado

Well-Known Member
Sep 8, 2009
228
8
68
United Kingdom
cPanel Access Level
Root Administrator
My server has a number of PHP-based services that operate using systemd.

Some of these services send emails using mail() but doing so does not send the email immediately. Instead, the email is queued by Exim. To workaround this, I also have to call shell_exec("/usr/sbin/exim -q -v") after mail() to send the email immediately.

Recently something must have changed as calling the Exim command above either sends the email straight away or produces an error from Exim stating "Spool file is locked (another process is handling this message)".

I'm puzzled as to why PHP mail() can't just send email immediately, but even more so now the Exim command has started to play up as well.

Any ideas what could be causing the problem?

The code is as follows:

/etc/systemd/system/EmailTest.service
Code:
[Unit]
Description=Email Test
After=network.target
Requires=mysql.service

[Service]
PIDFile=/var/run/EmailTest.pid
ExecStart=/usr/local/bin/php -f /home/myuser/emailtest.php
RestartSec=1m
Restart=always

[Install]
WantedBy=multi-user.target

/home/myuser/emailtest.php
PHP:
<?
$path = '/var/run/EmailTest.pid';

if (!file_exists($path))
    touch($path);

$file = fopen($path, 'w');
fwrite($file, getmypid());
fclose($file);

$from    = '[email protected]';
$to      = '[email protected]';
$subject = 'Test Subject';
$body    = 'Test Body';

$header  = 'From: Email Test <'.$from.'>'."\r\n";
$header .= 'Reply-To: Email Test <'.$from.'>'."\r\n";
$header .= 'X-Priority: 1'."\r\n";
$header .= 'X-Mailer: Emailer Test'."\r\n";
$header .= 'MIME-Version: 1.0'."\r\n";
$header .= 'Content-Type: text/plain; charset=utf-8';

mail($to, $subject, $body, $header, '-f '.$from);
echo shell_exec('/usr/sbin/exim -q -v');
 

Reado

Well-Known Member
Sep 8, 2009
228
8
68
United Kingdom
cPanel Access Level
Root Administrator
Sorted! Had to add sleep(1) between mail() and shell_exec(). Now I'm no longer getting the spooler file locked error, but would still like to know what could be causing mail not to send immediately regardless without the additional shell_exec() call, if anyone can suggest anything? Thanks.
 

cPanelMichael

Administrator
Staff member
Apr 11, 2011
47,909
2,228
463
Instead, the email is queued by Exim
Hello,

Do you notice any output to /var/log/exim_mainlog when the message is queued?

Thank you.