使用 mail() 发送 HTML 电子邮件

<?php
$to      = 'recipent@example.com';
$subject = 'Sending an HTML email using mail() in PHP';
$message = '<html><body><p><b>This paragraph is bold.</b></p><p><i>This text is italic.</i></p></body></html>';

$headers = implode("\r\n", [
    "From: John Conde <webmaster@example.com>",
    "Reply-To: webmaster@example.com",
    "X-Mailer: PHP/" . PHP_VERSION,
    "MIME-Version: 1.0",
    "Content-Type: text/html; charset=UTF-8"
]);

mail($to, $subject, $message, $headers);

这与发送纯文本电子邮件没什么不同。关键区别是内容主体的结构类似于 HTML 文档,并且必须包含两个额外的标头,以便电子邮件客户端知道将电子邮件作为 HTML 进行交换。他们是:

  • MIME 版本:1.0
  • Content-Type:text / html; 字符集= UTF-8