【问题标题】:Send email using the GMail SMTP server from a PHP page从 PHP 页面使用 GMail SMTP 服务器发送电子邮件
【发布时间】:2010-10-17 06:40:07
【问题描述】:

我正在尝试从 PHP 页面通过 GMail 的 SMTP 服务器发送电子邮件,但出现此错误:

身份验证失败 [SMTP:SMTP 服务器不支持身份验证(代码:250,响应:mx.google.com 为您服务,[98.117.99.235] SIZE 35651584 8BITMIME STARTTLS ENHANCEDSTATUSCODES PIPELINING)]

有人可以帮忙吗?这是我的代码:

<?php
require_once "Mail.php";

$from = "Sandra Sender <sender@example.com>";
$to = "Ramona Recipient <ramona@microsoft.com>";
$subject = "Hi!";
$body = "Hi,\n\nHow are you?";

$host = "smtp.gmail.com";
$port = "587";
$username = "testtest@gmail.com";
$password = "testtest";

$headers = array ('From' => $from,
  'To' => $to,
  'Subject' => $subject);
$smtp = Mail::factory('smtp',
  array ('host' => $host,
    'port' => $port,
    'auth' => true,
    'username' => $username,
    'password' => $password));

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

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

【问题讨论】:

    标签: php email smtp gmail


    【解决方案1】:

    设置

    'auth' => false,
    

    另外,看看端口 25 是否有效。

    【讨论】:

    【解决方案2】:

    您的代码似乎没有使用 TLS (SSL),即necessary to deliver mail to Google (and using ports 465 or 587)

    你可以通过设置来做到这一点

    $host = "ssl://smtp.gmail.com";

    您的代码看起来很像 this example,它在主机名方案中引用 ssl://。

    【讨论】:

      【解决方案3】:

      Gmail需要465端口,也是phpmailer的代码

      【讨论】:

        【解决方案4】:

        问题中列出的代码需要两处改动

        $host = "ssl://smtp.gmail.com";
        $port = "465";
        

        SSL 连接需要端口 465。

        【讨论】:

          【解决方案5】:
          // Pear Mail Library
          require_once "Mail.php";
          
          $from = '<fromaddress@gmail.com>';
          $to = '<toaddress@yahoo.com>';
          $subject = 'Hi!';
          $body = "Hi,\n\nHow are you?";
          
          $headers = array(
              'From' => $from,
              'To' => $to,
              'Subject' => $subject
          );
          
          $smtp = Mail::factory('smtp', array(
                  'host' => 'ssl://smtp.gmail.com',
                  'port' => '465',
                  'auth' => true,
                  'username' => 'johndoe@gmail.com',
                  'password' => 'passwordxxx'
              ));
          
          $mail = $smtp->send($to, $headers, $body);
          
          if (PEAR::isError($mail)) {
              echo('<p>' . $mail->getMessage() . '</p>');
          } else {
              echo('<p>Message successfully sent!</p>');
          }
          

          【讨论】:

          • 什么是Mail.php??我从哪里得到这个文件?
          • 谁能给我一个链接,我可以在其中获取 Mail.php 文件。因为我试过了,它不起作用谢谢
          • 上面这个例子中的@符号在哪里?我没有看到一个!
          • 我认为 myaccount.gmail.com 与电子邮件标准中的 myaccount@gmail.com 相同。
          • 如果您指定了服务器,则不需要包含@gmail。只需输入myaccount 作为用户名。
          【解决方案6】:

          SwiftMailer 可以使用外部服务器发送电子邮件。

          这是一个展示如何使用 Gmail 服务器的示例:

          require_once "lib/Swift.php";
          require_once "lib/Swift/Connection/SMTP.php";
          
          //Connect to localhost on port 25
          $swift =& new Swift(new Swift_Connection_SMTP("localhost"));
          
          
          //Connect to an IP address on a non-standard port
          $swift =& new Swift(new Swift_Connection_SMTP("217.147.94.117", 419));
          
          
          //Connect to Gmail (PHP5)
          $swift = new Swift(new Swift_Connection_SMTP(
              "smtp.gmail.com", Swift_Connection_SMTP::PORT_SECURE, Swift_Connection_SMTP::ENC_TLS));
          

          【讨论】:

            【解决方案7】:
            <?php
            date_default_timezone_set('America/Toronto');
            
            require_once('class.phpmailer.php');
            //include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
            
            $mail             = new PHPMailer();
            
            $body             = "gdssdh";
            //$body             = eregi_replace("[\]",'',$body);
            
            $mail->IsSMTP(); // telling the class to use SMTP
            //$mail->Host       = "ssl://smtp.gmail.com"; // SMTP server
            $mail->SMTPDebug  = 1;                     // enables SMTP debug information (for testing)
                                                       // 1 = errors and messages
                                                       // 2 = messages only
            $mail->SMTPAuth   = true;                  // enable SMTP authentication
            $mail->SMTPSecure = "ssl";                 // sets the prefix to the servier
            $mail->Host       = "smtp.gmail.com";      // sets GMAIL as the SMTP server
            $mail->Port       = 465;                   // set the SMTP port for the GMAIL server
            $mail->Username   = "user@gmail.com";  // GMAIL username
            $mail->Password   = "password";            // GMAIL password
            
            $mail->SetFrom('contact@prsps.in', 'PRSPS');
            
            //$mail->AddReplyTo("user2@gmail.com', 'First Last");
            
            $mail->Subject    = "PRSPS password";
            
            //$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
            
            $mail->MsgHTML($body);
            
            $address = "user2@yahoo.co.in";
            $mail->AddAddress($address, "user2");
            
            //$mail->AddAttachment("images/phpmailer.gif");      // attachment
            //$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
            
            if(!$mail->Send()) {
              echo "Mailer Error: " . $mail->ErrorInfo;
            } else {
              echo "Message sent!";
            }
            
            ?>
            

            【讨论】:

            • 主机为什么要设置两次,哪一个是对的?
            • 从哪里获得 class.phpmailer.php 文件?仅粘贴代码没有太大帮助,请在代码中包含更多描述!
            • 虽然有些语法已经过时,但 PHPMailer 最终成为我的最佳解决方案,+1
            【解决方案8】:

            使用Swift mailer,通过Gmail凭据发送邮件非常容易:

            <?php
            require_once 'swift/lib/swift_required.php';
            
            $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, "ssl")
              ->setUsername('GMAIL_USERNAME')
              ->setPassword('GMAIL_PASSWORD');
            
            $mailer = Swift_Mailer::newInstance($transport);
            
            $message = Swift_Message::newInstance('Test Subject')
              ->setFrom(array('abc@example.com' => 'ABC'))
              ->setTo(array('xyz@test.com'))
              ->setBody('This is a test mail.');
            
            $result = $mailer->send($message);
            ?>
            

            【讨论】:

            • 这“第一个”工作,只是更改了 GMAIL_USERNAME、GMAIL_PASSWORD 以及 From 和 To 地址。没有其他解决方案对我有用。谢谢。
            • 我同意,swift mailer 是一种邮件解决方案,比处理梨要容易得多。不要忘记启用 PHP 的 php_openssl 扩展。
            • 使用 SwiftMailer 的不错的解决方案! +1
            • 啊。无法让 swiftmailer 工作。我不知道如何使用那个“composer”,所以我只是从 github 下载了 swiftmailer zip,然后我启用了 open_ssl,然后提供了我的 gmail 电子邮件和密码,但它仍然没有用。
            • 对不起我的愚蠢。您必须打开您的 gmail 帐户,因为有一封电子邮件告诉您启用“不太安全的应用程序”。然后它现在工作了呵呵
            【解决方案9】:

            我不推荐 Pear Mail。自 2010 年以来一直没有更新。另请阅读源文件;源代码几乎已经过时,以 PHP 4 风格编写,并且已经发布了许多错误/错误(谷歌它)。我正在使用 Swift Mailer。

            Swift Mailer 集成到任何用 PHP 5 编写的 Web 应用程序中,提供了一种灵活而优雅的面向对象的方法来发送具有多种功能的电子邮件。

            使用 SMTP、sendmail、postfix 或自定义传输发送电子邮件 你自己的实现。

            支持需要用户名和密码和/或加密的服务器。

            在不剥离请求数据的情况下防止标头注入攻击 内容。

            发送符合 MIME 的 HTML/多部分电子邮件。

            使用事件驱动插件自定义库。

            处理大型附件和内存不足的内联/嵌入图像 使用。

            它是一个免费的开源软件,您可以Download Swift Mailer 并上传到您的服务器。 (功能列表是从所有者网站复制的)。

            Gmail SSL/SMTP 和 Swift Mailer 的工作示例在这里...

            // Swift Mailer Library
            require_once '../path/to/lib/swift_required.php';
            
            // Mail Transport
            $transport = Swift_SmtpTransport::newInstance('ssl://smtp.gmail.com', 465)
                ->setUsername('username@gmail.com') // Your Gmail Username
                ->setPassword('my_secure_gmail_password'); // Your Gmail Password
            
            // Mailer
            $mailer = Swift_Mailer::newInstance($transport);
            
            // Create a message
            $message = Swift_Message::newInstance('Wonderful Subject Here')
                ->setFrom(array('sender@example.com' => 'Sender Name')) // can be $_POST['email'] etc...
                ->setTo(array('receiver@example.com' => 'Receiver Name')) // your email / multiple supported.
                ->setBody('Here is the <strong>message</strong> itself. It can be text or <h1>HTML</h1>.', 'text/html');
            
            // Send the message
            if ($mailer->send($message)) {
                echo 'Mail sent successfully.';
            } else {
                echo 'I am sure, your configuration are not correct. :(';
            }
            

            【讨论】:

            • 这不再有效,我总是收到返回消息“535-5.7.8 用户名和密码不被接受”。我的凭据很好,我已将“允许不太安全的应用程序”设置为 ON。有人知道解决这个问题吗?
            • Swift 在 PHP 5.x 中似乎不起作用 - 不理解 ??合并 - 只是爆炸。
            【解决方案10】:

            通过 Gmail 使用 phpMailer 库发送邮件 请从Github下载库文件

            <?php
            /**
             * This example shows settings to use when sending via Google's Gmail servers.
             */
            //SMTP needs accurate times, and the PHP time zone MUST be set
            //This should be done in your php.ini, but this is how to do it if you don't have access to that
            date_default_timezone_set('Etc/UTC');
            require '../PHPMailerAutoload.php';
            //Create a new PHPMailer instance
            $mail = new PHPMailer;
            //Tell PHPMailer to use SMTP
            $mail->isSMTP();
            //Enable SMTP debugging
            // 0 = off (for production use)
            // 1 = client messages
            // 2 = client and server messages
            $mail->SMTPDebug = 2;
            //Ask for HTML-friendly debug output
            $mail->Debugoutput = 'html';
            //Set the hostname of the mail server
            $mail->Host = 'smtp.gmail.com';
            // use
            // $mail->Host = gethostbyname('smtp.gmail.com');
            // if your network does not support SMTP over IPv6
            //Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
            $mail->Port = 587;
            //Set the encryption system to use - ssl (deprecated) or tls
            $mail->SMTPSecure = 'tls';
            //Whether to use SMTP authentication
            $mail->SMTPAuth = true;
            //Username to use for SMTP authentication - use full email address for gmail
            $mail->Username = "username@gmail.com";
            //Password to use for SMTP authentication
            $mail->Password = "yourpassword";
            //Set who the message is to be sent from
            $mail->setFrom('from@example.com', 'First Last');
            //Set an alternative reply-to address
            $mail->addReplyTo('replyto@example.com', 'First Last');
            //Set who the message is to be sent to
            $mail->addAddress('whoto@example.com', 'John Doe');
            //Set the subject line
            $mail->Subject = 'PHPMailer GMail SMTP test';
            //Read an HTML message body from an external file, convert referenced images to embedded,
            //convert HTML into a basic plain-text alternative body
            $mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__));
            //Replace the plain text body with one created manually
            $mail->AltBody = 'This is a plain-text message body';
            //Attach an image file
            $mail->addAttachment('images/phpmailer_mini.png');
            //send the message, check for errors
            if (!$mail->send()) {
                echo "Mailer Error: " . $mail->ErrorInfo;
            } else {
                echo "Message sent!";
            }
            

            【讨论】:

              【解决方案11】:

              我也有这个问题。我设置了正确的设置并启用了不太安全的应用程序,但它仍然无法正常工作。最后,我启用了这个https://accounts.google.com/UnlockCaptcha,它对我有用。

              【讨论】:

                【解决方案12】:

                要在 Ubuntu 中安装 PEAR 的 Mail.php,请运行以下命令集:

                    sudo apt-get install php-pear
                    sudo pear install mail
                    sudo pear install Net_SMTP
                    sudo pear install Auth_SASL
                    sudo pear install mail_mime
                

                【讨论】:

                  【解决方案13】:

                  我有一个针对没有“@gmail.com”后缀的 GSuite 帐户的解决方案。此外,我认为它适用于 @gmail.com 的 GSuite 帐户,但尚未尝试过。 首先,您应该有权为您的 GSuite 帐户更改“allos¿w 不太安全的应用程序”选项。如果您有权限(您可以检查帐户设置-> 安全性),那么您必须停用“两步因素身份验证”,转到页面末尾并设置为“是”以允许不太安全的应用程序。就这样。如果您没有更改这些选项的权限,则此线程的解决方案将不起作用。检查https://support.google.com/a/answer/6260879?hl=en 以更改“允许更少...”选项。

                  【讨论】:

                    【解决方案14】:

                    我尝试了@shasi kanth 提供的建议,但没有成功。我阅读了文档,并且几乎没有进行任何更改。因此,我设法使用此代码通过 Gmail 发送邮件,其中 vendor/autoload.php 由作曲家使用 composer require "swiftmailer/swiftmailer:^6.0" 获得:

                    <?php
                         require_once 'vendor/autoload.php';
                         $transport = (new Swift_SmtpTransport('smtp.gmail.com', 465, 'ssl'))->setUsername ('SendingMail')->setPassword ('Password');
                    
                         $mailer = new Swift_Mailer($transport);
                    
                         $message = (new Swift_Message('test'))
                          ->setFrom(['Sending mail'])
                          ->setTo(['Recipient mail'])
                          ->setBody('Message')
                      ;
                    
                         $result = $mailer->send($message);
                        ?>
                    

                    【讨论】:

                      【解决方案15】:

                      我知道这是一个老问题,但它仍然有效,我看到的所有答案都显示基本身份验证,已弃用。下面是一个示例,展示了如何使用带有 XOAUTH2 身份验证的 PHPMailer 通过 Google 的 Gmail 服务器使用 SMTP 发送电子邮件:

                      //Import PHPMailer classes into the global namespace
                      use PHPMailer\PHPMailer\PHPMailer;
                      use PHPMailer\PHPMailer\SMTP;
                      use PHPMailer\PHPMailer\OAuth;
                      //Alias the League Google OAuth2 provider class
                      use League\OAuth2\Client\Provider\Google;
                      
                      //SMTP needs accurate times, and the PHP time zone MUST be set
                      //This should be done in your php.ini, but this is how to do it if you don't have access to that
                      date_default_timezone_set('Etc/UTC');
                      
                      //Load dependencies from composer
                      //If this causes an error, run 'composer install'
                      require '../vendor/autoload.php';
                      
                      //Create a new PHPMailer instance
                      $mail = new PHPMailer();
                      
                      //Tell PHPMailer to use SMTP
                      $mail->isSMTP();
                      
                      //Enable SMTP debugging
                      //SMTP::DEBUG_OFF = off (for production use)
                      //SMTP::DEBUG_CLIENT = client messages
                      //SMTP::DEBUG_SERVER = client and server messages
                      $mail->SMTPDebug = SMTP::DEBUG_SERVER;
                      
                      //Set the hostname of the mail server
                      $mail->Host = 'smtp.gmail.com';
                      
                      //Set the SMTP port number:
                      // - 465 for SMTP with implicit TLS, a.k.a. RFC8314 SMTPS or
                      // - 587 for SMTP+STARTTLS
                      $mail->Port = 465;
                      
                      //Set the encryption mechanism to use:
                      // - SMTPS (implicit TLS on port 465) or
                      // - STARTTLS (explicit TLS on port 587)
                      $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
                      
                      //Whether to use SMTP authentication
                      $mail->SMTPAuth = true;
                      
                      //Set AuthType to use XOAUTH2
                      $mail->AuthType = 'XOAUTH2';
                      
                      //Fill in authentication details here
                      //Either the gmail account owner, or the user that gave consent
                      $email = 'someone@gmail.com';
                      $clientId = 'RANDOMCHARS-----duv1n2.apps.googleusercontent.com';
                      $clientSecret = 'RANDOMCHARS-----lGyjPcRtvP';
                      
                      //Obtained by configuring and running get_oauth_token.php
                      //after setting up an app in Google Developer Console.
                      $refreshToken = 'RANDOMCHARS-----DWxgOvPT003r-yFUV49TQYag7_Aod7y0';
                      
                      //Create a new OAuth2 provider instance
                      $provider = new Google(
                          [
                              'clientId' => $clientId,
                              'clientSecret' => $clientSecret,
                          ]
                      );
                      
                      //Pass the OAuth provider instance to PHPMailer
                      $mail->setOAuth(
                          new OAuth(
                              [
                                  'provider' => $provider,
                                  'clientId' => $clientId,
                                  'clientSecret' => $clientSecret,
                                  'refreshToken' => $refreshToken,
                                  'userName' => $email,
                              ]
                          )
                      );
                      
                      //Set who the message is to be sent from
                      //For gmail, this generally needs to be the same as the user you logged in as
                      $mail->setFrom($email, 'First Last');
                      
                      //Set who the message is to be sent to
                      $mail->addAddress('someone@gmail.com', 'John Doe');
                      
                      //Set the subject line
                      $mail->Subject = 'PHPMailer GMail XOAUTH2 SMTP test';
                      
                      //Read an HTML message body from an external file, convert referenced images to embedded,
                      //convert HTML into a basic plain-text alternative body
                      $mail->CharSet = PHPMailer::CHARSET_UTF8;
                      $mail->msgHTML(file_get_contents('contentsutf8.html'), __DIR__);
                      
                      //Replace the plain text body with one created manually
                      $mail->AltBody = 'This is a plain-text message body';
                      
                      //Attach an image file
                      $mail->addAttachment('images/phpmailer_mini.png');
                      
                      //send the message, check for errors
                      if (!$mail->send()) {
                          echo 'Mailer Error: ' . $mail->ErrorInfo;
                      } else {
                          echo 'Message sent!';
                      }
                      

                      参考:PHPMailer examples folder

                      【讨论】:

                        猜你喜欢
                        • 2016-09-07
                        • 2011-12-13
                        • 1970-01-01
                        • 2020-11-19
                        相关资源
                        最近更新 更多