在使用 SMTP 身份验证时通过 PEAR 发送 HTML 消息会返回错误

2022-01-17 00:00:00 smtp gmail php pear

我正在尝试在 PHP 中使用 SMTP 身份验证向 Gmail 发送 HTML 邮件.这是我正在使用的脚本:

I'm trying to send an HTML message while using SMTP authentication to Gmail in PHP. Here is the script that I am using:

require_once "Mail.php";
require_once 'Mail/mime.php';

$from = "Some Name <myemail@gmail.com>";
$to = "Other Name <otheremail@gmail.com>";
$subject = "This is a test";
$crlf = "
";

$host = "ssl://smtp.gmail.com";
$port = "465";
$username = "myemail@gmail.com";
$password = "mypass";

$headers = array ('From' => $from,
                  'Return-Path' => $from,
                  'Subject' => $subject);

$smtp = Mail::factory('smtp',
  array ('host' => $host,
    'port' => $port,
    'auth' => true,
    'username' => $username,
    'password' => $password));

$mime = new Mail_mime($crlf);
$mime->setTXTBody("This is a test email message");
$mime->setHTMLBody($body);
$body = $mime->get();
$headers = $mime->headers($headers);

$mail = $smtp->send($to, $headers, $body);

if (PEAR::isError($mail)) {
  echo("<p>" . $mail->getMessage() . "</p>");
} else {
  echo("<p>Message successfully sent!</p>");
}

注意:$body 是一个包含图像和其他信息的 HTML 表格.

Note: the $body is an HTML table with images and other info.

当我执行脚本失败并出现以下错误:

When I execute the script it fails with the following error:

未能设置发件人:某些名称 [SMTP:无效的响应代码从服务器收到(代码:555,响应:5.5.2 语法错误.c6sm20541406obd.22)]

Failed to set sender: Some name [SMTP: Invalid response code received from server (code: 555, response: 5.5.2 Syntax error. c6sm20541406obd.22)]

这是我尝试查看的问题所在:1. 使用Mail"而不是smtp"使用相同的脚本,即

Here is what I've tried to see what is going wrong: 1. Using the same script using 'Mail' instead of 'smtp' i.e.

$smtp = Mail::factory('Mail');

这很好用.2. 使用没有 mime.php 的相同脚本,这也可以,但不允许发送 HTML 电子邮件.

This works just fine. 2. Using the same script w/o the mime.php, this also works but doesn't allow one to send an HTML email.

有人知道如何将两者结合起来,以便我仍然使用 SMTP 身份验证和发送 HTML 消息吗?

Does anybody know how I can combine the two so that I'm still using SMTP authentication and send an HTML message?

这是 $mime->headers() 的转储:

[MIME-Version] => 1.0
[From] => Some Name
[Return-Path] => Some Name
[Subject] => This is a test
[Content-Type] => multipart/alternative;
boundary="=_8662996a1f586248545d9f01f48e916d"

推荐答案

自己终于想通了.

感谢 Abid Hussain 在此处提供示例链接:http://tonyvirelli.com/slider/php-html-email-using-smtp/

Thanks to Abid Hussain for providing the link to the example here: http://tonyvirelli.com/slider/php-html-email-using-smtp/

解决方案:

  1. 去掉'Return-Path' =>$from 来自 headers 数组.
  2. 添加到=>;$to 到 headers 数组(没有这个,收到的电子邮件的 to 标头是未公开的收件人)
  1. Remove the 'Return-Path' => $from from the headers array.
  2. Add To => $to to the headers array(without this, the to header of the received email is Undisclosed recipients)

相关文章