我将通过一个PHP网站发送邮件。客户可能会自定义邮件主题,而我将获得UTF-8的帖子数据。但是,当我使用PHP mail()发送HTML电子邮件时,我发现主题无法正确显示,但正文可以。
如何在PHP邮件函数中发送中文词汇?
谢谢。
如何在PHP邮件函数中发送中文词汇?
谢谢。
您需要根据编码单词的规定(请参见RFC 2047)对主题进行编码:
encoded-word = "=?" charset "?" encoding "?" encoded-text "?="
the Base64 encoding (base64_encode
):
'Subject: =?UTF-8?B?'.base64_encode($subject).'?='
or
the quoted-printable encoding (see RFC 2045, imap_8bit
):
'Subject: =?UTF-8?Q?'.imap_8bit($subject).'?='
我使用 PEAR Mail_Mime 和 mb_encode_mimeheader 来编码主题。这里是一个可用的函数示例:
<?php
function mail_html($from, $to, $subject, $message_html, $headers = array()) {
require_once "Mail.php";
require_once 'Mail/mime.php';
$smtp = Mail::factory('smtp',
array (
'host' => 'smtp.example.com',
'auth' => true,
'username' => 'user@example.com',
'password' => 'password'));
if(function_exists('mb_internal_encoding'))
mb_internal_encoding('UTF-8');
if(function_exists('mb_encode_mimeheader'))
$subject = mb_encode_mimeheader($subject,"UTF-8", "B", "\n");
$h = array();
$h['From'] = "$from";
$h['Bounce'] = "$from";
$h['Reply-To'] = "$from";
$h['Return-Path'] = "$from";
$headers['Subject'] = $subject;
$headers = array_merge($h, $headers);
$mime = new Mail_mime();
$mime->setHTMLBody($message_html);
$body = $mime->get(array('html_charset' => 'UTF-8', 'html_encoding' => '8bit', 'head_charset'=> 'UTF-8'));
$hdrs = $mime->headers($headers);
$mail = $smtp->send($to, $hdrs, $body);
if (PEAR::isError($mail))
echo 'error', 'Unable to send email';
else
echo "Sent email to $to from $from";
}
?>