Безукоризненный message html. Создание красивых сообщений с помощью CSS

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

$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 отступ снизу, чтобы избежать этого указываем ей

В данном уроке Вы научитесь создавать красивые сообщения с помощью CSS. Кроме этого, Вы также узнаете как ими правильно пользоваться.

Давайте начнем с типов сообщений

1. Информационные сообщения

Цель этих сообщений информирования пользователя. Такие сообщения должны быть голубыми, так как люди ассоциируют этот цвет с информацией. Это может быть любая информация, которая может быть полезна юзеру.

2. Сообщения об успехе

Сообщения об успехе должны быть показаны после того, как юзер успешно выполнил какую-либо операцию. Успешно - означает полностью и без ошибок. Обычно такие сообщения зеленого цвета.

3. Сообщения-предупреждения

Подобные сообщения должны быть показаны пользователю если операция не может быть завершена. Обычно они желтого цвета.

4. Сообщения об ошибке

Сообщения об ошибке должны быть показаны только в том случае, если операцию невозможно выполнить. Красный идеальный цвет для этого, так как многие ассоциируют этот цвет с тревогой:)

5. Сообщения проверки

Еще один тип сообщений. Я предпочел для них оранжевый цвет. Подобные сообщения показывают пользователю его ошибки (например, при заполнении форм).

Теперь давайте посмотрим как такие сообщения создать

Нам понадобится следующий код CSS :

Body{
font-family:Arial, Helvetica, sans-serif;
font-size:13px;
}
.info, .success, .warning, .error, .validation {
border: 1px solid;
margin: 10px 0px;
padding:15px 10px 15px 50px;
background-repeat: no-repeat;
background-position: 10px center;
}
.info {
color: #00529B;
background-color: #BDE5F8;
background-image: url("info.png");
}
.success {
color: #4F8A10;
background-color: #DFF2BF;
background-image:url("success.png");
}
.warning {
color: #9F6000;
background-color: #FEEFB3;
background-image: url("warning.png");
}
.error {
color: #D8000C;
background-color: #FFBABA;
background-image: url("error.png");
}
.validation {
color: #D63301;
background-color: #FFCCBA;
background-image: url("validation.png");
}

Данный код можно вставить как в тот же файл, так и вынести в таблицу стилей.

Теперь нам достаточно в теле документа создать слой с необходимым классом:

Info message

Successful operation message

Warning message

Error message

Validation message

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

Sending HTML Email through PHP uses the exact same mail function as 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 .= "CC: [email protected]\r\n"; $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

Now We Can Use HTML Tags

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 .= "";

Here is whole shebang, to create the table of data as shown above:

$message = ""; $message ..png" alt="Website Change Request" />"; $message .= "

"; $message .= ""; $message .= ""; $message .= ""; $message .= ""; $message .= ""; $addURLS = $_POST["addURLS"]; if (($addURLS) != "") { $message .= ""; } $curText = htmlentities($_POST["curText"]); if (($curText) != "") { $message .= ""; } $message .= ""; $message .= "
Name: " . strip_tags($_POST["req-name"]) . "
Email: " . strip_tags($_POST["req-email"]) . "
Type of Change: " . strip_tags($_POST["typeOfChange"]) . "
Urgency: " . strip_tags($_POST["urgency"]) . "
URL To Change (main): " . $_POST["URL-main"] . "
URL To Change (additional): " . strip_tags($addURLS) . "
CURRENT Content: " . $curText . "
NEW Content: " . htmlentities($_POST["newText"]) . "
"; $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?

Concerns

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.

Demo

I updated the demo and download to use the new HTML email format.

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.

The HTML5 Messaging API enables HTML5 pages to send messages to each other, even if the pages are not loaded from the same domain (e.g. www.jenkov.com and www.scriptdraw.com).

Sending Messages

In order to send messages from one page to another, the page sending the message must have a reference to the window of the other page. The sending page then calls the postMessage() function on the window object of the receiving page.

Here is an example of a page sending a message to another page displayed in an iframe:

Var message = "Hello there"; var origin = "http://сайт"; var theIframe = document.getElementById("theIframe"); theIframe.contentWindow.postMessage(message, origin);

You can run the code above by pressing this button:


The value of the origin parameter passed to the postMessage() function must match the domain from which the page in the iframe was loaded. If the origins do not match, this will not work. You do not need the full address of the page as origin. The domain is enough, for instance http://localhost or http://сайт

Receiving Messages

To listen for messages a page needs to set the onmessage event handler function on its own window object. Here is an example that works in Firefox and Chrome:

Window.onmessage = function(event) { document.getElementById("show").innerHTML = "Message Received: " + event.data + " from: " + event.origin; };

This example sets the onmessage function on the window object. Inside the function the code selects the HTML element with the id show , and sets the inner HTML of that element to "Message Received: ", plus the message received. This event handler is actually the one used in the page displayed in the iframe in the example under "Sending Messages".

In Internet Explorer 9 you have to use this code to listen for the onmessage event:

Window.attachEvent("onmessage", function(event) { document.getElementById("show").innerHTML = "Message Received: " + event.data + " from: " + event.origin; });

You can just keep both of these event listener code blocks in your page. They should not conflict with each other.

The event object received contains the following properties:

Data origin source

The data property contains the message sent from the sending page.

The origin property contains the origin (domain) of the page that sent the message.

The source property contains a reference to the window object of the sending page. This window object reference can be used to send messages back to the sender page, using the postMessage() function. Here is an example:

Window.onmessage = function(event) { event.source.postMessage("Thank you for the message", event.origin); }

Sending JSON

The messaging API only allows you to send string messages. If you need to send a JavaScript object, you will need to turn it into a JSON string using JSON.stringify() , and parse it again using JSON.parse() . Here is an example:

Var theObject = { property1: "hello", property2: "world" }; var message = JSON..getElementById("theIframe"); theIframe.contentWindow.postMessage(message, origin);

And here is how the JSON string is parsed into a JavaScript object:

Window.onmessage = function(event) { var theObject = JSON.parse(event.data); }