Остаточний message html. Як відправляти текстові повідомлення за допомогою PHP. Одержувач: подія onmessage


                // Відкриваємо файл для читання в бінарному форматі $ file \u003d fopen ( "file.zip", "rb"); // Прочитуємо його в рядок $ str_file $ str_file \u003d fread ($ file, filesize ( "file.zip")); // Перетворимо цей рядок в base64-формат $ str_file \u003d 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 \u003d "spravkaweb-1234"; $ header \u003d "From:" $ from_name "n"; $ header. \u003d "To: $ ton"; $ header. \u003d "Subject: $ subjectn"; $ header. \u003d "Mime-Version: 1.0n"; $ header. \u003d "Content-Type: multipart / mixed; boundary \u003d" $ bound ""; $ body \u003d "nn - $ boundn"; $ body. \u003d "Content-type: text / html; charset \u003d" windows-1251 "\\ n"; $ body. \u003d "Content-Transfer-Encoding: quoted -printablenn "; $ body. \u003d" $ message "; $ file \u003d fopen ($ file_name," rb "); $ body. \u003d" nn - $ boundn "; $ body. \u003d" Content-Type: application / octet -stream; "; $ body. \u003d" name \u003d ". basename ($ file_name)." \\ n "; $ body. \u003d" Content-Transfer-Encoding: base64n "; $ body. \u003d" Content-Disposition: attachmentnn " ; $ body. \u003d base64_encode (fread ($ file, filesize ($ file_name))). "n"; $ body. \u003d "$ 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 \u003d |   ; 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 \u003d 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 \u003d 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 \u003d "Петро Петрович"; // необов'язкова змінна як приклад вставки в повідомлення

  $ Subject \u003d "Тема повідомлення"; //Тема повідомлення
  $ Message \u003d "Привіт,". $ Name. "! \\ N
  Просто запитати як справи! \\ N
  З повагою, Іван Іванович "; // зміст повідомлення
  mail ($ email, $ subject, $ message, "From: [email protected] \\ nReply-To: [email protected] \\ nContent-type: text / plain; Charset \u003d utf-8 \\ r \\ n"); // відправляємо повідомлення
?>

2. Відправлення листа mail php Тип text / html

  Можуть містити графічні html-елементи, ссликой і тп.
  Більше обсяг переданої інформації

  // відправка декільком адресатам
  $ To \u003d "[email protected]". ","; // кому відправляємо
  $ To. \u003d "[email protected]". ","; // Увага! Так пишемо другий і тд адреси
  // не забуваємо кому. Навіть в останньому контакті зайвою не буде
  // Для початківців! $ To. \u003d Точка в цьому випадку для дописування в змінну

  // встановлюємо тип повідомлення Content-type, якщо хочемо
  $ Headers \u003d "MIME-Version: 1.0". "\\ R \\ n";
  $ Headers. \u003d "Content-type: text / html; charset \u003d utf-8 \\ r \\ n";

  // додаткові дані
  $ Headers. \u003d "From: yournick \\ R \\ n "; // від кого
  $ Headers. \u003d "Cc: [email protected]". "\\ R \\ n"; // копія повідомлення на цю адресу
  $ Headers. \u003d "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 \u003d "MIME-Version: 1.0". "\\ R \\ n";

4)   використовуємо HTML 3.2. Вставляємо в початок html листи.


5)   Як background - можна колір. Хочете фон-зображення - тоді робіть весь текст і фон зображенням. Як варіант: можна вказати background-image для body.

6)   У єдиною в осередку картинки в Gmail з'являється 3px відступ знизу, щоб уникнути цього вказуємо їй