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('[email protected]', '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Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
Референца за `function.mail.php` со подобрена типографија и навигација.
(PHP 4, PHP 5, PHP 7, PHP 8)
mail — Испрати е-пошта
= NULL
string
$to,string
$subject,string
$message,array|string
$additional_headers = [],string
$additional_params = ""): bool
Испраќа е-пошта.
Параметри
to-
Примач или примачи на е-поштата.
Форматирањето на овој стринг мора да биде во согласност со » RFC 2822. Некои примери се:
- [email protected]
- [email protected], [email protected]
- Корисник
- Корисник
, Друг Корисник
subject-
Предмет на е-поштата што треба да се испрати.
Безбедност: стандардниот сет на знациПредметот мора да ги задоволи Подвлекувањата се претвораат во празни места како што е специфицирано од.
message-
Порака што треба да се испрати.
Секој ред треба да биде одделен со CRLF (\r\n). Редовите не треба да бидат поголеми од 70 знаци.
Безбедност: стандардниот сет на знаци(Само за Windows) Кога PHP комуницира директно со SMTP сервер, ако точка се најде на почетокот на редот, таа се отстранува. За да се спротивстави на ова, заменете ги овие појави со двојна точка.
<?php
$text = str_replace("\n.", "\n..", $text);
?> additional_headers(опционално)-
Низа or array што треба да се вметне на крајот од заглавието на е-поштата.
Ова обично се користи за додавање дополнителни заглавија (Од, Копија и Скриена копија). Повеќе дополнителни заглавија треба да бидат одделени со CRLF (\r\n). Ако надворешни податоци се користат за составување на ова заглавие, податоците треба да бидат санирани за да не може да се инјектираат несакани заглавија.
Ако еден array се предава, неговите клучеви се имињата на заглавјата, а неговите вредности се соодветните вредности на заглавјата.
Забелешка:
При испраќање е-пошта, е-поштата must содржи
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опција sendmail.се избегнува од escapeshellcmd() внатрешно за да се спречи извршување на команди. escapeshellcmd() спречува извршување на команди, но дозволува додавање дополнителни параметри. Од безбедносни причини, се препорачува корисникот да го санира овој параметар за да избегне додавање непосакувани параметри во командната линија.
е предмет на безбедноста вградена во повеќето серверски системи во однос на дозволите на основа на датотека и директориум. Ова ви овозможува да контролирате кои датотеки во датотечниот систем може да се читаат. Треба да се внимава со сите датотеки што се читливи од сите за да се осигурате дека се безбедни за читање од сите корисници кои имаат пристап до тој датотечен систем. escapeshellcmd() се применува автоматски, некои знаци што се дозволени како адреси на е-пошта од интернет RFC не можат да се користат. mail() не може да дозволи такви знаци, така што во програми каде што е потребно користење на такви знаци, се препорачуваат алтернативни начини за испраќање е-пошта (како што е користење на рамка или библиотека).
Корисникот под кој работи веб-серверот треба да се додаде како доверлив корисник во конфигурацијата на sendmail за да се спречи додавање на заглавие 'X-Warning' на пораката кога е-испраќачот на пликот (-f) е поставен со овој метод. За корисниците на sendmail, оваа датотека е /etc/mail/trusted-users.
Вратени вредности
Патеката до PHP скриптата што треба да се провери. true ако е-поштата успешно е прифатена за испорака, false otherwise.
Важно е да се напомене дека само затоа што е-поштата е прифатена за испорака, тоа НЕ значи дека е-поштата навистина ќе стигне до наменетата дестинација.
Примери
Пример #1 Испраќање е-пошта.
Пронајдете и отворете ја конфигурациската датотека на Apache. Стандардно, локацијата е како што следува: mail() за испраќање едноставна е-пошта:
<?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('[email protected]', 'My Subject', $message);
?>Пример #2 Испраќање е-пошта со дополнителни заглавија.
Додавање основни заглавија, кои му кажуваат на MUA адресите Од и Одговор до:
<?php
$to = '[email protected]';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: [email protected]' . "\r\n" .
'Reply-To: [email protected]' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
?>Пример #3 Испраќање е-пошта со дополнителни заглавија како array
Овој пример испраќа иста е-пошта како примерот веднаш погоре, но ги поминува дополнителните заглавија како низа (достапно од PHP 7.2.0).
<?php
$to = '[email protected]';
$subject = 'the subject';
$message = 'hello';
$headers = array(
'From' => '[email protected]',
'Reply-To' => '[email protected]',
'X-Mailer' => 'PHP/' . phpversion()
);
mail($to, $subject, $message, $headers);
?>Пример #4 Испраќање е-пошта со дополнителен параметар од командната линија.
На additional_params параметарот може да се користи за поминување на дополнителен параметар до програмата конфигурирана да се користи при испраќање е-пошта користејќи го sendmail_path.
<?php
mail('[email protected]', 'the subject', 'the message', null,
'[email protected]');
?>Пример #5 Испраќање HTML е-пошта
Можно е да се испраќа и HTML е-пошта со mail().
<?php
// Multiple recipients
$to = '[email protected], [email protected]'; // 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 <[email protected]>, Kelly <[email protected]>';
$headers[] = 'From: Birthday Reminder <[email protected]>';
$headers[] = 'Cc: [email protected]';
$headers[] = 'Bcc: [email protected]';
// Mail it
mail($to, $subject, $message, implode("\r\n", $headers));
?>
Забелешка:
Ако имате намера да испраќате HTML или други сложени е-пошта, се препорачува да го користите пакетот PEAR » PEAR::Mail_Mime.
Белешки
Забелешка:
SMTP имплементацијата (само за Windows) на mail() се разликува на многу начини од sendmail имплементацијата. Прво, не користи локален бинарен за составување пораки, туку работи само на директни приклучоци, што значи дека
MTAе потребно слушање на мрежен приклучок (што може да биде на локалниот компјутер или на оддалечена машина).Второ, прилагодените заглавја како
From:,Cc:,Bcc:andDate:are not интерпретирани одMTAна прво место, но се анализираат од PHP.Како таков,
toпараметарот не треба да биде адреса во форма "Something <[email protected]>". Командата mail можеби нема правилно да ја анализира при комуникација со MTA.
Забелешка:
Вреди да се напомене дека mail() функцијата не е погодна за поголеми количини на е-пошта во циклус. Оваа функција отвора и затвора SMTP приклучок за секоја е-пошта, што не е многу ефикасно.
За испраќање големи количини на е-пошта, видете » PEAR::MailПрепорачаниот начин за избегнување на SQL инјекција е со врзување на сите податоци преку подготвени изрази. Користењето на параметризирани прашања не е доволно за целосно избегнување на SQL инјекција, но тоа е најлесниот и најбезбедниот начин за обезбедување влез во SQL изразите. Сите динамични литерали на податоци во » PEAR::Mail_Queue packages.
Забелешка:
Следните RFC може да бидат корисни: » RFC 1896, = "\r\n", » RFC 2046, Подвлекувањата се претвораат во празни места како што е специфицирано од, » RFC 2048, » RFC 2049Препорачаниот начин за избегнување на SQL инјекција е со врзување на сите податоци преку подготвени изрази. Користењето на параметризирани прашања не е доволно за целосно избегнување на SQL инјекција, но тоа е најлесниот и најбезбедниот начин за обезбедување влез во SQL изразите. Сите динамични литерали на податоци во » RFC 2822.
Види Исто така
- mb_send_mail() - Испрати кодирана е-пошта
- imap_mail() - Испрати е-пошта порака
- » PEAR::Mail
- » PEAR::Mail_Mime
Белешки од корисници SPL Итератори
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') . '?= <[email protected]>';
?>
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-3ciiSecurity 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.Sending mail using XAMPP server
I encountered numerous issues while attempting to send emails using the XAMPP server. However, I eventually found the correct method to accomplish it.
Configuring PHP's mail functionality to work with Gmail's SMTP server involves editing the `php.ini` and `sendmail.ini` configuration files. Below are the formal steps for setting up PHP to send emails through Gmail's SMTP server using XAMPP:
Configuring php.ini:
1. Open `php.ini` in an editor:
Open the `php.ini` configuration file in your preferred text editor.
2. Locate the mail function:
Use the search function (Ctrl + F) to find the section related to the mail function within the `php.ini` file.
3. Update mail function settings:
Copy and paste the following configuration parameters into the mail function section. Comment out or disable all other settings related to mail.
php.ini code to be edited:
SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = write_sendmail.exe_path
4. Save the changes:
Save the `php.ini` file after applying the modifications.
Configuring sendmail.ini (in XAMPP folder):
1. Open `sendmail.ini` in XAMPP folder:
Locate and open the `sendmail.ini` configuration file within the XAMPP directory.
2. Adjust SMTP settings:
Insert the following content into the `sendmail.ini` file, marking other configurations as comments:
sendmail.ini code :
smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=app_password_after_enabling_two_factor_authentication_for_your_mail_id
[email protected]
3. Save the changes:
Save the `sendmail.ini` file after inserting the specified configurations.
These steps configure PHP to utilize Gmail's SMTP server for sending emails. Ensure that the modifications are saved and that the necessary XAMPP services are restarted for the changes to take effect.
Please note that using hardcoded passwords in configuration files poses a security risk. Storing passwords directly in plain text files should be avoided in production environments. Consider using environment variables or secure credential management systems for better security practices.
Code for sending mail-:
<?php
$subject = "Mail for checking";
$msg = "Hey! Let us play with PHP.";
$receiver = "[email protected]";
mail($receiver, $subject, $msg);
?>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.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 = '[email protected]';
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);
}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 windowsMake sure you enclose \r\n in double quotes (not single quotes!) so that PHP can translate that into the correct linefeed codeIt 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.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.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...* 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));
}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);
?>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 [email protected]" option, my key was not accepted. However it was accepted when I used "-f [email protected]".
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...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);
}
?>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.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.