Php mail: как отправить html? - PullRequest
       3

Php mail: как отправить html?

10 голосов
/ 04 февраля 2011

Код ниже отправляет электронное письмо правильно, но для тела. Мне нужно показать HTML в теле сообщения, и я не могу это сделать. Примеры в Интернете не отправят электронное письмо: (

Как я могу исправить свой код, чтобы отправить письмо с HTML в теле?

Спасибо за тонну!

<?php

$to = 'mymail@mail.com';

$subject = 'I need to show html'; 

$from ='example@example.com'; 

$body = '<p style=color:red;>This text should be red</p>';

ini_set("sendmail_from", $from);

$headers = "From: " . $from . "\r\nReply-To: " . $from . "";
  $headers .= "Content-type: text/html\r\n"; 
if (mail($to, $subject, $body, $headers)) {

  echo("<p>Sent</p>");
 } else {
  echo("<p>Error...</p>");
 }

?>

Ответы [ 5 ]

16 голосов
/ 04 февраля 2011

используйте этот заголовок для почты:

 $header  = "MIME-Version: 1.0\r\n";
 $header .= "Content-type: text/html; charset: utf8\r\n";

и для содержимого / тела:

<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
... ... ...

важно использовать встроенные команды css и рекомендуется использовать таблицы для интерфейса.

...

В вашем Mail-Body вы должны поместить HTML-код с головой и телом

4 голосов
/ 04 февраля 2011

Вы смотрели заголовки входящей почты? Это говорит

Reply-To: example@example.comContent-type: text/html

Просто добавьте еще \r\n здесь:

Reply-To: " . $from . "\r\n";
2 голосов
/ 04 февраля 2011

Я рекомендую вместо того, чтобы возиться с этим самостоятельно, вы используете один из многих бесплатных классов, доступных по всему Интернету.

Я бы порекомендовал: PHPMailer

1 голос
/ 04 февраля 2011

Я нашел, что это хорошо работает!

Источник

<?php
//define the receiver of the email
$to = 'youraddress@example.com';
//define the subject of the email
$subject = 'Test HTML email'; 
//create a boundary string. It must be unique 
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time())); 
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/alternative; boundary=\"PHP-alt-".$random_hash."\""; 
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-alt-<?php echo $random_hash; ?>  
Content-Type: text/plain; charset="iso-8859-1" 
Content-Transfer-Encoding: 7bit

Hello World!!! 
This is simple text email message. 

--PHP-alt-<?php echo $random_hash; ?>  
Content-Type: text/html; charset="iso-8859-1" 
Content-Transfer-Encoding: 7bit

<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p> 

--PHP-alt-<?php echo $random_hash; ?>--
<?
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed" 
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
0 голосов
/ 04 февраля 2011

Простой ответ: не делай этого.Письма в формате HTML являются злыми и раздражающими.По крайней мере, если не включена версия PROPER с открытым текстом.Proper = та же информация, что и в HTML-версии, а не просто глупый комментарий о получении другого почтового клиента или ссылка на html-версию, если она доступна в Интернете.

Если вам это действительно нужно: http://pear.php.net/package/Mail_Mime

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...