Php mail вывести ошибку

Try this. If I got any error on any file then I got error mail on my email id. Create two files index.php and checkErrorEmail.php and uploaded them to your server. Then load index.php with your browser.

Index.php

<?php
    include('checkErrorEmail.php');
    include('dereporting.php');
    $temp;
    echo 'hi '.$temp;
?>

checkErrorEmail.php

<?php
  // Destinations
  define("ADMIN_EMAIL", "pradeep.callus7@hotmail.com");
  //define("LOG_FILE", "/my/home/errors.log");

  // Destination types
  define("DEST_EMAIL", "1");
  //define("DEST_LOGFILE", "3");

  /* Examples */

  // Send an e-mail to the administrator
  //error_log("Fix me!", DEST_EMAIL, ADMIN_EMAIL);

  // Write the error to our log file
  //error_log("Error", DEST_LOGFILE, LOG_FILE);

  /**
    * my_error_handler($errno, $errstr, $errfile, $errline)
    *
    * Author(s): thanosb, ddonahue
    * Date: May 11, 2008
    * 
    * custom error handler
    *
    * Parameters:
    *  $errno:   Error level
    *  $errstr:  Error message
    *  $errfile: File in which the error was raised
    *  $errline: Line at which the error occurred
    */

  function my_error_handler($errno, $errstr, $errfile, $errline)
  {  
  echo "<br><br><br><br>errno ".$errno.",<br>errstr ".$errstr.",<br>errfile ".$errfile.",<br>errline ".$errline;
      if($errno)
      {
              error_log("Error: $errstr \n error on line $errline in file $errfile \n", DEST_EMAIL, ADMIN_EMAIL);
      }
    /*switch ($errno) {
      case E_USER_ERROR:
        // Send an e-mail to the administrator
        error_log("Error: $errstr \n Fatal error on line $errline in file $errfile \n", DEST_EMAIL, ADMIN_EMAIL);

        // Write the error to our log file
        //error_log("Error: $errstr \n Fatal error on line $errline in file $errfile \n", DEST_LOGFILE, LOG_FILE);
        break;

      case E_USER_WARNING:
        // Write the error to our log file
        //error_log("Warning: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
        break;

      case E_USER_NOTICE:
        // Write the error to our log file
       // error_log("Notice: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
        break;

      default:
        // Write the error to our log file
        //error_log("Unknown error [#$errno]: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
        break;
    }*/

    // Don't execute PHP's internal error handler
    return TRUE;
  }


  // Use set_error_handler() to tell PHP to use our method
  $old_error_handler = set_error_handler("my_error_handler");


?>

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

mailОтправляет электронную почту

Описание

mail(
    string $to,
    string $subject,
    string $message,
    array|string $additional_headers = [],
    string $additional_params = «»
): bool

Список параметров

to

Получатель, или получатели письма.

Формат этого параметра должен соответствовать
» RFC 2822. Несколько примеров:

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

Тема отправляемого письма.

Предостережение

Тема должна соответствовать » RFC 2047.

message

Отправляемое сообщение.

Каждая строка должна быть отделена символом CRLF (\r\n).
Строки не должны быть длиннее 70 символов.

Предостережение

(Только для Windows) Если PHP передаёт данные напрямую SMTP-серверу и
в начале строки стоит точка, то она будет удалена. Чтобы избежать этого замените
все такие точки на две.

<?php
$text
= str_replace("\n.", "\n..", $text);
?>

additional_headers (необязательный)

Строка или массив, которые будут вставлены в конец отправляемых заголовков письма.

Обычно используется для добавления дополнительных заголовков (From, Cc, and Bcc).
Несколько дополнительных заголовков должны быть разделены CRLF (\r\n).
Если для составления этого заголовка используются внешние данные,
то они должны быть проверены для избежания инъекций нежелательных заголовков.

Если передан массив, то его ключи будут именами заголовка, а значения значениями.

Замечание:

До PHP 5.4.42 и 5.5.27, параметр additional_headers
не имел защиты от инъекции.
Так что пользователи должны удостовериться, что передаваемые заголовки
безопасны и содержат только заголовки. т.е. не содержат несколько
переводов строк подряд, что стартует тело сообщения.

Замечание:

При отправке письмо должно содержать
заголовок From. Он может быть установлен с помощью
параметра additional_headers, или значение
по умолчанию может быть установлено в php.ini.

Если заголовок отсутствует, будет сгенерировано сообщение об ошибке
вида Warning: mail(): "sendmail_from" not
set in php.ini or custom "From:" header missing
.
Заголовок From также определяет заголовок
Return-Path при отправке напрямую через SMTP (только Windows).

Замечание:

Если сообщения не отправляются, попробуйте использовать только LF (\n).
Некоторые агенты пересылки сообщений Unix (особенно
» qmail) автоматически заменяют LF на CRLF
(что приводит к двойному CR, если использовалось CRLF).
Используйте эту меру в крайнем случае, так как это нарушает
» RFC 2822.

additional_params (необязательный)

Параметр additional_params может быть
использован для передачи дополнительных флагов в виде аргументов
командной строки для программы сконфигурированной для отправки писем,
указанной директивой sendmail_path. Например, можно
установить отправителя письма при использовании sendmail с помощью опции
-f.

Параметр автоматически экранируется функцией escapeshellcmd(),
чтобы не допустить выполнение команд. Но escapeshellcmd()
позволяет добавлять дополнительные параметры. В целях безопасности
рекомендуется проверять и очищать этот параметр.

Так как escapeshellcmd() применяется автоматически, то нельзя использовать
некоторые символы, допустимые к использованию в email-адресах некоторыми RFC.
mail() не допускает такие символы, поэтому в программах, в которых они требуются,
рекомендуется использовать альтернативы для их отправки (например фреймворки или библиотеки).

Пользователь, под которым работает веб-сервер должен быть добавлен в список
доверенных в конфигурации sendmail для того чтобы избежать добавления заголовка
‘X-Warning’ при указании отправителя с помощью опции (-f).
Для пользователей sendmail — это файл /etc/mail/trusted-users.

Возвращаемые значения

Возвращает true, если письмо было принято для передачи, иначе false.

Важно заметить, что то что письмо было принято для передачи вовсе НЕ означает
что оно достигло получателя.

Список изменений

Версия Описание
7.2.0 Параметр additional_headers может принимать
значения типа массив.

Примеры

Пример #1 Отправка письма.

Использование функции mail() для отправки простого письма:

<?php
// Сообщение
$message = "Line 1\r\nLine 2\r\nLine 3";// На случай если какая-то строка письма длиннее 70 символов мы используем wordwrap()
$message = wordwrap($message, 70, "\r\n");// Отправляем
mail('caffeinated@example.com', 'My Subject', $message);
?>

