This is about the best you can do:
if (!mail(...)) {
// Reschedule for later try or panic appropriately!
}
http://php.net/manual/en/function.mail.php
mail()returnsTRUEif the mail was successfully accepted for delivery,FALSEotherwise.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.
If you need to suppress warnings, you can use:
if (!@mail(...))
Be careful though about using the @ operator without appropriate checks as to whether something succeed or not.
If mail() errors are not suppressible (weird, but can’t test it right now), you could:
a) turn off errors temporarily:
$errLevel = error_reporting(E_ALL ^ E_NOTICE); // suppress NOTICEs
mail(...);
error_reporting($errLevel); // restore old error levels
b) use a different mailer, as suggested by fire and Mike.
If mail() turns out to be too flaky and inflexible, I’d look into b). Turning off errors is making debugging harder and is generally ungood.
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 указан неправильно
Ну по чему? 
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:WEBProjectsinetpubwwwrootPHPDevelopingRegform2.phtml on line 73
То есть какая-то же диагностика есть??
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: [email protected]@aaa.com
Test!!!
");
$read = fread($mailer, 2096);
echo $read;
pclose ($mailer);
(PHP 4, PHP 5, PHP 7, PHP 
mail — Send mail
Description
mail(
string $to,
string $subject,
string $message,
array|string $additional_headers = [],
string $additional_params = «»
): bool
Parameters
-
to -
Receiver, or receivers of the mail.
The formatting of this string must comply with
» RFC 2822. Some examples are:- user@example.com
- user@example.com, anotheruser@example.com
- User <user@example.com>
- User <user@example.com>, Another User <anotheruser@example.com>
-
subject -
Subject of the email to be sent.
-
message -
Message to be sent.
Each line should be separated with a CRLF (rn). Lines should not be
larger than 70 characters.Caution
(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.
<?php
$text = str_replace("n.", "n..", $text);
?>
-
additional_headers(optional) -
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 (rn).
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_headersdid 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
aFromheader. This can be set with the
additional_headersparameter, or a default
can be set in php.ini.Failing to do this will result in an error
message similar toWarning: mail(): "sendmail_from" not.
set in php.ini or custom "From:" header missing
TheFromheader sets also
Return-Pathwhen 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. -
additional_params(optional) -
The
additional_paramsparameter
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_pathconfiguration setting. For example,
this can be used to set the envelope sender address when using
sendmail with the-fsendmail 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 acceptsan array. |
Examples
Example #1 Sending mail.
Using mail() to send a simple email:
<?php
// The message
$message = "Line 1rnLine 2rnLine 3";// In case any of our lines are larger than 70 characters, we should use wordwrap()
$message = wordwrap($message, 70, "rn");// 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' . "rn" .
'Reply-To: webmaster@example.com' . "rn" .
'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.
<?php
mail('nobody@example.com', 'the subject', 'the message', null,
'-fwebmaster@example.com');
?>
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';// Message
$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>
';// 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("rn", $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
MTAis 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
MTAin the first place, but are parsed by PHP.As such, the
toparameter 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.
Note:
The following RFCs may be useful:
» RFC 1896,
» RFC 2045,
» RFC 2046,
» RFC 2047,
» RFC 2048,
» RFC 2049, and
» RFC 2822.
See Also
- mb_send_mail() — Send encoded mail
- imap_mail() — Send an email message
- » PEAR::Mail
- » PEAR::Mail_Mime
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...
I am sending mails from php mail() : and I want to receive a failed message if sending is failed to the destinatio .
$to = 'itsdfdsf@7sisters.in';
$email_from = "info@7sisters.in";
$full_name = 'XXXX';
$from_mail = $full_name.'<'.$email_from.'>';
$subject = "testing sender name";
$message = "";
$message .= '
<p><strong>This is only a test mail. Please do not reply.</strong><br />
';
$from = $from_mail;
//$headers = "" .
// "Reply-To:" . $from . "rn" .
// "X-Mailer: PHP/" . phpversion();
$headers = "From:" . $from_mail . "rn" .
"Reply-To:" . $from_mail . "rn" .
"X-Mailer: PHP/" . phpversion();
$headers .= 'MIME-Version: 1.0' . "rn";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "rn";
if(!mail($to,$subject,$message,$headers))
{
echo 'failed !!';
}
But although $to mail does no exist,it is not showing failed !!
asked Dec 5, 2011 at 11:52
4
The mail method is just sending the mail out. If it does not receive any errors (e.g. by not finding the server etc), it will return succesfull. You will not be able to know if the mail actually landed in the inbox of the recipient unless you create some code around bounced emails etc.
answered Dec 5, 2011 at 11:57
Bas SlagterBas Slagter
9,8117 gold badges47 silver badges78 bronze badges
I think what you want is to check for a real email not only a valid formatted email. So I would suggest you to have a look at this blog
Martin.
10.5k3 gold badges42 silver badges68 bronze badges
answered Dec 5, 2011 at 11:59
SERPROSERPRO
10k8 gold badges46 silver badges63 bronze badges
0
check the return from of mail
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.
Although the fact it is returning true probably means that your mail program is accepting the message but then failing when it tries to send to no one…
You should run the $to through a validator to check its a valid address and then throw an error if its not, don’t rely on mail() to filter out things which you already know are wrong, or can check against easily.
—UPDATE
Then check out @SeRPRo , but what your trying to do is hard work to test programatically — its far easier and more reliable to send an e-mail which requires the user to click a link to verify that it’s real than try querying SMTP servers which all have different behaviour (read: are broken to different degrees). Also note that your intended behaviour (code wise) is hard to differentiate from a spammers so don’t be surprised to find it difficult going if you avoid the verification e-mail route.
answered Dec 5, 2011 at 11:57
James ButlerJames Butler
3,8541 gold badge26 silver badges38 bronze badges
1
But although $to mail does no exist,it is not showing failed !!
actually the fact that mail is being delivered to SMTP server, doesn’t mean it will be delivered to the end user. There’s no easy way in PHP to check whether it’s delivered.
answered Dec 5, 2011 at 11:55
Martin.Martin.
10.5k3 gold badges42 silver badges68 bronze badges
You could CC yourself as a way of testing that it is leaving the outbox.
answered Dec 5, 2011 at 11:59
abcde123483abcde123483
3,8754 gold badges41 silver badges41 bronze badges
1
In my case it helped to set the return-path via the commandline parameter «-f», which can be passed in the $additional_parameters parameter of mail(). so i call
mail($to, $subject, $message, $headers, "-f address.where.i.want.the.bounces@xy.com");
… according to some comments on http://www.php.net/manual/en/function.mail.php hosting-inviroments react different and have different restrictions (address might need to be registered in the same hosting-account, or be on the same domain, the same as the «From:» in the heade … and so on)
The page where I got the bounces to be received (with non of the mentioned restrictions, as it seems) is hosted at Domainfactory http://www.df.eu
answered May 23, 2012 at 14:06
johjohjohjoh
4644 silver badges18 bronze badges
Use phpmailer to send email and set $mail->AddCustomHeader(‘Return-path:bounce@mail.com’);
This will send bounce email at bounce@mail.com if recipient mail id does not exist or recipient does not receive email by any other case.
answered Apr 2, 2013 at 5:24
Я пытаюсь использовать PHPMailer для небольшого проекта, но я немного запутался в обработке ошибок с помощью этого программного обеспечения. Надеюсь, что у кого-то есть опыт. Когда я настроил электронную почту, и я использую:
Который работает отлично, более или менее. Проблема в том, что есть ошибка, PHPMailer также, похоже, повторяет ошибку, поэтому, если есть проблема, она просто отправляет эту информацию непосредственно в браузер, по сути, нарушая любую обработку ошибок, которую я пытаюсь сделать.
Есть ли способ заставить замолчать эти сообщения? Он не бросает исключение, просто распечатывает ошибку, которая в моем тестовом примере:
Он должен быть ошибкой, но он должен находиться в $ mail-> ErrorInfo; не будучи эхо-программным обеспечением.
PHPMAiler использует Исключения. Попробуйте принять следующий код :
require_once '../class.phpmailer.php'; $mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch try { $mail->AddReplyTo('name@yourdomain.com', 'First Last'); $mail->AddAddress('whoto@otherdomain.com', 'John Doe'); $mail->SetFrom('name@yourdomain.com', 'First Last'); $mail->AddReplyTo('name@yourdomain.com', 'First Last'); $mail->Subject = 'PHPMailer Test Subject via mail(), advanced'; $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically $mail->MsgHTML(file_get_contents('contents.html')); $mail->AddAttachment('images/phpmailer.gif'); // attachment $mail->AddAttachment('images/phpmailer_mini.gif'); // attachment $mail->Send(); echo "Message Sent OKn"; } catch (phpmailerException $e) { echo $e->errorMessage(); //Pretty error messages from PHPMailer } catch (Exception $e) { echo $e->getMessage(); //Boring error messages from anything else! }
Просто нужно было это исправить. Вышеприведенные ответы, похоже, не учитывают $mail->SMTPDebug = 0; вариант. Возможно, он не был доступен, когда вопрос был задан первым.
Если вы получили свой код с сайта PHPMail, по умолчанию будет $mail->SMTPDebug = 2; // enables SMTP debug information (for testing) $mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
https://github.com/Synchro/PHPMailer/blob/master/examples/test_smtp_gmail_advanced.php
Установите значение 0 для подавления ошибок и отредактируйте часть «catch» вашего кода, как описано выше.
Пожалуйста, обратите внимание!!! Вы должны использовать следующий формат при создании PHPMailer!
$mail = new PHPMailer(true);
Если вы не делаете исключений, игнорируются, и единственное, что вы получите, – это эхо от рутины! Я знаю, что это хорошо после того, как это было создано, но, надеюсь, это поможет кому-то.
Вы можете получить дополнительную информацию об ошибке с помощью метода $mail->ErrorInfo . Например:
if(!$mail->send()) { echo 'Message could not be sent.'; echo 'Mailer Error: ' . $mail->ErrorInfo; } else { echo 'Message has been sent'; }
Это альтернатива модели исключения, которую нужно активировать с помощью new PHPMailer(true) . Но если можно использовать модель исключения, используйте ее как @Phil Rykoff.
Это происходит с главной страницы PHPMailer по github https://github.com/PHPMailer/PHPMailer .
Мы написали класс-оболочку, который захватывает буфер и преобразует печатный результат в исключение. это позволяет нам обновлять файл phpmailer, не задумываясь о том, чтобы комментировать события echo при каждом обновлении.
Класс-оболочка имеет методы:
public function AddAddress($email, $name = null) { ob_start(); parent::AddAddress($email, $name); $error = ob_get_contents(); ob_end_clean(); if( !empty($error) ) { throw new Exception($error); } }
Даже если вы используете исключения, он все равно выводит ошибки.
Вы должны установить $ MailerDebug в False, который должен выглядеть так
$mail = new PHPMailer(); $mail->MailerDebug = false;
Это прекрасно работает
use try { as above use Catch as above but comment out the echo lines } catch (phpmailerException $e) { //echo $e->errorMessage(); //Pretty error messages from PHPMailer } catch (Exception $e) { //echo $e->getMessage(); //Boring error messages from anything else! }
Затем добавьте это
if ($e) { //enter yor error message or redirect the user } else { //do something else }
В PHPMailer.php есть строки, как показано ниже:
echo $e->getMessage()
Просто прокомментируйте эти строки, и вам будет хорошо идти.
$mail = new PHPMailer(); $mail->AddAddress($email); $mail->From = $from; $mail->Subject = $subject; $mail->Body = $body; if($mail->Send()){ echo 'Email Successfully Sent!'; }else{ echo 'Email Sending Failed!'; }
самый простой способ обработки электронной почты успешно или неудачно …


