Php mail error что это

от admin

How can I get the error message for the mail() function?

If the mail doesn’t send for any reason, I’d like to echo the error message. How would I do that?

8 Answers 8

If you are on Windows using SMTP, you can use error_get_last() when mail() returns false. Keep in mind this does not work with PHP’s native mail() function.

With print_r(error_get_last()) , you get something like this:

[type] => 2
[message] => mail(): Failed to connect to mailserver at "x.x.x.x" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()
[file] => C:\www\X\X.php
[line] => 2

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.

In my case, I couldn’t get the error message in my PHP script no matter what I do ( error_get_last() , or ini_set(‘display_errors’,1); ) don’t show the error message

The return value from $mail refers only to whether or not your server’s mailing system accepted the message for delivery, and does not and can not in any way know whether or not you are providing valid arguments. For example, the return value would be false if sendmail failed to load (e.g. if it wasn’t installed properly), but would return true if sendmail loaded properly but the recipient address doesn’t exist.

I confirm this because after some failed attempts to use mail() in my PHP scripts, it turns that sendmail was not installed on my machine, however the php.ini variable sendmail_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 the sendmail program logged under /var/mail/ directory. 1 file per user

Php mail error что это

(PHP 4, PHP 5, PHP 7, PHP 8)

mail — Send mail

Description

Parameters

Receiver, or receivers of the mail.

  • user@example.com
  • user@example.com, anotheruser@example.com
  • User <user@example.com>
  • User <user@example.com>, Another User <anotheruser@example.com>

Subject of the email to be sent.

Subject must satisfy » RFC 2047.

Message to be sent.

Each line should be separated with a CRLF (\r\n). Lines should not be larger than 70 characters.

(Windows only) When PHP is talking to a SMTP server directly, if a full stop is found on the start of a line, it is removed. To counter-act this, replace these occurrences with a double dot.

String or array to be inserted at the end of the email header.

This is typically used to add extra headers (From, Cc, and Bcc). Multiple extra headers should be separated with a CRLF (\r\n). If outside data are used to compose this header, the data should be sanitized so that no unwanted headers could be injected.

If an array is passed, its keys are the header names and its values are the respective header values.

Note:

Before PHP 5.4.42 and 5.5.27, repectively, additional_headers did not have mail header injection protection. Therefore, users must make sure specified headers are safe and contains headers only. i.e. Never start mail body by putting multiple newlines.

Note:

When sending mail, the mail must contain a From header. This can be set with the additional_headers parameter, or a default can be set in php.ini .

Failing to do this will result in an error message similar to Warning: mail(): "sendmail_from" not set in php.ini or custom "From:" header missing . The From header sets also Return-Path when sending directly via SMTP (Windows only).

Note:

If messages are not received, try using a LF (\n) only. Some Unix mail transfer agents (most notably » qmail) replace LF by CRLF automatically (which leads to doubling CR if CRLF is used). This should be a last resort, as it does not comply with » RFC 2822.

The additional_params parameter can be used to pass additional flags as command line options to the program configured to be used when sending mail, as defined by the sendmail_path configuration setting. For example, this can be used to set the envelope sender address when using sendmail with the -f sendmail option.

This parameter is escaped by escapeshellcmd() internally to prevent command execution. escapeshellcmd() prevents command execution, but allows to add additional parameters. For security reasons, it is recommended for the user to sanitize this parameter to avoid adding unwanted parameters to the shell command.

Since escapeshellcmd() is applied automatically, some characters that are allowed as email addresses by internet RFCs cannot be used. mail() can not allow such characters, so in programs where the use of such characters is required, alternative means of sending emails (such as using a framework or a library) is recommended.

The user that the webserver runs as should be added as a trusted user to the sendmail configuration to prevent a 'X-Warning' header from being added to the message when the envelope sender (-f) is set using this method. For sendmail users, this file is /etc/mail/trusted-users .

Return Values

Returns true if the mail was successfully accepted for delivery, false otherwise.

It is important to note that just because the mail was accepted for delivery, it does NOT mean the mail will actually reach the intended destination.

Changelog

Version Description
7.2.0 The additional_headers parameter now also accepts an array .

Examples

Example #1 Sending mail.

Using mail() to send a simple email:

<?php
// The message
$message = «Line 1\r\nLine 2\r\nLine 3» ;

