使用html代码发送phpmailer电子邮件

时间:2014-10-24 06:21:37

标签: php email phpmailer

我创建了一个发送邮件的函数,但是它们解释了html代码。如何让它在身体中发送确切的HTML代码?例如,用户应该收到<strong>text</strong>而不是粗体强的&#39;。

function sendmail($dest,$subj ,$htmlmessage,$textmessage) {
    $Mail = new PHPMailer( true );
    try{

        $Mail->IsSMTP(); // Use SMTP
        $Mail->SMTPAuth = TRUE; // enable SMTP authentication
        //$Mail->SMTPDebug = 2; // 2 to enable SMTP debug information

        $Mail->Host = "smtp.gmail.com"; // Sets SMTP server
        $Mail->Username = 'mymail@gmail.com'; // SMTP account username
        $Mail->Password = 'mypassword'; // SMTP account password
        $Mail->SMTPSecure  = "ssl"; //Secure conection
        $Mail->Port = 465; // set the SMTP port

        $Mail->SetFrom ( 'mymail@gmail.com', 'def' );
        $Mail->FromName    = 'myname';
        //$Mail->addReplyTo( 'mymail@gmail.com', 'Reply here' );

        $Mail->addAddress($dest, 'to' ); // To:
        $Mail->isHTML( false );

        $Mail->Subject=$subj;
        $Mail->Body=$htmlmessage;
        $Mail->AltBody=$textmessage;

        $Mail->Send();
    }
    catch ( phpmailerException $e ) {

        file_put_contents( 'Mailerrors.txt', $e->errorMessage() , FILE_APPEND );
        die( "Problem with emailing." );
    }
}

我在这里发送邮件

$dest='sendto@gmail.com';
$subj='hello';
$htmlmessage='this is the body<strong>asd</strong>';
$textmessage='this is the body';

sendmail($dest,$subj, $htmlmessage,$textmessage);

请注意,该功能可以正常工作并向我发送电子邮件,只需解释html代码即可。

2 个答案:

答案 0 :(得分:1)

有几种可能的解决方案。

要仅发送纯文本,请执行以下操作:

$mail->isHTML(false);

不要放任何内容 $mail->AltBody。这样,即使消息包含HTML标记,消息也将以纯文本形式发送。

如果您只想要部分邮件正文转义HTML呈现,则可以使用htmlspecialchars或将标记的那部分包装在<pre>标记中。

htmlspecialchars应用于整个邮件正文有点毫无意义,因为它可以获得与isHTML(false)相似的结果,但效率却低得多。

答案 1 :(得分:0)

我做到了。我所要做的就是:

 $Mail->Body=htmlspecialchars($htmlmessage);

不确定这是不是一个好主意,即使它有效。我确信也必须有另一种方式。

相关问题