I've been using the PHP mail()
function.
If the mail doesn't send for any reason, I'd like to echo the error message. How would I do that?
Something like
$this_mail = mail('example@example.com', 'My Subject', $message);
if($this_mail) echo 'sent!';
else echo error_message;
Thanks!
As the others have said, there is no error tracking for send mail it return the boolean result of adding the mail to the outgoing queue. If you want to track true success failure try using SMTP with a mail library like Swift Mailer, Zend_Mail, or phpmailer.
You can use
error_get_last()
whenmail()
returns false.With
print_r(error_get_last())
, you get something like this:There is no error message associated with the
mail()
function. There is only atrue
orfalse
returned on whether the email was accepted for delivery. Not whether it ultimately gets delivered, but basically whether the domain exists and the address is a validly formatted email address.sending mail in php is not a one-step process. mail() returns true/false, but even if it returns true, it doesn't mean the message is going to be sent. all mail() does is add the message to the queue(using sendmail or whatever you set in php.ini)
there is no reliable way to check if the message has been sent in php. you will have to look through the mail server logs.
error_get_last(); - return the last error that occurred
In my case, I couldn't get the error message in my PHP script no matter what I do (
error_get_last()
, orini_set('display_errors',1);
) don't show the error messageaccording to this post
I confirm this because after some failed attempts to use
mail()
in my PHP scripts, it turns thatsendmail
was not installed on my machine, however the php.ini variablesendmail_path
was/usr/sbin/sendmail -t -i
1- I installed sendmail from my package manager
shell> dnf install sendmail
2- I started it
shell> service sendmail start
3- Now if any PHP
mail()
function fails I find the errors of thesendmail
program logged under/var/mail/
directory. 1 file per userFor example this snippet is taken from my
/var/mail/root
fileMy system is linux Fedora 28 with apache2.4 and PHP 7.2