PHP为什么我的html显示为文本


PHP Why does my html display as text?

我正在学习php,并尝试将其发送到我的电子邮件中。这是我的代码:

  $to = "name@domain.com";
  $subject = "Competition Entry - WIN A 2 NIGHT FAMILY PRICE";
  $message = "Name: ".$name. "<br />" ."Surname: ".$surname.;
  mail ($to, $subject, $message);
  ?>

当它发送到我的电子邮件时,它显示为:

Name:  <br /> Surname:

为什么我的<br />显示为文本而不是中断?

附加头Content-Type

$headers .= "Content-Type: text/html; charset=UTF-8'r'n";

使用HTML格式发送邮件的文档示例:http://css-tricks.com/sending-nice-html-email-with-php/

如果您需要使用html:发送邮件,则必须发送正确的邮件头

 $header  = "MIME-Version: 1.0'r'n";
 $header .= "Content-type: text/html; charset: utf8'r'n";
 $to      = "name@domain.com";
 $subject = "Competition Entry - WIN A 2 NIGHT FAMILY PRICE";
 $message = "Name: ".$name. "<br />" ."Surname: ".$surname.;
 mail ($to, $subject, $message, $headers);

因为您的邮件正文默认为纯文本,而<br />是HTML标记。如果你想用HTML发送邮件,你需要正确地构建它(我建议你使用PHPMailer类来完成这项工作)。如果你只想换行。您需要使用'n

开始使用Swiftmailer,你的生活会更轻松。

require_once('swift/lib/swift_required.php');
$transport = Swift_MailTransport::newInstance();
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance()
    ->setFrom(array($from))
    ->setTo(array($to))
    ->setEncoder(Swift_Encoding::get7BitEncoding())
    ->setSubject($subject)
    ->setBody($body, 'text/html')
    ->addPart(strip_tags($body), 'text/plain')
    ->attach(Swift_Attachment::fromPath($filename))
;
$mailer->send($message);