2011-02-04 67 views
10

下面的代码正确发送电子邮件,但是正文。我需要在邮件正文中显示html,但我无法做到。在网络中的示例将不会发送电子邮件:(Php mail:如何发送html?

如何解决我的代码与在体内的HTML发送电子邮件?

由于一吨!

<?php 

$to = '[email protected]'; 

$subject = 'I need to show html'; 

$from ='[email protected]'; 

$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>"); 
} 

?> 
+0

+1的问题,我有同样的问题,但这个线程的答案是(从不同的角度) – Sam 2011-03-30 01:55:58

回答

16

用这个头的麦L:

$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命令的重要和建议报告给使用表格的接口。

...

在您的邮件正文,你不是得把HTML code with head and body

1

我发现这个效果很好!

Source

<?php 
//define the receiver of the email 
$to = '[email protected]'; 
//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: [email protected]\r\nReply-To: [email protected]"; 
//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

发现在我的情况太多,但不发送,为什么? – lleoun 2011-02-04 11:06:08

+0

邮件设置是否正确?你在IIS服务器上吗? – chrisjlee 2011-05-06 20:35:47

+0

这依赖于邮件命令。该命令出现在大多数* NIX系统中。 – 2012-04-18 18:01:29

-3

答案很简单:不要这样做。 HTML电子邮件是邪恶和烦人的。至少如果不包含PROPER纯文本版本。 Proper =与HTML版本相同的信息,不仅仅是关于获取另一个电子邮件客户端的愚蠢评论,或者如果网页上提供了html版本的链接。

如果你真的需要它:http://pear.php.net/package/Mail_Mime

2

我建议,而不是做这个自己乱搞,你可以使用所有网站上做了很多免费的课程之一。

我会建议:PHPMailer

3

你看着接收邮件的标题?它说

Reply-To: [email protected]: text/html

只需添加另一个\r\n这里:

Reply-To: " . $from . "\r\n";