Окончательный message html. Как отправлять текстовые сообщения с помощью PHP. Получатель: событие onmessage

// Открываем файл для чтения в бинарном формате $file=fopen("file.zip", "rb"); // Считываем его в строку $str_file $str_file=fread($file,filesize("file.zip")); // Преобразуем эту строку в base64-формат $str_file=base64_encode($str_file);

Теперь переменную $str_file , которая содержит файл, можно вставлять в письмо.

Для окончательного закрепления материала напишем функцию, которая отправляет письмо в HTML-формате по указанному адресату с прикрепленным файлом:

/* $to - адрес получателя письма $from_mail - адрес отправителя письма $from_name - имя отправителя письма $subject - тема письма $message - само сообщение в HTML-формате $file_name - путь к файлу, который надо прикрепить к письму (это может быть имя файла, выбранного в поле ) */ function sendMail($to,$from_mail,$from_name,$subject,$message,$file_name) { $bound="spravkaweb-1234"; $header="From: "$from_name" n"; $header.="To: $ton"; $header.="Subject: $subjectn"; $header.="Mime-Version: 1.0n"; $header.="Content-Type: multipart/mixed; boundary="$bound""; $body="nn--$boundn"; $body.="Content-type: text/html; charset="windows-1251"\n"; $body.="Content-Transfer-Encoding: quoted-printablenn"; $body.="$message"; $file=fopen($file_name,"rb"); $body.="nn--$boundn"; $body.="Content-Type: application/octet-stream;"; $body.="name=".basename($file_name)."\n"; $body.="Content-Transfer-Encoding:base64n"; $body.="Content-Disposition:attachmentnn"; $body.=base64_encode(fread($file,filesize($file_name)))."n"; $body.="$bound--nn"; if(mail($to, $subject, $body, $header)) { echo " Письмо было успешно отправлено! "; } else { echo " Сообщение не отправлено! "; }; };

HTTP is based on the client-server architecture model and a stateless request/response protocol that operates by exchanging messages across a reliable TCP/IP connection.

An HTTP "client" is a program (Web browser or any other client) that establishes a connection to a server for the purpose of sending one or more HTTP request messages. An HTTP "server" is a program (generally a web server like Apache Web Server or Internet Information Services IIS, etc.) that accepts connections in order to serve HTTP requests by sending HTTP response messages.

HTTP makes use of the Uniform Resource Identifier (URI) to identify a given resource and to establish a connection. Once the connection is established, HTTP messages are passed in a format similar to that used by the Internet mail and the Multipurpose Internet Mail Extensions (MIME) . These messages include requests from client to server and responses from server to client which will have the following format:

HTTP-message = | ; HTTP/1.1 messages

HTTP requests and HTTP responses use a generic message format of RFC 822 for transferring the required data. This generic message format consists of the following four items.

  • A Start-line
  • Zero or more header fields followed by CRLF
  • An empty line (i.e., a line with nothing preceding the CRLF) indicating the end of the header fields
  • Optionally a message-body

In the following sections, we will explain each of the entities used in an HTTP message.

Message Start-Line

A start-line will have the following generic syntax:

Start-line = Request-Line | Status-Line

We will discuss Request-Line and Status-Line while discussing HTTP Request and HTTP Response messages respectively. For now, let"s see the examples of start line in case of request and response:

GET /hello.htm HTTP/1.1 (This is Request-Line sent by the client) HTTP/1.1 200 OK (This is Status-Line sent by the server)

Header Fields

HTTP header fields provide required information about the request or response, or about the object sent in the message body. There are four types of HTTP message headers:

    General-header: These header fields have general applicability for both request and response messages.

    Request-header: These header fields have applicability only for request messages.

    Response-header: These header fields have applicability only for response messages.

    Entity-header: These header fields define meta information about the entity-body or, if no body is present, about the resource identified by the request.

All the above mentioned headers follow the same generic format and each of the header field consists of a name followed by a colon (: ) and the field value as follows:

Message-header = field-name ":" [ field-value ]

Following are the examples of various header fields:

User-Agent: curl/7.16.3 libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3 Host: www.example.com Accept-Language: en, mi Date: Mon, 27 Jul 2009 12:28:53 GMT Server: Apache Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT ETag: "34aa387-d-1568eb00" Accept-Ranges: bytes Content-Length: 51 Vary: Accept-Encoding Content-Type: text/plain

Message Body

The message body part is optional for an HTTP message but if it is available, then it is used to carry the entity-body associated with the request or response. If entity body is associated, then usually Content-Type and Content-Length headers lines specify the nature of the body associated.

Содержит только текст (малый вес сообщения)

$name = "Пётр Петрович"; // необязательная переменная в качестве примера вставки в сообщение

$subject = "Тема сообщения"; //тема сообщения
$message = "Здравствуйте,".$name."!\n
Просто спросить как дела!\n
С уважением, Иван Иванович";//содержание сообщения
mail($email, $subject, $message, "From: [email protected]\nReply-To: [email protected]\nContent-type:text/plain; Charset=utf-8\r\n"); //отправляем сообщение
?>

2. Отправка письма mail php Тип text/html

Могут содержать графические html-элементы, сслыки и тп.
Больше объём передаваемой информации

// отправка нескольким адресатам
$to = "[email protected]" . ", "; // кому отправляем
$to .= "[email protected]" . ", "; // Внимание! Так пишем второй и тд адреса
// не забываем запятую. Даже в последнем контакте лишней не будет
// Для начинающих! $to .= точка в этом случае для Дописывания в переменную

// устанавливаем тип сообщения Content-type, если хотим
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=utf-8 \r\n";

// дополнительные данные
$headers .= "From: yournick \r\n"; // от кого
$headers .= "Cc: [email protected]" . "\r\n"; // копия сообщения на этот адрес
$headers .= "Bcc: [email protected]\r\n"; // скрытая копия сообщения на этот
mail($to, $subject, $message, $headers);
?>

3. Как использовать в письме CSS?

Тут я хочу сразу немного огорчить Вас - CSS в привычном для Вас виде не стоит использовать. Mail, Yandex, Google, Outlook - выкидывают стили из писем. Однако, есть выход.

Выполним несколько условий:
1) Надеюсь не нужно пояснять, что используем Content-type: text/html

2) Вспоминаем, что такое table вёрстска. Теперь все стили вписываем только в неё. Можно также вспомнить center , font .




От кого: Иванов Иван Иванович
Адрес: [email protected]
Сообщение: Смотрим и радуемся

С div то же самое

Нужный Вам текст

3) В примере выше с отправкой письма приводилась данная строка. Так вот её не забываем

$headers = "MIME-Version: 1.0" . "\r\n";

4) Используем HTML 3.2 . Вставляем в начало html письма.


5) В качестве background - можно цвет. Хотите фон-изображение - тогда делайте весь текст и фон изображением. Как вариант: можно указать background-image для body.

6) У единственной в ячейке картинки в Gmail появляется 3px отступ снизу, чтобы избежать этого указываем ей