PHP邮件:如何发送HTML?

下面的代码正确发送电子邮件,但正文。 我需要在消息的正文中显示html,我无法做到。 在networking中的例子不会发送电子邮件:(

我怎样才能修正我的代码发送电子邮件与身体的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>"); } ?> 

使用这个邮件头:

  $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命令很重要,build议使用表格作为接口。

在你的邮箱中,你不得不把头部和身体的HTML代码

你看过传入邮件的标题吗? 它说

 回复:example@example.comContent-type:text / html 

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

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

我build议你不要自己动手做这个,而是使用networking上的许多免费课程之一来做。

我会build议: PHPMailer

我发现这个效果很好!

资源

 <?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"; ?> 

简单的答案:不要这样做。 HTML电子邮件是邪恶和烦人的。 至less如果没有包含PROPER的纯文本版本。 适当=相同的信息,如在HTML版本,不只是一个愚蠢的评论关于获得另一个电子邮件客户端或链接到的HTML版本,如果它可以在网上。

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