'What makes PHP's mail() function so slow?

I made a quick PHP script on my server containing a call to mail() and started testing it. The html page always loads instantly, so I assume that means the PHP containing the call to mail() is finished executing. However, the emails sent from mail() are only ever being received every 10-20 minutes after the call. Why the delay? Does mail() trigger external programs? (the emails are being sent to a gmail email account if that's relevant)



Solution 1:[1]

Just as @Michael Berkowski said, it's not the mail() function itself. mail() works by calling your systems built in SMTP courier software. It then automatically negotiates the conversation with the receiving system by performing the necessary DNS lookups to find the proper mail server. Then that server picks up your message, checks your system through grey-listing and reverse DNS lookups, scans it and runs it against it's own spam/virus protection, then finally delivers. Also many mail servers delay unknown sending servers to prevent against mail DOS'ing and fishers.

Solution 2:[2]

Today I was setting up my local devserver and had same problem. Sending mail fom php via mail()-function was very slow. As already mentioned, the problem was the sendmail-setup (/var/log/mail.log):

My unqualified host name (devserver) unknown; sleeping for retry

I had to make my hostname resolvable folling this guide: https://linuxconfig.org/sendmail-unqualified-hostname-unknown-sleeping-for-retry-unqualified-hostname

tldr; edit /etc/hosts

127.0.0.1       localhost.localdomain localhost devserver
127.0.1.1       devserver

Maybe it will help somebody, too

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CP510
Solution 2 Andi S.