Пример #2 Отправка письма с дополнительными заголовками.

Добавление простых заголовков, сообщающих почтовому агенту
адреса From и Reply-To:

<?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);
?>

Пример #3 Отправка письма с дополнительными заголовками, переданными массивом

В этом примере посылается то же письмо, что и в примере выше, но
дополнительные заголовки задаются массивом (доступно с 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);
?>

Пример #4 Отправка письма с дополнительными аргументами командной строки.

Параметр additional_params может быть использован
для передачи дополнительных параметров программе, используемой для отправки
писем с помощью директивы sendmail_path.

<?php
mail
('nobody@example.com', 'the subject', 'the message', null,
'-fwebmaster@example.com');
?>

Пример #5 Отправка HTML-сообщения

С помощью функции mail() также можно отправить и HTML-письмо.

<?php
// несколько получателей
$to = 'johny@example.com, sally@example.com'; // обратите внимание на запятую

// тема письма

$subject = 'Birthday Reminders for August';// текст письма
$message = '
<html>
<head>
<title>Birthday Reminders for August</title>
</head>
<body>
<p>Here are the birthdays upcoming in August!</p>
<table>
<tr>
<th>Person</th><th>Day</th><th>Month</th><th>Year</th>
</tr>
<tr>
<td>Johny</td><td>10th</td><td>August</td><td>1970</td>
</tr>
<tr>
<td>Sally</td><td>17th</td><td>August</td><td>1973</td>
</tr>
</table>
</body>
</html>
'
;// Для отправки HTML-письма должен быть установлен заголовок Content-type
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";// Дополнительные заголовки
$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($to, $subject, $message, implode("\r\n", $headers));
?>

Замечание:

Для отправки HTML или других комплексных сообщений рекомендуется использовать
PEAR-пакет » PEAR::Mail_Mime.

Примечания

Замечание:

Реализация SMTP (только Windows) функции mail() в Windows во многом отличается от
реализации в sendmail. Во-первых, она не использует локальную программу для
составления писем, а работает непосредственно с сокетами, что означает что
необходим почтовый агент (MTA), ожидающий
соединений на сокете (может быть как на локальном так и на
удалённом сервере).

Во-вторых, дополнительные заголовки вроде:
From:,
Cc:,
Bcc: и
Date:
интерпретируются в первую очередь не,
MTA, а PHP.

Поэтому параметр to не должен быть адресом вида
«Something <someone@example.com>». Команда
mail может неправильно интерпретировать этот адрес во время передачи
данных MTA.

Замечание:

Не следует использовать функцию mail() для отправки
большого количества писем в цикле. Функция открывает и закрывает
соединение с SMTP-сервером для каждого письма, что не очень эффективно.

Для отправки большого количества сообщений обратите внимание на пакеты
» PEAR::Mail и
» PEAR::Mail_Queue.

Замечание:

Полезные RFC:
» RFC 1896,
» RFC 2045,
» RFC 2046,
» RFC 2047,
» RFC 2048,
» RFC 2049 и
» RFC 2822.

Anonymous

6 years ago

Security advice: Although it is not documented, for the parameters $to and $subject the mail() function changes at least \r and \n to space. So these parameters are safe against injection of additional headers. But you might want to check $to for commas as these separate multiple addresses and you might not want to send to more than one recipient.

The crucial part is the $additional_headers parameter. This parameter can't be cleaned by the mail() function. So it is up to you to prevent unwanted \r or \n to be inserted into the values you put in there. Otherwise you just created a potential spam distributor.

Anonymous

3 years ago

If you notice wrong displayed characters in the email it's because you need to properly set the Content-Type and the Charset in the headers of the email:

<?php
$headers
= 'Content-Type: text/plain; charset=utf-8' . "\r\n";
?>

Mostly, UTF-8 is your best choice.

You can set custom headers with the fourth parameter of the mail() function.

To make the whole thing waterproof, add the following header too:

<?php
$headers
.= 'Content-Transfer-Encoding: base64' . "\r\n";
?>

Now you can use the combination of UTF-8 and Base64 to properly encode the subject line and the recipient name like this:

<?php
$subject
= '=?UTF-8?B?' . base64_encode('Test email with German Umlauts öäüß') . '?=';
$recipient = '=?UTF-8?B?' . base64_encode('Margret Müller') . '?= <recipient@domain.com>';
?>

And don't forget to Base64 encode the email message too:

<?php
$message
= base64_encode('This email contains German Umlauts öäüß.');
?>

All references are taken from:
https://dev.to/lutvit/how-to-make-the-php-mail-function-awesome-3cii

php at simoneast dot net

6 years ago

Often it's helpful to find the exact error message that is triggered by the mail() function. While the function doesn't provide an error directly, you can use error_get_last() when mail() returns false.

<?php
$success
= mail('example@example.com', 'My Subject', $message);
if (!
$success) {
$errorMessage = error_get_last()['message'];
}
?>

(Tested successfully on Windows which uses SMTP by default, but sendmail on Linux/OSX may not provide the same level of detail.)

Thanks to https://stackoverflow.com/a/20203870/195835

charles dot fisher at arconic dot com

5 years ago

I migrated an application to a platform without a local transport agent (MTA). I did not want to configure an MTA, so I wrote this xxmail function to replace mail() with calls to a remote SMTP server. Hopefully it is of some use.

function xxmail($to, $subject, $body, $headers)
{
$smtp = stream_socket_client('tcp://smtp.yourmail.com:25', $eno, $estr, 30);

$B = 8192;
$c = "\r\n";
$s = 'myapp@someserver.com';

fwrite($smtp, 'helo ' . $_ENV['HOSTNAME'] . $c);
$junk = fgets($smtp, $B);

// Envelope
fwrite($smtp, 'mail from: ' . $s . $c);
$junk = fgets($smtp, $B);
fwrite($smtp, 'rcpt to: ' . $to . $c);
$junk = fgets($smtp, $B);
fwrite($smtp, 'data' . $c);
$junk = fgets($smtp, $B);

// Header
fwrite($smtp, 'To: ' . $to . $c);
if(strlen($subject)) fwrite($smtp, 'Subject: ' . $subject . $c);
if(strlen($headers)) fwrite($smtp, $headers); // Must be \r\n (delimited)
fwrite($smtp, $headers . $c);

// Body
if(strlen($body)) fwrite($smtp, $body . $c);
fwrite($smtp, $c . '.' . $c);
$junk = fgets($smtp, $B);

// Close
fwrite($smtp, 'quit' . $c);
$junk = fgets($smtp, $B);
fclose($smtp);
}

imme_emosol

