无法使用 PHPMailer 在邮件中嵌入 base64 图像 URI

Unable to embed base64 image URI in mail using PHPMailer

我正在使用 https://github.com/endroid/qr-code and getting their URI to embed them in a mail using PHPMailer (https://github.com/PHPMailer/PHPMailer).

生成二维码

构建邮件对象:

$mail = new PHPMailer();
$mail->CharSet = "utf-8";
$mail->isSMTP();
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->SMTPDebug = 1; 
$mail->Host = "smtp.gmail.com";
$mail->Port = "587";
$mail->Username = "something@somewhere.com";
$mail->Password = "password";
$mail->setFrom("somewhere");
$mail->isHTML(true);
$mail->Subject = "QR";

然后生成 URI 并将其嵌入到邮件中

$qrURI = generateQR($requestId)
$mail->addStringEmbeddedImage($qrURI,"qr","qr.png",'base64','image/png');
$mail->Body = 'QR code: <img src="cid:qr" alt="QR code">'

发送邮件的结果是这样的:

我有 SMTPDebug=1,它没有给我任何错误

这是我生成的一个 URI 作为示例:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAUAAAAFACAIAAABC8jL9AAAACXBIWXMAAA7EAAAOxAGVKw4bAAAFEUlEQVR4nO3dQY7bQBAEQdPw/78sP2HHBhutJCPOC61EKTGnwlyfz+cX0PR7+w0A/0/AECZgCBMwhAkYwgQMYQKGMAFDmIAhTMAQJmAIEzCE/Tn8u+u6Rt/HM5wvQ573PN/82SccPk8nMIQJGMIEDGEChjABQ5iAIUzAECZgCBMwhAkYwgQMYQKGMAFD2Oka6dzz7mqZWM9MbHd2X3OC39KPnMAQJmAIEzCECRjCBAxhAoYwAUOYgCFMwBAmYAgTMIQJGMIEDGH3r5HO7d6R8+aly5s/+4TF5+kEhjABQ5iAIUzAECZgCBMwhAkYwgQMYQKGMAFDmIAhTMAQJmAI21wjseXNu6WHcQJDmIAhTMAQJmAIEzCECRjCBAxhAoYwAUOYgCFMwBAmYAgTMIRZI3278z3QxMbIbunLOYEhTMAQJmAIEzCECRjCBAxhAoYwAUOYgCFMwBAmYAgTMIQJGMI210j2K/ea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ECZgCBMwhAkYwgQMYQKGMAFDmIAhTMAQJmAIEzCECRjCrsMhxe7WpGJxlTKksoU6t/vkb3+eTmAIEzCECRjCBAxhAoYwAUOYgCFMwBAmYAgTMIQJGMIEDGEChrDTNRLwhZzAECZgCBMwhAkYwgQMYQKGMAFDmIAhTMAQJmAIEzCECRjC/gIsHA2FiBfxDQAAAABJRU5ErkJggg==

编辑: 好像数据格式不对,请问如何输出二维码嵌入到邮件中?

这是我在尝试@Synchro 所说的内容后生成的 QR 函数:

function generateQR($requestId){
    try {
        $writer = new PngWriter();
        $qrCode = QrCode::create($requestId)
        ->setEncoding(new Encoding('UTF-8'))
        ->setErrorCorrectionLevel(new ErrorCorrectionLevelLow())
        ->setSize(300)
        ->setMargin(10)
        ->setRoundBlockSizeMode(new RoundBlockSizeModeMargin())
        ->setForegroundColor(new Color(0, 0, 0))
        ->setBackgroundColor(new Color(255, 255, 255));

        $result = $writer->write($qrCode);
        echo $result->getString()
        } 
    catch (\Throwable $th) {
            echo $th;
        }
}

PHPMailer 不支持数据 URI,主要是因为使用它们不是一个好主意,因为它们在电子邮件客户端之间存在很多兼容性问题。最好使用常规的嵌入图像。为此,您需要做的就是将二进制 PNG 数据传递给 addStringEmbeddedImage 调用的第一个参数,而不是 URI 编码数据。我假设您需要修改 generateQR 函数以提供该格式的数据。