使用 PHPMailer 在 HTML 电子邮件中无法很好地显示 UTF-8 口音

我正在设置一个 PHPMailer PHP 表单,它将表单发送到我们的 Office 365 帐户。我对显示的法语口音有疑问,有“éééÃÃÃÃçç”口音,如“ééààçç”。


PHP 表单以 UTF-8 编码;PHP 代码也采用 UTF-8 编码;


但是收到的电子邮件似乎没有显示正确的字符。


我添加了这些设置,但没有任何改变:


在 PHP 文件中


header('Content-Type: charset=utf-8');


$mail->isHTML(true);     // Set email format to HTML

$mail->CharSet = "UTF-8";

Php 发送表单源代码:


<?php

header('Content-Type: charset=utf-8');

ini_set('startup_errors', 1);

ini_set('display_errors', 1);

error_reporting(E_ALL);    


use PHPMailer\PHPMailer\PHPMailer;

use PHPMailer\PHPMailer\Exception;


require 'php/phpmailer/vendor/phpmailer/phpmailer/src/Exception.php';

require 'php/phpmailer/vendor/phpmailer/phpmailer/src/PHPMailer.php';

require 'php/phpmailer/vendor/phpmailer/phpmailer/src/SMTP.php';


$nom_compagnie = $_POST['nom_compagnie'];

$nom_complet = $_POST['nom_complet'];

$poste = $_POST['poste'];

$email = $_POST['email'];

$telephone = $_POST['telephone'];

$commentaire = $_POST['commentaire'];

$from = $_POST['email'];


function post_captcha($user_response) {

    $fields_string = '';

    $fields = array(

        'secret' => 'PrivateKey',

        'response' => $user_response

    );

    foreach($fields as $key=>$value)

    $fields_string .= $key . '=' . $value . '&';

    $fields_string = rtrim($fields_string, '&');


    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');

    curl_setopt($ch, CURLOPT_POST, count($fields));

    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);


    $result = curl_exec($ch);

    curl_close($ch);


    return json_decode($result, true);

}

    

收到的电子邮件显示如下:


显示邮件中的 H3 标题


Vous avez reçu un formulaire de contact via le site Web

应该是这样写的


Vous avez reçu un formulaire de contact via le site web

口音“é”也显示有“é”。


我不知道问题出在哪里。


如果我的代码编程良好,有什么线索吗?


至尊宝的传说
浏览 152回答 2
2回答

临摹微笑

卓悦斯特凡。此页面描述了您所看到的症状;一个字符变成两个意味着您的数据是 UTF-8 格式,但正在使用 8 位字符集显示。一般来说,PHPMailer 是正确的,所以你需要弄清楚你哪里出错了。如果您使用,SMTPDebug = 2您将能够看到正在发送的消息(使用像é😎这样的非常短的消息正文,保证只能在 UTF-8 中工作)。确保脚本文件本身的编码也是 UTF-8 - 将表情符号放入其中是确保它是的好方法。诊断的问题在于您会发现您的操作系统受到干扰 - 诸如复制到剪贴板之类的事情可能会改变编码 - 因此处理它的方法是使用十六进制转储功能,让您检查实际字节值。法语是最容易查看的字符之一,因为几乎所有字符都是常规的单字节 ASCII 兼容字符,并且重音字符更容易被发现。在 PHP 中,该bin2hex()函数将执行此操作。您有 2 个错别字:Debutoutput应该Debugoutput并且fonction应该是function- 这是从以下位置转储十六进制数据的好地方:$mail->Debugoutput&nbsp;=&nbsp;function($str,&nbsp;$level)&nbsp;{echo&nbsp;$str,&nbsp;"\n",&nbsp;bin2hex($str),&nbsp;"\n";};下面是一个例子:echo&nbsp;'abc&nbsp;',&nbsp;bin2hex('abc');这将产生abc 616263;&nbsp;每个输入字符都会产生 2 个十六进制数字(1 个字节)的输出。如果您的输入是abé并且您的字符集是 ISO-8859-1,它将显示为abé 6162e9,因为该字符e9集中的é 是(十六进制)。UTF-8 中的相同字符串将作为 出现abé 6162c3a9,因为 UTF8 中的 é 是c3a9-两个字节,而不仅仅是一个。像这样检查字符可以让您绝对确定数据所在的字符集 - 仅查看它是不够的!所以,虽然我不能确切地说出你的问题在哪里,但希望你对如何诊断它有一些更好的想法。

心有法竹

代替$mail&nbsp;->&nbsp;charSet&nbsp;=&nbsp;"UTF-8";和$mail->CharSet&nbsp;=&nbsp;'UTF-8';
打开App,查看更多内容
随时随地看视频慕课网APP