6 months ago

Also see chunk_split (as "alternative" to wordwrap).

atesin > gmail

7 months ago

mail() internals:

doing some tests i can say... if sendmail_path is defined in php.ini or by ini.set(), by calling function like...

mail($to, $subject, $message, $headers, $params)

would be like if php open a shell internally, execute this command, send this text to stdin, and return true if return value == 0

------------
shell> $sendmail_path $params
To: $to
Subject: $subject
$headers

$message
(EOF)
------------

in windows instead using php smtp which is very limited, i prefer to force use sendmail-like behavior, by setting sendmail_path and then use msmtp for windows

Mark Simon

4 years ago

It is worth noting that you can set up a fake sendmail program using the sendmail_path directive in php.ini.

Despite the comment in that file, sendmail_path also works for Window. From https://www.php.net/manual/en/mail.configuration.php#ini.sendmail-path:

This directive works also under Windows. If set, smtp, smtp_port and sendmail_from are ignored and the specified command is executed.

Porjo

13 years ago

Make sure you enclose \r\n in double quotes (not single quotes!) so that PHP can translate that into the correct linefeed code

chris at ocproducts dot com

6 years ago

The 'sendmail' executable which PHP uses on Linux/Mac (not Windows) expects "\n" as a line separator.

This executable is a standard, and emulated by other MTAs.

"\n" is confirmed required for qmail and postfix, probably also for sendmail and exim but I have not tested.

If you pass through using "\r\n" as a separator it may appear to work, but your email will be subtly corrupted and some middleware may break. It only works because some systems will clean up your mistake.

If you are implementing DKIM be very careful, as DKIM checks will fail (at least on popular validation tools) if you screw this up. DKIM must be calculated using "\r\n" but then you must switch it all to "\n" when using the PHP mail function.

On Windows, however, you should use "\r\n" because PHP is using SMTP in this situation, and hence the normal rules of the SMTP protocol (not the normal rules of Unix piping) apply.

pangz dot lab at gmail dot com

3 years ago

* Sending email with attachment

function sendMail(
string $fileAttachment,
string $mailMessage = MAIL_CONF["mailMessage"],
string $subject = MAIL_CONF["subject"],
string $toAddress = MAIL_CONF["toAddress"],
string $fromMail = MAIL_CONF["fromMail"]
): bool {

$fileAttachment = trim($fileAttachment);
$from = $fromMail;
$pathInfo = pathinfo($fileAttachment);
$attchmentName = "attachment_".date("YmdHms").(
(isset($pathInfo['extension']))? ".".$pathInfo['extension'] : ""
);

$attachment = chunk_split(base64_encode(file_get_contents($fileAttachment)));
$boundary = "PHP-mixed-".md5(time());
$boundWithPre = "\n--".$boundary;

$headers = "From: $from";
$headers .= "\nReply-To: $from";
$headers .= "\nContent-Type: multipart/mixed; boundary=\"".$boundary."\"";

$message = $boundWithPre;
$message .= "\n Content-Type: text/plain; charset=UTF-8\n";
$message .= "\n $mailMessage";

$message .= $boundWithPre;
$message .= "\nContent-Type: application/octet-stream; name=\"".$attchmentName."\"";
$message .= "\nContent-Transfer-Encoding: base64\n";
$message .= "\nContent-Disposition: attachment\n";
$message .= $attachment;
$message .= $boundWithPre."--";

return mail($toAddress, $subject, $message, $headers);
}

* Sending email in html

function sendHtmlMail(
string $mailMessage = MAIL_CONF["mailMessage"],
string $subject = MAIL_CONF["subject"],
array $toAddress = MAIL_CONF["toAddress"],
string $fromMail = MAIL_CONF["fromMail"]
): bool {

$to = implode(",", $toAddress);
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
$headers[] = 'To: '.$to;
$headers[] = 'From: '.$fromMail;

return mail($to, $subject, $mailMessage, implode("\r\n", $headers));
}

ABOMB

11 years ago

I was having delivery issues from this function to Gmail, Yahoo, AOL, etc. I used the notes here to figure that you need to be setting your Return-Path to a valid email to catch bounces. There are two extra delivery gotchas on top of that:

1) The domain in the email used in the -f option in the php.ini sendmail parameter or in the mail() extra parameters field, needs to have a valid SPF record for the domain (in DNS as a "TXT" record type for sure and add an additional "SPF" type record if possible). Why? That's header field being used for spam checks.

2) You should also use a domain key or DKIM. The trick here is that the domain key/DKIM is case sensitive! I used Cpanel to create my domain key which automatically used all lowercase domain names in the key creation. I found when sending email and using a camel case "-f account@MyDomainHere.Com" option, my key was not accepted. However it was accepted when I used "-f account@mydomainhere.com".

There are many other factors that can contribute to mail not getting to inboxes, including your own multiple failed testing attempts, so I suggest you consult each site's guidelines and don't ask me for help. These are just the couple technical issues that helped my case.

I hope this saves someone some time and headaches...

Ben Cooke

17 years ago

Note that there is a big difference between the behavior of this function on Windows systems vs. UNIX systems. On Windows it delivers directly to an SMTP server, while on a UNIX system it uses a local command to hand off to the system's own MTA.

The upshot of all this is that on a Windows system your message and headers must use the standard line endings \r\n as prescribed by the email specs. On a UNIX system the MTA's "sendmail" interface assumes that recieved data will use UNIX line endings and will turn any \n to \r\n, so you must supply only \n to mail() on a UNIX system to avoid the MTA hypercorrecting to \r\r\n.

If you use plain old \n on a Windows system, some MTAs will get a little upset. qmail in particular will refuse outright to accept any message that has a lonely \n without an accompanying \r.

pavel.lint at vk.com

11 years ago

Here's a small handy function I use to send email in UTF-8.

