PHP HTML邮件无法正常工作

时间:2012-07-29 05:24:41

标签: php html gmail sendmail

我创建了重置密码页面,其中使用了输入hes email,然后PHP向他发送了重置密钥。邮件有效,但它在我的Gmail帐户中以纯文本格式显示。我希望它用HTML格式。

$subject = "Your password reset for {$config['site_name']}";

$message = "<html><body>";

$message .= "<p>Someone on" . $config['site_domain'] . "tried to reset your password.</p>";
$message .= "<p>Please click below link, if you want to reset your password.</p>";

$message .= "<p><a href='" . $config['site_url'] . "/forgot_password.php?key=" . $key . "'>" . $config['site_url'] . "/forgot_password.php?key=" . $key . "</a></p>";


$message .= "<p>Thank you,<br>The Admin - " . $config['site_url'] . " </p>";

$message .= "</body></html>";

// Create email headers             
// To send HTML mail, the Content-type header must be set
$headers  = "MIME-Version: 1.0 \r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1 \r\n";

// Additional headers
//$headers .= 'To: Mary <mary@example.com>, Kelly <kelly@example.com>' . "\r\n";
$headers .= "From: " . $config['site_name'] . " <noreply@" . $config['site_domain'] . "> \r\n";
$headers .= "X-Sender: <noreply@" . $config['site_domain'] . "> \r\n";
$headers .= "Reply-To: <noreply@" . $config['site_domain'] . "> \r\n";

mail($input['email'],$subject,$message,$headers);

//update pw_reset field into DATABASE
$stmt = $mysqli->prepare("UPDATE members SET pw_reset = ? WHERE email = ?");
$stmt->bind_param("ss", $key, $input['email']);
$stmt->execute();
$stmt->close();     

2 个答案:

答案 0 :(得分:1)

您应该像这样构建标题:

$headers = 'From: You <you@example.com>' . "\n"; 
$headers .= 'MIME-Version: 1.0' . "\n"; 
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; 

请注意,From位于MIME和Content之前,只有Content以“\ r \ n”结尾,另一个只是“\ n”。

Source(saganwebdesign)

答案 1 :(得分:0)

试试这个功能。成功时返回true

function sendMail($email, $subject, $message)
{
    $supportEmail = 'support@abc.com';
    $from = 'Test Application';
    $msg  = $message;
    $from = str_replace(' ', '-', $from);
    $frm  = $from.' <'.$supportEmail.'>';
    preg_match("<(.*)@(.*\..*)>", $frm, $match);

    ///////////////////Headers/////////////////
    $hdr='';
    $hdr.='MIME-Version: 1.0'."\n";
    $hdr.='content-type: text/html; charset=iso-8859-1'."\n";
    $hdr.="From: {$frm}\n";
    $hdr.="Reply-To: {$frm}\n";
    $hdr.="Message-ID: <".time()."@{$match[2]}>\n";
    $hdr.='X-Mailer: PHP v'.phpversion();
    $x=@mail($email, $subject, $msg, $hdr);
    if($x==0)
    {
        $email=str_replace('@','\@', $email);
        $hdr=str_replace('@','\@',$hdr);
        $x=@mail($email, $subject, $msg, $hdr);
    }
    return $x;
}