// In case any of our lines are larger than 70 characters, we should use wordwrap()
$message = wordwrap ( $message , 70 , «\r\n» );

// Send
mail ( ‘caffeinated@example.com’ , ‘My Subject’ , $message );
?>

Example #2 Sending mail with extra headers.

The addition of basic headers, telling the MUA the From and Reply-To addresses:

<?php
$to = ‘nobody@example.com’ ;
$subject = ‘the subject’ ;
$message = ‘hello’ ;
$headers = ‘From: webmaster@example.com’ . «\r\n» .
‘Reply-To: webmaster@example.com’ . «\r\n» .
‘X-Mailer: PHP/’ . phpversion ();

mail ( $to , $subject , $message , $headers );
?>

Example #3 Sending mail with extra headers as array

This example sends the same mail as the example immediately above, but passes the additional headers as array (available as of PHP 7.2.0).

<?php
$to = ‘nobody@example.com’ ;
$subject = ‘the subject’ ;
$message = ‘hello’ ;
$headers = array(
‘From’ => ‘webmaster@example.com’ ,
‘Reply-To’ => ‘webmaster@example.com’ ,
‘X-Mailer’ => ‘PHP/’ . phpversion ()
);

mail ( $to , $subject , $message , $headers );
?>

Example #4 Sending mail with an additional command line parameter.

The additional_params parameter can be used to pass an additional parameter to the program configured to use when sending mail using the sendmail_path .

Example #5 Sending HTML email

It is also possible to send HTML email with mail() .

<?php
// Multiple recipients
$to = ‘johny@example.com, sally@example.com’ ; // note the comma

// Subject
$subject = ‘Birthday Reminders for August’ ;

// To send HTML mail, the Content-type header must be set
$headers [] = ‘MIME-Version: 1.0’ ;
$headers [] = ‘Content-type: text/html; charset=iso-8859-1’ ;

// Additional headers
$headers [] = ‘To: Mary <mary@example.com>, Kelly <kelly@example.com>’ ;
$headers [] = ‘From: Birthday Reminder <birthday@example.com>’ ;
$headers [] = ‘Cc: birthdayarchive@example.com’ ;
$headers [] = ‘Bcc: birthdaycheck@example.com’ ;

// Mail it
mail ( $to , $subject , $message , implode ( «\r\n» , $headers ));
?>

Note:

If intending to send HTML or otherwise Complex mails, it is recommended to use the PEAR package » PEAR::Mail_Mime.

Notes

Note:

The SMTP implementation (Windows only) of mail() differs in many ways from the sendmail implementation. First, it doesn't use a local binary for composing messages but only operates on direct sockets which means a MTA is needed listening on a network socket (which can either on the localhost or a remote machine).

Second, the custom headers like From: , Cc: , Bcc: and Date: are not interpreted by the MTA in the first place, but are parsed by PHP.

As such, the to parameter should not be an address in the form of "Something <someone@example.com>". The mail command may not parse this properly while talking with the MTA.

Note:

It is worth noting that the mail() function is not suitable for larger volumes of email in a loop. This function opens and closes an SMTP socket for each email, which is not very efficient.

For the sending of large amounts of email, see the » PEAR::Mail, and » PEAR::Mail_Queue packages.

PHP Mail Not Working Not Sending (How To Fix It!)

After spending some time setting up your web server and writing up the scripts, the PHP mail function is not sending emails out as expected. Tutorials from all over the Internet show different solutions, and just what the heck is happening!? How do we fix it?

  1. Install a local SMTP server.
    • Windows – Use Papercut for local testing.
    • Linux – Use sendmail or postfix, sudo apt-get install postfix .
  2. Use a remote SMTP server, simply point the SMTP settings in the php.ini file to the mail server.

That is the gist of it, but let us go through the actual steps on fixing the mail problem – Read on!

TLDR – QUICK SLIDES

TABLE OF CONTENTS

INSTALLING A LOCAL SMTP SERVER

All right, let us get started with the first solution – Installing a mail server on your own machine.

WINDOWS USERS – PAPERCUT SMTP FOR LOCAL TESTING

For Windows users, try out Papercut SMTP. Papercut is probably the fastest and fuss-free SMTP server for testing. While it can be configured to relay email out, I don’t really recommend using this for a production server.

LINUX USERS – POSTFIX OR SENDMAIL

For you guys who are on Linux, simply install Sendmail or Postfix –