<?php
function mail_utf8($to, $from_user, $from_email,
$subject = '(No subject)', $message = '')
{
$from_user = "=?UTF-8?B?".base64_encode($from_user)."?=";
$subject = "=?UTF-8?B?".base64_encode($subject)."?=";$headers = "From: $from_user <$from_email>\r\n".
"MIME-Version: 1.0" . "\r\n" .
"Content-type: text/html; charset=UTF-8" . "\r\n";

return

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

eeeugeneee

6 years ago

Send mail with minimal requirements from email services.

<?php
$encoding
= "utf-8";// Preferences for Subject field
$subject_preferences = array(
"input-charset" => $encoding,
"output-charset" => $encoding,
"line-length" => 76,
"line-break-chars" => "\r\n"
);// Mail header
$header = "Content-type: text/html; charset=".$encoding." \r\n";
$header .= "From: ".$from_name." <".$from_mail."> \r\n";
$header .= "MIME-Version: 1.0 \r\n";
$header .= "Content-Transfer-Encoding: 8bit \r\n";
$header .= "Date: ".date("r (T)")." \r\n";
$header .= iconv_mime_encode("Subject", $mail_subject, $subject_preferences);// Send mail
mail($mail_to, $mail_subject, $mail_message, $header);
?>

rexlorenzo at gmail dot com

11 years ago

Be careful to not put extra spaces for the $headers variable.

For example, this didn't work on our servers:

$headers = "From: $from \r\n Bcc: $bcc \r\n";

But this did:

$headers = "From: $from\r\nBcc: $bcc\r\n";

Notice the removal of the spaces around the first \r\n.

Anonymous

6 months ago

So far I used the following to make sure special charakters where correctly shown in the mail subject:

<?php $subject = '=?utf-8?B?' . base64_encode($subject) . '?='; ?>

But with very long subjects, the header line gets longer than 76 chars and some e-mail servers really don't like that... So this is my new solution:

<?php $subject = substr(mb_encode_mimeheader("Subject: " . $subject, 'utf-8', 'B', "\r\n", 0), 9); ?>

Please note: I added "Subject: " in front of $subject and stripped it of afterwards. This is to make sure, that the necessarry space is reserved, as PHP will add the "Subject: " itself...

Max AT

11 years ago

To define a mail sensitivity you have to put this line in the headers:

<?php
$headers
= "MIME-Version: 1.0\n" ;
$headers .= "Content-Type: text/html; charset=\"iso-8859-1\"\n";$headers .= "Sensitivity: Personal\n";$status = mail($to, $subject, $message,$headers);
?>

Possible Options:
Sensitivity: Normal, Personal, Private and Company-Confidential

These will be recognised and handled in Outlook, Thunderbird and others.

andrew at my-syte dot com

10 months ago

Regarding To:

be careful not to duplicate To in the additional_headers,

lest gmail already flags it thus:

host gmail-smtp-in.l.google.com [142.251.xx.xx]
SMTP error from remote mail server after end of data:
550-5.7.1 [xxx.xxx.xx.xx] This message is not RFC 5322 compliant, the issue is:
550-5.7.1 duplicate To headers. To reduce the amount of spam sent to Gmail,
550-5.7.1 this message has been blocked. Please review
550 5.7.1 RFC 5322 specifications for more information.

php dot net at schrecktech dot com

18 years ago

When sending MIME email make sure you follow the documentation with the "70" characters per line...you may end up with missing characters...and that is really hard to track down...

Chese

Guest


  • #1

Отловить в PHP ошибку при отправлении почты(mail)

Функция mail возврашает TRUE или FALSE, а можно ли при FALSE отловить, почему именно не ушло письмо т.е. код ошибки.

  • #2

используй [m]imap_mail[/m]
тексты ошибок — через [m]imap_errors[/m], [m]imap_last_error[/m]

Chese

Guest


  • #3

А если нет imap, его в самом деле нет :)

  • #4

тогда все пропало.
в исходниках нет возврата ошибок — есть либо TRUE, либо FALSE

Код:

        if (php_mail(to, subject, message, headers, extra_cmd TSRMLS_CC)) {
                RETVAL_TRUE;
        } else {
                RETVAL_FALSE;
        }

Chese

Guest


  • #5

Понято, значит будем просто ругаться без объяснения причин.

  • #6

Автор оригинала: Chese
Понято, значит будем просто ругаться без объяснения причин.

Что кстати не корректно:) Но другого выхода нет…

Barlone

Guest


  • #7

Re: Отловить в PHP ошибку при отправлении почты(mail)

Автор оригинала: Chese
Функция mail возврашает TRUE или FALSE, а можно ли при FALSE отловить, почему именно не ушло письмо т.е. код ошибки.

Не уйти оно может только по одной причине — в php.ini путь к sendmail указан неправильно.

Chese

Guest


  • #8

Не уйти оно может только по одной причине — в php.ini путь к sendmail указан неправильно

Ну по чему? ;) Если емайл верный, а записи в DNS про домен нет, или у Sendmail переполнена очередь и он не возьмет в отправку….

Barlone

Guest


  • #9

Если емайл верный, а записи в DNS про домен нет

… то письмо успешно передастся sendmail’у, а вот он уже не сможет его доставить. Очередь переполнена? Ну не знаю, тестировать не возьмусь :)

trolik

Guest


  • #10

зачем юзать функцию mail?
передавай парметры sendmail и пиши тело письма с заголовками ему же… а потом анализируй код возврата

-ViT-

Guest


  • #11

А вот что сегодня выдал броузер….

Автор оригинала: tony2001
тогда все пропало.
в исходниках нет возврата ошибок — есть либо TRUE, либо FALSE

Я как раз сегодня добрался до функции mail. Иногда пропадает переменная сессии и в качестве e-mail передается пустое поле — и тогда броузер пишет (цитирую):

Warning: Bad Message destination in F:\WEBProjects\inetpub\wwwroot\PHPDeveloping\Regform2.phtml on line 73

То есть какая-то же диагностика есть?? :confused:

Barlone

Guest


  • #12

Под виндой mail работает совсем не так, как под unix.

  • #13

ViT:
какая диагностика ?
неправильный аргумент приходит — вот и ошибка.
проверяй ДО и все будет ок.
исходники посмотри — там все достаточно ясно.

-ViT-

Guest


  • #14

2 tony2001: — это я знаю, и в данном случае потерянный аргумент — это нормально, это стадия отладки у меня шла… Я просто хочу спросить (абсолютно ПО теме топика) — что раз пришло такое сообщение, значит все же что-то как-то диагносцируется? В исходниках (приведенных тобой) — все совершенно ясно, простейшая конструкция.. Но кто тогда вернул мне этот мессадж? :)

2 Barlone: ты прав, это PHP у меня крутится под IIS, и клиент, с которого снято сообщение — WinXP/Opera. Но ведь ядро PHP (сорцы) — одинаково или тоже нет?

  • #15

речь шла о том «как определить почему не доставляется письмо».
так ?
логично предположить, что элементарная проверка на «а что нам передали как е-мэйл?» там присутствует.
так ?
вот ты видишь ее результат.
более подробно — смотри исходники.

честно говоря, немного не понимаю понятия «диагностика».
если проверка аргумента — это диагностика, то да, диагностика есть.

Barlone

Guest


  • #16

