简体   繁体   English

发送带有html代码的phpmailer电子邮件

[英]Send phpmailer email with html code

I made a function that sends mails, but they interpret html code. 我做了一个发送邮件的函数,但是它们解释html代码。 How can I make it to send exact html code in the body? 我怎样才能使其在正文中发送确切的html代码? For instance, the user should receive <strong>text</strong> and not bolded 'strong'. 例如,用户应该收到<strong>text</strong>而不是粗体的“ strong”。

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." );
    }
}

Here I send the mail 我在这里发送邮件

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

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

Note that the function does work and sends me emails, just they interpret the html code. 请注意,该功能确实起作用并向我发送电子邮件,仅由他们解释html代码。

There are several possible solutions to this. 有几种可能的解决方案。

To send only plain text, just do this: 要仅发送纯文本,只需执行以下操作:

$mail->isHTML(false);

and do not put anything in $mail->AltBody . 并且不要在 $mail->AltBody 放置任何 $mail->AltBody That way the message will be sent as plain text, even if it contains HTML markup. 这样,即使邮件包含HTML标记,邮件也将以纯文本格式发送。

If you only want part of your message body to escape HTML rendering, you can either use htmlspecialchars or wrap that portion of your markup in <pre> tags. 如果只希望消息正文的一部分转义HTML呈现,则可以使用htmlspecialchars或将标记的那部分包装在<pre>标记中。

Applying htmlspecialchars to the whole message body is a bit pointless as it achieves a similar looking result to isHTML(false) , but far less efficiently. htmlspecialchars应用于整个消息主体是没有意义的,因为它实现了与isHTML(false)类似的外观结果,但是效率低得多。

I did it. 我做的。 All I had to do: 我要做的就是:

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

Not sure if it's a good idea, even though it works. 即使可行,也不确定这是否是一个好主意。 I'm sure there must be another way, too. 我相信也必须有另一种方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM