SMTP 连接()失败 PHPmailer - PHP

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22927634/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:22:35  来源:igfitidea点击:

SMTP connect() failed PHPmailer - PHP

phpemail

提问by Chinmay Dabke

I am new to PHP. I was trying to send myself a sample e-mail through PHPmailer. I am using gmail's smtp server. I am trying to send a sample mail from my gmail account to my yahoo account. But I am getting the error : Mailer Error: SMTP connect() failed.
Here is the code :

我是 PHP 新手。我试图通过 PHPmailer 给自己发送一封示例电子邮件。我正在使用 gmail 的 smtp 服务器。我正在尝试将示例邮件从我的 gmail 帐户发送到我的 yahoo 帐户。但我收到错误:Mailer Error: SMTP connect() failed.
这是代码:

<?php

require "class.phpmailer.php";
$mail = new PHPMailer(); 
$mail->IsSMTP();                              // send via SMTP
$mail->Host = "ssl://smtp.gmail.com";
$mail->SMTPAuth = true;                       // turn on SMTP authentication
$mail->Username = "[email protected]";        // SMTP username
$mail->Password = "mypassword";               // SMTP password
$webmaster_email = "[email protected]";       //Reply to this email ID
$email="[email protected]";                // Recipients email ID
$name="My Name";                              // Recipient's name
$mail->From = $webmaster_email;
$mail->Port = 465;
$mail->FromName = "My Name";
$mail->AddAddress($email,$name);
$mail->AddReplyTo($webmaster_email,"My Name");
$mail->WordWrap = 50;                         // set word wrap
$mail->IsHTML(true);                          // send as HTML
$mail->Subject = "subject";
$mail->Body = "Hi,
This is the HTML BODY ";                      //HTML Body 
$mail->AltBody = "This is the body when user views in plain text format"; //Text Body 

if(!$mail->Send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message has been sent";
}
?>

I am using WAMP server on a Windows 7 64-bit machine. What could be the prob?
Please help me solve this. Thanks!

我在 Windows 7 64 位机器上使用 WAMP 服务器。可能是什么问题?
请帮我解决这个问题。谢谢!

采纳答案by Shankar Damodaran

You need to add the Hostparameter

您需要添加Host参数

$mail->Host = "ssl://smtp.gmail.com"; 

Also, check if you have open_sslenabled.

另外,请检查您是否已open_ssl启用。

<?php
echo !extension_loaded('openssl')?"Not Available":"Available";

回答by Rizwan Akhwandzada

The solution of this problem is really very simple. actually Google start using a new authorization mechanism for its User.. you might have seen another line in debug console prompting you to log into your account using any browser.! this is because of new XOAUTH2authentication mechanism which google start using since 2014. remember.. do not use the ssl over port 465, instead go for tls over 587. this is just because of XOAUTH2 authentication mechanism. if you use ssl over 465, your request will be bounced back.

这个问题的解决方法真的很简单。实际上,Google 开始为其用户使用新的授权机制。您可能已经在调试控制台中看到另一行提示您使用任何浏览器登录您的帐户。!这是因为谷歌自 2014 年开始使用新的XOAUTH2身份验证机制。记住..不要在端口 465 上使用ssl,而是在 587 上使用tls。这只是因为 XOAUTH2 认证机制。如果您使用 ssl 超过 465,您的请求将被退回。

what you really need to do is .. log into your google account and open up following address https://www.google.com/settings/security/lesssecureappsand check turn on. you have to do this for letting you to connect with the google SMTP because according to new authentication mechanism google bounce back all the requests from all those applications which does not follow any standard encryption technique.. after checking turn on.. you are good to go.. here is the code which worked fine for me..

您真正需要做的是..登录您的谷歌帐户并打开以下地址 https://www.google.com/settings/security/lesssecureapps并检查打开。您必须这样做才能让您与 google SMTP 连接,因为根据新的身份验证机制,google 会退回来自所有那些不遵循任何标准加密技术的应用程序的所有请求。去..这是对我来说很好用的代码..

require_once 'C:\xampp\htdocs\email\vendor\autoload.php';

define ('GUSER','[email protected]');
define ('GPWD','your password');


// make a separate file and include this file in that. call this function in that file.

function smtpmailer($to, $from, $from_name, $subject, $body) { 
    global $error;
    $mail = new PHPMailer();  // create a new object
    $mail->IsSMTP(); // enable SMTP
    $mail->SMTPDebug = 2;  // debugging: 1 = errors and messages, 2 = messages only
    $mail->SMTPAuth = true;  // authentication enabled
    $mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for GMail
    $mail->SMTPAutoTLS = false;
    $mail->Host = 'smtp.gmail.com';
    $mail->Port = 587;

    $mail->Username = GUSER;  
    $mail->Password = GPWD;           
    $mail->SetFrom($from, $from_name);
    $mail->Subject = $subject;
    $mail->Body = $body;
    $mail->AddAddress($to);
    if(!$mail->Send()) {
        $error = 'Mail error: '.$mail->ErrorInfo; 
        return false;
    } else {
        $error = 'Message sent!';
        return true;
    }
}

回答by Lynton Black

Solved an almost identical problem, by adding these lines to the standard PHPMailer configuration. Works like a charm.

通过将这些行添加到标准 PHPMailer 配置中,解决了几乎相同的问题。奇迹般有效。

$mail->SMTPKeepAlive = true;   
$mail->Mailer = “smtp”; // don't change the quotes!

Came across this code (from Simon Chen) while researching a solution here, https://webolio.wordpress.com/2008/03/02/phpmailer-and-smtp-on-1and1-shared-hosting/#comment-89

在此处研究解决方案时遇到了此代码(来自 Simon Chen),https://webolio.wordpress.com/2008/03/02/phpmailer-and-smtp-on-1and1-shared-hosting/#comment-89

回答by Jhonattan

Troubleshooting

故障排除

You have add this code:

您已添加此代码:

 $mail->SMTPOptions = array(
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        )
    );

And Enabling Allow less secure apps: "will usually solve the problem for PHPMailer, and it does not really make your app significantly less secure. Reportedly, changing this setting may take an hour or more to take effect, so don't expect an immediate fix"

和启用允许不太安全的应用程序:“通常会解决 PHPMailer 的问题,并且它不会真正使您的应用程序安全性显着降低。据报道,更改此设置可能需要一个小时或更长时间才能生效,因此不要指望立即使固定”

This work for me!

这对我有用!

回答by A.M.N.Bandara

If anyone is still unable to solve the issue, please check following thread and follow callmebob's answer.

如果有人仍然无法解决问题,请查看以下线程并遵循 callmebob 的回答。

PHPMailer - SMTP ERROR: Password command failed when send mail from my server

PHPMailer - SMTP 错误:从我的服务器发送邮件时密码命令失败

回答by Kraang Prime

You are missing the directive that states the connection uses SSL

您缺少说明连接使用 SSL 的指令

require ("class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP(); 
$mail->SMTPAuth = true;     // turn of SMTP authentication
$mail->Username = "YAHOO ACCOUNT";  // SMTP username
$mail->Password = "YAHOO ACCOUNT PASSWORD"; // SMTP password
$mail->SMTPSecure = "ssl";
$mail->Host = "YAHOO HOST"; // SMTP host
$mail->Port = 465;

Then add in the other parts

然后加入其他部分

$webmaster_email = "[email protected]";       //Reply to this email ID
$email="[email protected]";                // Recipients email ID
$name="My Name";                              // Recipient's name
$mail->From = $webmaster_email;
$mail->FromName = "My Name";
$mail->AddAddress($email,$name);
$mail->AddReplyTo($webmaster_email,"My Name");
$mail->WordWrap = 50;                         // set word wrap
$mail->IsHTML(true);                          // send as HTML
$mail->Subject = "subject";
$mail->Body = "Hi,
This is the HTML BODY ";                      //HTML Body 
$mail->AltBody = "This is the body when user views in plain text format"; //Text Body 

if(!$mail->Send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message has been sent";
}

As a side note, I have had trouble using Body + AltBody together although they are supposed to work. As a result, I wrote the following wrapper function which works perfectly.

作为旁注,我在使用 Body + AltBody 时遇到了麻烦,尽管它们应该可以工作。因此,我编写了以下完美运行的包装函数。

<?php
require ("class.phpmailer.php");

// Setup Configuration for Mail Server Settings
$email['host']          = 'smtp.email.com';
$email['port']          = 366;
$email['user']          = '[email protected]';
$email['pass']          = 'from password';
$email['from']          = 'From Name';
$email['reply']         = '[email protected]';
$email['replyname']     = 'Reply To Name';

$addresses_to_mail_to = '[email protected];[email protected]';
$email_subject = 'My Subject';
$email_body = '<html>Code Here</html>';
$who_is_receiving_name = 'John Smith';

$result = sendmail(
    $email_body,
    $email_subject,
    $addresses_to_mail_to,
    $who_is_receiving_name
);

var_export($result);


function sendmail($body, $subject, $to, $name, $attach = "") {

  global $email;
  $return = false;

  $mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
  $mail->IsSMTP(); // telling the class to use SMTP
  try {
    $mail->Host       = $email['host']; // SMTP server
//    $mail->SMTPDebug  = 2;                     // enables SMTP debug information (for testing)
    $mail->SMTPAuth   = true;                  // enable SMTP authentication
    $mail->Host       = $email['host']; // sets the SMTP server
    $mail->Port       = $email['port'];                    // set the SMTP port for the GMAIL server
    $mail->SMTPSecure = "tls";
    $mail->Username   = $email['user']; // SMTP account username
    $mail->Password   = $email['pass'];        // SMTP account password
    $mail->AddReplyTo($email['reply'], $email['replyname']);
    if(stristr($to,';')) {
      $totmp = explode(';',$to);
      foreach($totmp as $destto) {
        if(trim($destto) != "") {
          $mail->AddAddress(trim($destto), $name);
        }
      }
    } else {
      $mail->AddAddress($to, $name);
    }
    $mail->SetFrom($email['user'], $email['from']);
    $mail->Subject = $subject;
    $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
    $mail->MsgHTML($body);
    if(is_array($attach)) {
        foreach($attach as $attach_f) {
            if($attach_f != "") {
              $mail->AddAttachment($attach_f);      // attachment
            }
        }
    } else {
        if($attach != "") {
          $mail->AddAttachment($attach);      // attachment
        }
    }
    $mail->Send();
  } catch (phpmailerException $e) {
    $return = $e->errorMessage();
  } catch (Exception $e) {
    $return = $e->errorMessage();
  }

  return $return;
}

回答by user889030

if everything fails then for gmail you must turn on access to 3rd party apps to connect to ur gmail account.

如果一切都失败了,那么对于 Gmail,您必须打开对 3rd 方应用程序的访问权限才能连接到您的 Gmail 帐户。

https://www.google.com/settings/security/lesssecureapps// turn it on

https://www.google.com/settings/security/lesssecureapps// 打开它

回答by Musab ibnu Siraj

I fixed it ...

我修好了它 ...

https://github.com/PHPMailer/PHPMailer/tree/5.2-stable

https://github.com/PHPMailer/PHPMailer/tree/5.2-stable

<?php
require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

//$mail->SMTPDebug = 3;                               // Enable verbose debug output

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = '[email protected]';                 // SMTP username
$mail->Password = 'pass';                           // SMTP password
//$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 25;                                    // TCP port to connect to

$mail->setFrom('[email protected]', 'Mailer');
$mail->addAddress('[email protected]', 'User');     // Add a recipient

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

$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}

Turn on access and enjoy..! That is on Gmail account setting.

打开访问并享受..!那是 Gmail 帐户设置。

Turn On access

打开访问

回答by chobela

Try adding this line to your script. This worked for me!

尝试将此行添加到您的脚本中。这对我有用!

$mail->Mailer = “smtp”;

$mail->Mailer = “smtp”;

回答by Maki92

If you're using VPS and with httpd service, please check if your httpd_can_sendmail is on.

如果您使用的是 VPS 和 httpd 服务,请检查您的 httpd_can_sendmail 是否打开。

getsebool -a | grep mail

to set on

设置

setsebool -P httpd_can_sendmail on