Специально посмотрел в исходники РНР :)
Для Win (#ifdef PHP_WIN32) там идет отправка по smtp, и какие-то ошибки в smtp-сессии видимо отлавливаются.
Для не-win никаких проверок не делается, popen’ом открывается sendmail, ему пихаются «To:», «Subject:», остальные заголовки (как есть) и тело письма. Ошибка может быть только одна: «Could not execute mail delivery program» если popen не сработал.

-ViT-

Guest


  • #17

2 Barlone:
Вот спасибо, а то я никак до исходников не доберусь! :(
Лично мне так механизм стал намного понятнее!
Следовательно, если переносить хост на Unix-сервера, то надо вновь очень тщательно тестить/вычищать/модернизировать все скрипты…. мда, жаль :(

  • #18

http://cvs.php.net/co.php/php4/ext/standard/mail.c?login=2&r=1.66.2.1
смотреть
php_mail() & PHP_FUNCTION(mail)

Barlone

Guest


  • #19

Ну тестить-то надо в любом случае. :) Модернизировать ? Зачем ? Если письмо формируется правильно, без разницы, как оно отправляется.
Кстати, если указать sendmail_path под виндой, то он будет использоваться, и отправляться как на unix. Остается только найти sendmail под винду. :)

Chese

Guest


  • #20

Автор оригинала: trolik
зачем юзать функцию mail?
передавай парметры sendmail и пиши тело письма с заголовками ему же… а потом анализируй код возврата

Молчит как партизан sendmail

PHP:

error_reporting(E_ALL);
$mailer = popen ("/usr/sbin/sendmail -t -i","w");
fwrite ($mailer,"Subject: Test
From: [email][email protected][/email]
To: aaa@[email protected]

Test!!!
");
$read = fread($mailer, 2096);
echo $read;
pclose ($mailer);

PHP предлагает гибкие настройки вывода ошибок, среди которых функия error_reporting($level) – задает, какие ошибки PHP попадут в отчет, могут быть значения:

  • E_ALL – все ошибки,
  • E_ERROR – критические ошибки,
  • E_WARNING – предупреждения,
  • E_PARSE – ошибки синтаксиса,
  • E_NOTICE – замечания,
  • E_CORE_ERROR – ошибки обработчика,
  • E_CORE_WARNING – предупреждения обработчика,
  • E_COMPILE_ERROR – ошибки компилятора,
  • E_COMPILE_WARNING – предупреждения компилятора,
  • E_USER_ERROR – ошибки пользователей,
  • E_USER_WARNING – предупреждения пользователей,
  • E_USER_NOTICE – уведомления пользователей.

1

Вывод ошибок в браузере

error_reporting(E_ALL);
ini_set('display_errors', 'On'); 

PHP

В htaccess

php_value error_reporting "E_ALL"
php_flag display_errors On

htaccess

На рабочем проекте вывод ошибок лучше сделать только у авторизированного пользователя или в крайнем случаи по IP.

2

Запись ошибок в лог файл

error_reporting(E_ALL);
ini_set('display_errors', 'Off'); 
ini_set('log_errors', 'On');
ini_set('error_log', $_SERVER['DOCUMENT_ROOT'] . '/logs/php-errors.log');

PHP

Файлы логов также не должны быть доступны из браузера, храните их в закрытой директории с файлом .htaccess:

Order Allow,Deny
Deny from all

htaccess

Или запретить доступ к файлам по расширению .log (заодно и другие системные файлы и исходники):

<FilesMatch ".(htaccess|htpasswd|bak|ini|log|sh|inc|config|psd|fla|ai)$">
Order Allow,Deny
Deny from all
</FilesMatch>

htaccess

3

Отправка ошибок на e-mail

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

Первый – register_shutdown_function() регистрирует функцию, которая выполнится при завершении работы скрипта, error_get_last() получает последнюю ошибку.

register_shutdown_function('error_alert');

function error_alert() 
{ 
	$error = error_get_last();
	if (!empty($error)) {
		mail('mail@example.com', 'Ошибка на сайте example.com', print_r($error, true)); 
	}
}

PHP

Стоит учесть что оператор управления ошибками (знак @) работать в данном случаи не будет и письмо будет отправляться при каждой ошибке.

Второй метод использует «пользовательский обработчик ошибок», поэтому в браузер ошибки выводится не будут.

function error_alert($type, $message, $file, $line, $vars)
{
	$error = array(
		'type'    => $type,
		'message' => $message,
		'file'    => $file,
		'line'    => $line
	);
	error_log(print_r($error, true), 1, 'mail@example.com', 'From: mail@example.com');
}

set_error_handler('error_alert');

PHP

4

Пользовательские ошибки

PHP позволяет разработчику самому объявлять ошибки, которые выведутся в браузере или в логе. Для создания ошибки используется функция trigger_error():

trigger_error('Пользовательская ошибка', E_USER_ERROR);

PHP

Результат:

Fatal error: Пользовательская ошибка in /public_html/script.php on line 2
  • E_USER_ERROR – критическая ошибка,
  • E_USER_WARNING – не критическая,
  • E_USER_NOTICE – сообщения которые не являются ошибками,
  • E_USER_DEPRECATED – сообщения о устаревшем коде.

10.10.2019, обновлено 09.10.2021

Другие публикации

HTTP коды

Список основных кодов состояния HTTP, без WebDAV.

Автоматическое сжатие и оптимизация картинок на сайте

Изображения нужно сжимать для ускорения скорости загрузки сайта, но как это сделать? На многих хостингах нет…

Работа с JSON в PHP

JSON (JavaScript Object Notation) – текстовый формат обмена данными, основанный на JavaScript, который представляет собой набор пар {ключ: значение}. Значение может быть массивом, числом, строкой и…

Пример парсинга html-страницы на phpQuery

phpQuery – это удобный HTML парсер взявший за основу селекторы, фильтры и методы jQuery, которые позволяют…

Примеры отправки AJAX JQuery

AJAX позволяет отправить и получить данные без перезагрузки страницы. Например, делать проверку форм, подгружать контент и т.д. А функции JQuery значительно упрощают работу.

Подключение к платежной системе Сбербанка

После регистрации в системе эквайринга Сбербанка и получив доступ к тестовой среде, можно приступить к интеграции с…

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

mailОтправляет электронную почту

Описание

mail(
    string $to,
    string $subject,
    string $message,
    array|string $additional_headers = [],
    string $additional_params = «»
): bool

Список параметров

to

Получатель, или получатели письма.

Формат этого параметра должен соответствовать
» RFC 2822. Несколько примеров:

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

Тема отправляемого письма.

Предостережение

Тема должна соответствовать » RFC 2047.

message

Отправляемое сообщение.

Каждая строка должна быть отделена символом CRLF (rn).
Строки не должны быть длиннее 70 символов.

Предостережение

(Только для Windows) Если PHP передаёт данные напрямую SMTP-серверу и
в начале строки стоит точка, то она будет удалена. Чтобы избежать этого замените
все такие точки на две.


<?php
$text
= str_replace("n.", "n..", $text);
?>

additional_headers (необязательный)

Строка или массив, которые будут вставлены в конец отправляемых заголовков письма.

Обычно используется для добавления дополнительных заголовков (From, Cc, and Bcc).
Несколько дополнительных заголовков должны быть разделены CRLF (rn).
Если для составления этого заголовка используются внешние данные,
то они должны быть проверены для избежания инъекций нежелательных заголовков.

Если передан массив, то его ключи будут именами заголовка, а значения значениями.

Замечание:

До PHP 5.4.42 и 5.5.27, параметр additional_headers
не имел защиты от инъекции.
Так что пользователи должны удостовериться, что передаваемые заголовки
безопасны и содержат только заголовки. т.е. не содержат несколько
переводов строк подряд, что стартует тело сообщения.

Замечание:

При отправке письмо должно содержать
заголовок From. Он может быть установлен с помощью
параметра additional_headers, или значение
по умолчанию может быть установлено в php.ini.

Если заголовок отсутствует, будет сгенерировано сообщение об ошибке
вида Warning: mail(): "sendmail_from" not
set in php.ini or custom "From:" header missing
.
Заголовок From также определяет заголовок
Return-Path при отправке напрямую через SMTP (только Windows).

Замечание:

Если сообщения не отправляются, попробуйте использовать только LF (n).
Некоторые агенты пересылки сообщений Unix (особенно
» qmail) автоматически заменяют LF на CRLF
(что приводит к двойному CR, если использовалось CRLF).
Используйте эту меру в крайнем случае, так как это нарушает
» RFC 2822.

additional_params (необязательный)

Параметр additional_params может быть
использован для передачи дополнительных флагов в виде аргументов
командной строки для программы сконфигурированной для отправки писем,
указанной директивой sendmail_path. Например, можно
установить отправителя письма при использовании sendmail с помощью опции
-f.

Параметр автоматически экранируется функцией escapeshellcmd(),
чтобы не допустить выполнение команд. Но escapeshellcmd()
позволяет добавлять дополнительные параметры. В целях безопасности
рекомендуется проверять и очищать этот параметр.

Так как escapeshellcmd() применяется автоматически, то нельзя использовать
некоторые символы, допустимые к использованию в email-адресах некоторыми RFC.
mail() не допускает такие символы, поэтому в программах, в которых они требуются,
рекомендуется использовать альтернативы для их отправки (например фреймворки или библиотеки).

Пользователь, под которым работает веб-сервер должен быть добавлен в список
доверенных в конфигурации sendmail для того чтобы избежать добавления заголовка
‘X-Warning’ при указании отправителя с помощью опции (-f).
Для пользователей sendmail — это файл /etc/mail/trusted-users.

Возвращаемые значения

Возвращает true, если письмо было принято для передачи, иначе false.

Важно заметить, что то что письмо было принято для передачи вовсе НЕ означает
что оно достигло получателя.

Список изменений

Версия Описание
7.2.0 Параметр additional_headers может принимать
значения типа массив.

Примеры

Пример #1 Отправка письма.

Использование функции mail() для отправки простого письма:


<?php
// Сообщение
$message = "Line 1rnLine 2rnLine 3";// На случай если какая-то строка письма длиннее 70 символов мы используем wordwrap()
$message = wordwrap($message, 70, "rn");// Отправляем
mail('caffeinated@example.com', 'My Subject', $message);
?>

Пример #2 Отправка письма с дополнительными заголовками.

Добавление простых заголовков, сообщающих почтовому агенту
адреса From и Reply-To:


<?php
$to
= 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "rn" .
'Reply-To: webmaster@example.com' . "rn" .
'X-Mailer: PHP/' . phpversion();mail($to, $subject, $message, $headers);
?>

Пример #3 Отправка письма с дополнительными заголовками, переданными массивом

В этом примере посылается то же письмо, что и в примере выше, но
дополнительные заголовки задаются массивом (доступно с 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);
?>

Пример #4 Отправка письма с дополнительными аргументами командной строки.

Параметр additional_params может быть использован
для передачи дополнительных параметров программе, используемой для отправки
писем с помощью директивы sendmail_path.


<?php
mail
('nobody@example.com', 'the subject', 'the message', null,
'-fwebmaster@example.com');
?>

Пример #5 Отправка HTML-сообщения

С помощью функции mail() также можно отправить и HTML-письмо.


<?php
// несколько получателей
$to = 'johny@example.com, sally@example.com'; // обратите внимание на запятую

// тема письма

$subject = 'Birthday Reminders for August';// текст письма
$message = '
<html>
<head>
<title>Birthday Reminders for August</title>
</head>
<body>
<p>Here are the birthdays upcoming in August!</p>
<table>
<tr>
<th>Person</th><th>Day</th><th>Month</th><th>Year</th>
</tr>
<tr>
<td>Johny</td><td>10th</td><td>August</td><td>1970</td>
</tr>
<tr>
<td>Sally</td><td>17th</td><td>August</td><td>1973</td>
</tr>
</table>
</body>
</html>
'
;// Для отправки HTML-письма должен быть установлен заголовок Content-type
$headers = 'MIME-Version: 1.0' . "rn";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "rn";// Дополнительные заголовки
$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($to, $subject, $message, implode("rn", $headers));
?>

Замечание:

Для отправки HTML или других комплексных сообщений рекомендуется использовать
PEAR-пакет » PEAR::Mail_Mime.

Примечания

Замечание:

Реализация SMTP (только Windows) функции mail() в Windows во многом отличается от
реализации в sendmail. Во-первых, она не использует локальную программу для
составления писем, а работает непосредственно с сокетами, что означает что
необходим почтовый агент (MTA), ожидающий
соединений на сокете (может быть как на локальном так и на
удалённом сервере).

Во-вторых, дополнительные заголовки вроде:
From:,
Cc:,
Bcc: и
Date:
интерпретируются в первую очередь не,
MTA, а PHP.

Поэтому параметр to не должен быть адресом вида
«Something <someone@example.com>». Команда
mail может неправильно интерпретировать этот адрес во время передачи
данных MTA.

Замечание:

Не следует использовать функцию mail() для отправки
большого количества писем в цикле. Функция открывает и закрывает
соединение с SMTP-сервером для каждого письма, что не очень эффективно.

Для отправки большого количества сообщений обратите внимание на пакеты
» PEAR::Mail и
» PEAR::Mail_Queue.

Замечание:

Полезные RFC:
» RFC 1896,
» RFC 2045,
» RFC 2046,
» RFC 2047,
» RFC 2048,
» RFC 2049 и
» RFC 2822.

Anonymous

3 years ago


If you notice wrong displayed characters in the email it's because you need to properly set the Content-Type and the Charset in the headers of the email:

<?php
$headers
= 'Content-Type: text/plain; charset=utf-8' . "rn";
?>

Mostly, UTF-8 is your best choice.

You can set custom headers with the fourth parameter of the mail() function.

To make the whole thing waterproof, add the following header too:

<?php
$headers
.= 'Content-Transfer-Encoding: base64' . "rn";
?>

Now you can use the combination of UTF-8 and Base64 to properly encode the subject line and the recipient name like this:

<?php
$subject
= '=?UTF-8?B?' . base64_encode('Test email with German Umlauts öäüß') . '?=';
$recipient = '=?UTF-8?B?' . base64_encode('Margret Müller') . '?= <recipient@domain.com>';
?>

And don't forget to Base64 encode the email message too:

<?php
$message
= base64_encode('This email contains German Umlauts öäüß.');
?>

All references are taken from:
https://dev.to/lutvit/how-to-make-the-php-mail-function-awesome-3cii

Anonymous

6 years ago


Security advice: Although it is not documented, for the parameters $to and $subject the mail() function changes at least r and n to space. So these parameters are safe against injection of additional headers. But you might want to check $to for commas as these separate multiple addresses and you might not want to send to more than one recipient.

The crucial part is the $additional_headers parameter. This parameter can't be cleaned by the mail() function. So it is up to you to prevent unwanted r or n to be inserted into the values you put in there. Otherwise you just created a potential spam distributor.

php at simoneast dot net

6 years ago


Often it's helpful to find the exact error message that is triggered by the mail() function. While the function doesn't provide an error directly, you can use error_get_last() when mail() returns false.

<?php
$success
= mail('example@example.com', 'My Subject', $message);
if (!
$success) {
   
$errorMessage = error_get_last()['message'];
}
?>

(Tested successfully on Windows which uses SMTP by default, but sendmail on Linux/OSX may not provide the same level of detail.)

Thanks to https://stackoverflow.com/a/20203870/195835

imme_emosol

3 months ago


Also see chunk_split (as "alternative" to wordwrap).

charles dot fisher at arconic dot com

5 years ago


I migrated an application to a platform without a local transport agent (MTA). I did not want to configure an MTA, so I wrote this xxmail function to replace mail() with calls to a remote SMTP server. Hopefully it is of some use.

function xxmail($to, $subject, $body, $headers)
{
$smtp = stream_socket_client('tcp://smtp.yourmail.com:25', $eno, $estr, 30);

$B = 8192;
$c = "rn";
$s = 'myapp@someserver.com';

fwrite($smtp, 'helo ' . $_ENV['HOSTNAME'] . $c);
  $junk = fgets($smtp, $B);

// Envelope
fwrite($smtp, 'mail from: ' . $s . $c);
  $junk = fgets($smtp, $B);
fwrite($smtp, 'rcpt to: ' . $to . $c);
  $junk = fgets($smtp, $B);
fwrite($smtp, 'data' . $c);
  $junk = fgets($smtp, $B);

// Header
fwrite($smtp, 'To: ' . $to . $c);
if(strlen($subject)) fwrite($smtp, 'Subject: ' . $subject . $c);
if(strlen($headers)) fwrite($smtp, $headers); // Must be rn (delimited)
fwrite($smtp, $headers . $c);

// Body
if(strlen($body)) fwrite($smtp, $body . $c);
fwrite($smtp, $c . '.' . $c);
  $junk = fgets($smtp, $B);

// Close
fwrite($smtp, 'quit' . $c);
  $junk = fgets($smtp, $B);
fclose($smtp);
}

chris at ocproducts dot com

6 years ago


The 'sendmail' executable which PHP uses on Linux/Mac (not Windows) expects "n" as a line separator.

This executable is a standard, and emulated by other MTAs.

"n" is confirmed required for qmail and postfix, probably also for sendmail and exim but I have not tested.

If you pass through using "rn" as a separator it may appear to work, but your email will be subtly corrupted and some middleware may break. It only works because some systems will clean up your mistake.

If you are implementing DKIM be very careful, as DKIM checks will fail (at least on popular validation tools) if you screw this up. DKIM must be calculated using "rn" but then you must switch it all to "n" when using the PHP mail function.

On Windows, however, you should use "rn" because PHP is using SMTP in this situation, and hence the normal rules of the SMTP protocol (not the normal rules of Unix piping) apply.

pangz dot lab at gmail dot com

2 years ago


* Sending email with attachment

function sendMail(
    string $fileAttachment,
    string $mailMessage = MAIL_CONF["mailMessage"],
    string $subject     = MAIL_CONF["subject"],
    string $toAddress   = MAIL_CONF["toAddress"],
    string $fromMail    = MAIL_CONF["fromMail"]
): bool {

        $fileAttachment = trim($fileAttachment);
    $from           = $fromMail;
    $pathInfo       = pathinfo($fileAttachment);
    $attchmentName  = "attachment_".date("YmdHms").(
    (isset($pathInfo['extension']))? ".".$pathInfo['extension'] : ""
    );

        $attachment    = chunk_split(base64_encode(file_get_contents($fileAttachment)));
    $boundary      = "PHP-mixed-".md5(time());
    $boundWithPre  = "n--".$boundary;

        $headers   = "From: $from";
    $headers  .= "nReply-To: $from";
    $headers  .= "nContent-Type: multipart/mixed; boundary="".$boundary.""";

        $message   = $boundWithPre;
    $message  .= "n Content-Type: text/plain; charset=UTF-8n";
    $message  .= "n $mailMessage";

        $message .= $boundWithPre;
    $message .= "nContent-Type: application/octet-stream; name="".$attchmentName.""";
    $message .= "nContent-Transfer-Encoding: base64n";
    $message .= "nContent-Disposition: attachmentn";
    $message .= $attachment;
    $message .= $boundWithPre."--";

        return mail($toAddress, $subject, $message, $headers);
}

* Sending email in html

function sendHtmlMail(
    string $mailMessage = MAIL_CONF["mailMessage"],
    string $subject     = MAIL_CONF["subject"],
    array $toAddress    = MAIL_CONF["toAddress"],
    string $fromMail    = MAIL_CONF["fromMail"]
): bool {

        $to        = implode(",", $toAddress);
    $headers[] = 'MIME-Version: 1.0';
    $headers[] = 'Content-type: text/html; charset=iso-8859-1';   
    $headers[] = 'To: '.$to;
    $headers[] = 'From: '.$fromMail;   

    return mail($to, $subject, $mailMessage, implode("rn", $headers));
}

Mark Simon

3 years ago


It is worth noting that you can set up a fake sendmail program using the sendmail_path directive in php.ini.

Despite the comment in that file, sendmail_path also works for Window. From https://www.php.net/manual/en/mail.configuration.php#ini.sendmail-path:

This directive works also under Windows. If set, smtp, smtp_port and sendmail_from are ignored and the specified command is executed.

Porjo

12 years ago


Make sure you enclose rn in double quotes (not single quotes!) so that PHP can translate that into the correct linefeed code

eeeugeneee

5 years ago


Send mail with minimal requirements from email services.

<?php
    $encoding
= "utf-8";// Preferences for Subject field
   
$subject_preferences = array(
       
"input-charset" => $encoding,
       
"output-charset" => $encoding,
       
"line-length" => 76,
       
"line-break-chars" => "rn"
   
);// Mail header
   
$header = "Content-type: text/html; charset=".$encoding." rn";
   
$header .= "From: ".$from_name." <".$from_mail."> rn";
   
$header .= "MIME-Version: 1.0 rn";
   
$header .= "Content-Transfer-Encoding: 8bit rn";
   
$header .= "Date: ".date("r (T)")." rn";
   
$header .= iconv_mime_encode("Subject", $mail_subject, $subject_preferences);// Send mail
   
mail($mail_to, $mail_subject, $mail_message, $header);
?>

ABOMB

11 years ago


I was having delivery issues from this function to Gmail, Yahoo, AOL, etc.  I used the notes here to figure that you need to be setting your Return-Path to a valid email to catch bounces.  There are two extra delivery gotchas on top of that:

1) The domain in the email used in the -f option in the php.ini sendmail parameter or in the mail() extra parameters field, needs to have a valid SPF record for the domain (in DNS as a "TXT" record type for sure and add an additional  "SPF" type record if possible).  Why? That's header field being used for spam checks.

2) You should also use a domain key or DKIM.  The trick here is that the domain key/DKIM is case sensitive!  I used Cpanel to create my domain key which automatically used all lowercase domain names in the key creation.  I found when  sending email and using a camel case "-f account@MyDomainHere.Com" option, my key was not accepted.  However it was accepted when I used "-f account@mydomainhere.com".

