- PHP mail() Function
- Syntax
- Parameter Values
- Technical Details
- More Examples
- Отправка почты средствами PHP
- php mail
- Introduction to the PHP mail() function
- PHP mail() function examples
- 1) Using the PHP mail() function to send a plain text email example
- 2) Using the PHP mail() function to send a mail with extra headers example
- 3) Using the PHP mail() function to send HTML email example
- Summary
- Sending Nice HTML Email with PHP
PHP mail() Function
The mail() function allows you to send emails directly from a script.
Syntax
Parameter Values
Parameter | Description |
---|---|
to | Required. Specifies the receiver / receivers of the email |
subject | Required. Specifies the subject of the email. Note: This parameter cannot contain any newline characters |
message | Required. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters. |
Windows note: If a full stop is found on the beginning of a line in the message, it might be removed. To solve this problem, replace the full stop with a double dot:
$txt = str_replace(«\n.», «\n..», $txt);
?>
Note: When sending an email, it must contain a From header. This can be set with this parameter or in the php.ini file.
Technical Details
Return Value: | Returns the hash value of the address parameter, or FALSE on failure. Note: Keep in mind that even if the email was accepted for delivery, it does NOT mean the email is actually sent and received! |
---|---|
PHP Version: | 4+ |
PHP Changelog: | PHP 7.2: The headers parameter also accepts an array PHP 5.4: Added header injection protection for the headers parameter. PHP 4.3.0: (Windows only) All custom headers (like From, Cc, Bcc and Date) are supported, and are not case-sensitive. PHP 4.2.3: The parameter parameter is disabled in safe mode PHP 4.0.5: The parameter parameter was added |
More Examples
Send an email with extra headers:
$to = «somebody@example.com»;
$subject = «My subject»;
$txt = «Hello world!»;
$headers = «From: webmaster@example.com» . «\r\n» .
«CC: somebodyelse@example.com»;
?php
$to = «somebody@example.com, somebodyelse@example.com»;
$subject = «HTML email»;
?php
$message = »
This email contains HTML Tags!
Firstname | Lastname |
---|---|
John | Doe |
«;
// Always set content-type when sending HTML email
$headers = «MIME-Version: 1.0» . «\r\n»;
$headers .= «Content-type:text/html;charset=UTF-8» . «\r\n»;
// More headers
$headers .= ‘From: ‘ . «\r\n»;
$headers .= ‘Cc: myboss@example.com’ . «\r\n»;
Отправка почты средствами PHP
Работая над проектом, мне пришлось создать специфичную «анкету соискателя» в котором надо была отправлять всю анкету на указные за ране e-mail адрес, и я сразу же вспомнил про PHP функцию mail().
bool mail ( string to, string subject, string message [, string additional_headers [, string additional_parameters]])
- E-mail получателя
- Заголовок письма
- Текст письма
- Дополнительные заголовки письма
- Дополнительные параметры командной строки
- true, если письмо было принято к доставке
- false, в противном случае.
Простейший пример
Перейдем к более сложному примеру
Текст письма 1-ая строчка 2-ая строчка '; $headers = "Content-type: text/html; charset=windows-1251 \r\n"; $headers . ; $headers .= "Reply-To: reply-to@example.com\r\n"; mail($to, $subject, $message, $headers); ?>
В начале мы определяем кому адресовано письмо, за это отвечает переменная &to, если же получателей несколько человек, то записываем через запятую адреса эл. почты.
Переменные $subject и $message, не буду описывать, это и так понятно.
- В первой строчке ми определяем ты отправляемого письма-HTML и кодировку windows-1251.
- В 2-ом мы указываем от кого пришло письмо.
- В 3-ем указываем e-mail адрес, для ответа на письмо.
А теперь самое интересное отправка письма c вложением (attachment)
$subject = "тема письма"; $message ="Текст сообщения"; // текст сообщения, здесь вы можете вставлять таблицы, рисунки, заголовки, оформление цветом и т.п. $filename = "file.doc"; // название файла $filepath = "files/file.doc"; // месторасположение файла //исьмо с вложением состоит из нескольких частей, которые разделяются разделителем $boundary = "--".md5(uniqid(time())); // генерируем разделитель $mailheaders = "MIME-Version: 1.0;\r\n"; $mailheaders .="Content-Type: multipart/mixed; boundary=\"$boundary\"\r\n"; // разделитель указывается в заголовке в параметре boundary $mailheaders . ; $mailheaders .= "Reply-To: $user_email\r\n"; $multipart = "--$boundary\r\n"; $multipart .= "Content-Type: text/html; charset=windows-1251\r\n"; $multipart .= "Content-Transfer-Encoding: base64\r\n"; $multipart .= \r\n; $multipart .= chunk_split(base64_encode(iconv("utf8", "windows-1251", $message))); // первая часть само сообщение // Закачиваем файл $fp = fopen($filepath,"r"); if (!$fp) < print "Не удается открыть файл22"; exit(); >$file = fread($fp, filesize($filepath)); fclose($fp); // чтение файла $message_part = "\r\n--$boundary\r\n"; $message_part .= "Content-Type: application/octet-stream; name=\"$filename\"\r\n"; $message_part .= "Content-Transfer-Encoding: base64\r\n"; $message_part .= "Content-Disposition: attachment; filename=\"$filename\"\r\n"; $message_part .= \r\n; $message_part .= chunk_split(base64_encode($file)); $message_part .= "\r\n--$boundary--\r\n"; // второй частью прикрепляем файл, можно прикрепить два и более файла $multipart .= $message_part; mail($to,$subject,$multipart,$mailheaders); // отправляем письмо //удаляем файлы через 60 сек. if (time_nanosleep(5, 0)) < unlink($filepath); >// удаление файла
php mail
Summary: in this tutorial, you’ll learn how to send email using the PHP mail() function.
Introduction to the PHP mail() function
To send mail, you use the mail() function.
On Linux or Unix systems, you can configure the mail() function to use the sednmail or Qmail program to send messages.
On Windows, you can install the sendmail and set the sendmail_path in php.ini file to point at the executable file.
However, it’s more convenient to set the SMTP server with a port and sendmail_from in the php.ini file on Windows like this:
[mail function] SMTP=smtp.phptutorial.net smtp_port=25 sendmail_from=contact@phptutorial.net
Code language: PHP (php)
If the SMTP server requires authentication, you can add the following lines for the account to authenticate:
auth_username=smtp_user auth_password=smpt_password
Code language: PHP (php)
Once the configuration is ready, you need to restart the webserver.
The following illustrates the syntax of the mail() function:
mail( string $to, string $subject, string $message, array|string $additional_headers = [], string $additional_params = "" ): bool
Code language: PHP (php)
The mail() function has the following parameters:
- $to is the receiver of the email
- $subject is the email subject.
- $message is the email message. It can be plain text or HTML. If $message is plain text, you use a CRLF (\r\n) to separate lines. And each line should not exceed 70 characters.
- $additional_headers is a string or an array inserted at the email’s header. It includes from, cc, bcc… If the header comes from an untrusted source, you should always sanitize it for security purposes.
- $additional_params allows you to pass additional flags as the command-line options to the sendmail program.
The mail() function returns true if the mail was accepted for delivery. It doesn’t mean that the mail is successfully reached the intended receiver. If an error occurred, the mail() function return false .
PHP mail() function examples
Let’s take some examples of using the PHP mail() function.
1) Using the PHP mail() function to send a plain text email example
The following example uses the mail() function to send a simple email:
$subject = 'This is a test email'; $message = wordwrap($message, 70, "\r\n"); mail('contact@phptutorial.net', $subject, $message);
Code language: PHP (php)
In this example, we use the wordwrap() function to ensure that the lines of the message won’t exceed 70 characters.
2) Using the PHP mail() function to send a mail with extra headers example
The following example uses the mail() function to send a mail with additional headers like From, Reply-To, and X-Mailer:
$to = 'contact@phptutorial.net'; $subject = 'This is a test email'; $message = 'Hi there'; $headers[] = 'From: john.doe@example.com'; $headers[] = 'Reply-To: john.doe@example.com'; $headers[] = 'X-Mailer: PHP/' . phpversion(); mail($to, $subject, $message, implode('\r\n', $headers));
Code language: PHP (php)
If you use PHP 7.2 or later, you can pass the headers as an array like this:
$to = 'contact@phptutorial.net'; $subject = 'This is a test email'; $message = 'Hi there'; $headers = [ 'From' => 'john.doe@example.com', 'Reply-To' => 'john.doe@example.com', 'X-Mailer' => 'PHP/' . phpversion() ]; mail($to, $subject, $message, $headers);
Code language: PHP (php)
3) Using the PHP mail() function to send HTML email example
To send HTML mail, you need to set the Content-type for the header like this:
$to = 'contact@phptutorial.net'; $subject = 'This is a test email'; $message = ' This is HTML mail
'; $headers = [ 'MIME-Version' => '1.0', 'Content-type' => 'text/html; charset=utf8', 'From' => 'john.doe@example.com', 'Reply-To' => 'john.doe@example.com', 'X-Mailer' => 'PHP/' . phpversion() ]; if (mail($to, $subject, $message, $headers)) < echo 'email was sent.'; > else < echo 'An error occurred.'; >
Code language: PHP (php)
Summary
Sending Nice HTML Email with PHP
This is going to be a continuation of the Website Change Request Form demo we’ve been using around here for a while. If you need to catch up, first I talked about it, then I built it, then I screencasted it, then I secured it. Throughout all of this, the end result has been a boring text-only email that gets sent to a single email address. We’re going to improve that output, and make the email into a nicer looking HTML-formatted email.
It’s Not Much Different Than Text Email
mail($to, $subject, $message, $headers);
The last parameter, the headers, are optional for the function but required for sending HTML email, as this is where we are able to pass along the Content-Type declaration telling email clients to parse the email as HTML. In fact, the headers area gives us the opportunity to do lots of important email functions. This is where we can set the From: and Reply To: settings if need be, as well as CC and BCC other recipients (Hey, a checkbox for CC’ing yourself would be a cool feature to add!). Here is the code used for the new and improved HTML-Sendin’ Website Change Request Form:
$to = '[email protected]'; $subject = 'Website Change Request'; $headers = "From: " . strip_tags($_POST['req-email']) . "\r\n"; $headers .= "Reply-To: ". strip_tags($_POST['req-email']) . "\r\n"; $headers . /cdn-cgi/l/email-protection" data-cfemail="f3808680929db3968b929e839f96dd909c9e">[email protected]\r\n"; $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
The message parameter (a big string we pass to the mail function with the body of our email), can now have HTML tags in it. For example:
$message = ''; $message .= 'Hello, World!
'; $message .= '';
$message = ''; $message .= ''; $message .= ''; $message .= "Name: " . strip_tags($_POST['req-name']) . " "; $message .= "Email: " . strip_tags($_POST['req-email']) . " "; $message .= "Type of Change: " . strip_tags($_POST['typeOfChange']) . " "; $message .= "Urgency: " . strip_tags($_POST['urgency']) . " "; $message .= "URL To Change (main): " . $_POST['URL-main'] . " "; $addURLS = $_POST['addURLS']; if (($addURLS) != '') < $message .= "URL To Change (additional): " . strip_tags($addURLS) . " "; > $curText = htmlentities($_POST['curText']); if (($curText) != '') < $message .= "CURRENT Content: " . $curText . " "; > $message .= "NEW Content: " . htmlentities($_POST['newText']) . " "; $message .= "
"; $message .= "";
I think that looks A LOT nicer. And since this email is (theoretically) coming directly to you, isn’t it nice to know that it will be formatted to be easy on the eyes?
Some people just absolutely hate HTML email. For one, it can be a security risk as it’s possible to run JavaScript in them in some email clients which can be problematic. HTML emails also have a habit of being more easily caught in Spam filters. I think it’s less of a concern here as this email is essentially being created BY you FOR you.
I updated the demo and download to use the new HTML email format. View Demo Download Files There is likely to be another one or two demos on this form yet to come. I would at least like to do one on writing the data to a database before sending the email. Email can be such a fragile thing, that saving the data to a DB first is surely a smart move.