But different flavors of Linux has a different package manager – YUM or RPM , just use whichever is correct.

UPDATE THE PHP.INI FILE

Finally in the php.ini file, simply ensure that SMTP is pointing to localhost . Also for the Windows users, set sendmail_from or you will get a “bad message return path” error message.

OTHER MAIL SERVERS – FOR PRODUCTION SERVERS

  • Or just check Wikipedia for a whole list of mail servers.

USING A REMOTE SMTP SERVER

Don’t want to install anything? Then use an existing SMTP server that you have access to.

POINT PHP.INI TO THE SMTP SERVER

To use an existing SMTP server, just update the php.ini file and point to the SMTP server accordingly. For example, we can actually point to the Gmail SMTP server:

That’s it, but I will not recommend using your personal Gmail, Yahoo, or Outlook accounts on production servers… At least use one of their business accounts.

EXTRA – GMAIL AUTHENTICATION

Is Google rejecting the SMTP requests? Authentication failure? That is because Google will simply not allow any Tom, Dick, and Harry to access your email account. Thankfully, we only need to do some security setting stuff to get past this issue.

ENABLE 2-STEP AUTHENTICATION

Firstly, enable the 2-step authentication on your Google account if you have not already done so. That is basically, sending a PIN code to your mobile phone when Google detects login from an unknown device.

CREATE AN APP PASSWORD

But of course, we are not going to answer a PIN code challenge whenever we try to send an email from the server… So what we are going to do instead, is to create an app password.

Select “Other (Custom Name)” under the drop-down menu.

You can name it whatever you want…

Finally, just copy that email/password into php.ini .

EXTRA BITS

That’s all for the tutorial, and here is a small section on some extras that may be useful to you.

PHP MAIL DEBUGGING

  1. In your PHP script, check the error message after sending out the email – if (!mail(TO, SUBJECT, MESSAGE)) < print_r(error_get_last()); >
  2. Set mail.log = FOLDER/mail.log in php.ini .
  3. Also, set a mail log on the SMTP server itself.

That’s all. Do a test mail send and trace the log files – Did PHP send out the email? Did the SMTP server send out the email? Are the configurations correct? Lastly, also very important – Did you send it to the correct email address, is it even a valid email?

TONE DOWN FIREWALLS, ANTI-VIRUS, CHECK SPAM FOLDER

  • Windows – Check and allow an exception in the Windows firewall.
  • Linux – Allow an exception in iptables .
  • Elsewhere – Maybe a hardware firewall that is somewhere in the network, or an anti-virus stopping the SMTP send.

INFOGRAPHIC CHEAT SHEET

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped to solve your email problems, and if you have anything to share with this guide, please feel free to comment below. Good luck and happy coding!

PHP Mail Error

Обратитесь за исправлением к Вашему хостинг-провайдеру, это их вина.

я обратился вот мне что прислали хотя ранее всё работало.

Пример реализации отправки со скриптов через mail():

$to = ‘support@sweb.ru, supsweb@mail.ru’;

$headers = ‘MIME-Version: 1.0’ . «\r\n» .

‘Content-type: text/html; charset=cp1251’ . «\r\n» .

‘From: ‘ . $return . «\r\n» .

‘Reply-To: ‘ . $return . «\r\n» .

‘Return-Path: ‘ . $return . «\r\n» .

‘X-Mailer: PHP/’ . phpversion();

$date = date(‘l\, M dS Y\, h:i:s A’);

mail(«$to», «mail_test», «$date», $headers);

echo «mail sent $date\n»;

Отправка почты со скриптов у вас не заблокирована, поэтому все должно решаться

Пусть хостеры пришлют лог ошибок, будет более понятно, что за косяк при отправке письма по mail()

Ранее работало на этом же хостинге? Вспомните, что делали на сайте, в коде из того, что могло привести к такому косяку?

Думаю, тут нужно включать debug в dle и смотреть там, т.к. скорей всего в лог почтового сервера это не попадёт.

DyaDya:
Пусть хостеры пришлют лог ошибок, будет более понятно, что за косяк при отправке письма по mail()

Ранее работало на этом же хостинге? Вспомните, что делали на сайте, в коде из того, что могло привести к такому косяку?

ничего такого ни делал сайты то не один а три и у всех сайтах также не работает

Читать:
Как обработать callback уведомления от чера php

Похожие статьи