There are many other factors that can contribute to mail not getting to inboxes, including your own multiple failed testing attempts, so I suggest you consult each site's guidelines and don't ask me for help.  These are just the couple technical issues that helped my case.

I hope this saves someone some time and headaches...

Ben Cooke

17 years ago


Note that there is a big difference between the behavior of this function on Windows systems vs. UNIX systems. On Windows it delivers directly to an SMTP server, while on a UNIX system it uses a local command to hand off to the system's own MTA.

The upshot of all this is that on a Windows system your  message and headers must use the standard line endings rn as prescribed by the email specs. On a UNIX system the MTA's "sendmail" interface assumes that recieved data will use UNIX line endings and will turn any n to rn, so you must supply only n to mail() on a UNIX system to avoid the MTA hypercorrecting to rrn.

If you use plain old n on a Windows system, some MTAs will get a little upset. qmail in particular will refuse outright to accept any message that has a lonely n without an accompanying r.

Anonymous

2 months ago


So far I used the following to make sure special charakters where correctly shown in the mail subject:

<?php $subject = '=?utf-8?B?' . base64_encode($subject) . '?='; ?>

But with very long subjects, the header line gets longer than 76 chars and some e-mail servers really don't like that... So this is my new solution:

<?php $subject = substr(mb_encode_mimeheader("Subject: " . $subject, 'utf-8', 'B', "rn", 0), 9); ?>

Please note: I added "Subject: " in front of $subject and stripped it of afterwards. This is to make sure, that the necessarry space is reserved, as PHP will add the "Subject: " itself...

atesin > gmail

4 months ago


mail() internals:

doing some tests i can say... if sendmail_path is defined in php.ini or by ini.set(), by calling function like...

mail($to, $subject, $message, $headers, $params)

would be like if php open a shell internally, execute this command, send this text to stdin, and return true if return value == 0

------------
shell> $sendmail_path $params
To: $to
Subject: $subject
$headers

$message
(EOF)
------------

in windows instead using php smtp which is very limited, i prefer to force use sendmail-like behavior, by setting sendmail_path and then use msmtp for windows

rexlorenzo at gmail dot com

11 years ago


Be careful to not put extra spaces for the $headers variable.

For example, this didn't work on our servers:

$headers = "From: $from rn Bcc: $bcc rn";

But this did:

$headers = "From: $fromrnBcc: $bccrn";

Notice the removal of the spaces around the first rn.

pavel.lint at vk.com

11 years ago


Here's a small handy function I use to send email in UTF-8.

<?php
function mail_utf8($to, $from_user, $from_email,
                                            
$subject = '(No subject)', $message = '')
   {
     
$from_user = "=?UTF-8?B?".base64_encode($from_user)."?=";
     
$subject = "=?UTF-8?B?".base64_encode($subject)."?=";$headers = "From: $from_user <$from_email>rn".
              
"MIME-Version: 1.0" . "rn" .
              
"Content-type: text/html; charset=UTF-8" . "rn";

     return

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

Max AT

11 years ago


To define a mail sensitivity you have to put this line in the headers:

<?php
        $headers
= "MIME-Version: 1.0n" ;
       
$headers .= "Content-Type: text/html; charset="iso-8859-1"n";$headers .= "Sensitivity: Personaln";$status   = mail($to, $subject, $message,$headers);
?>

Possible Options:
Sensitivity: Normal, Personal, Private and Company-Confidential

These will be recognised and handled in Outlook, Thunderbird and others.

andrew at my-syte dot com

7 months ago


Regarding To:

be careful not to duplicate To in the additional_headers,

lest gmail already flags it thus:

host gmail-smtp-in.l.google.com [142.251.xx.xx]
SMTP error from remote mail server after end of data:
550-5.7.1 [xxx.xxx.xx.xx] This message is not RFC 5322 compliant, the issue is:
550-5.7.1 duplicate To headers. To reduce the amount of spam sent to Gmail,
550-5.7.1 this message has been blocked. Please review
550 5.7.1 RFC 5322 specifications for more information.

php dot net at schrecktech dot com

18 years ago


When sending MIME email make sure you follow the documentation with the "70" characters per line...you may end up with missing characters...and that is really hard to track down...

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Philips hd8828 ошибка 5
  • Photoshop ошибка при открытии файла
  • Php json decode обработка ошибок
  • Php ini включить вывод ошибок
  • Philips hd3039 00 ошибка е4

  • Добавить комментарий

    ;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: