Gmail 在PHPMailer上有问题吗

Gmail 在PHPMailer上有问题吗,gmail,php,Gmail,Php,我正在尝试使用PHPMailer发送gmail电子邮件。我跟着这个 为此,我设置了一个如下所示的函数: function sendEmail($email, $name) { $mail = new PHPMailer(); $mail->IsSMTP(); // send via SMTP //IsSMTP(); // send via SMTP I commented it cos it gives an error $mail->SMTPAuth

我正在尝试使用PHPMailer发送gmail电子邮件。我跟着这个

为此,我设置了一个如下所示的函数:

function sendEmail($email, $name) {
    $mail = new PHPMailer();
    $mail->IsSMTP(); // send via SMTP
    //IsSMTP(); // send via SMTP I commented it cos it gives an error
    $mail->SMTPAuth = true; // turn on SMTP authentication
    $mail->Username = 'email@gmail.com'; // Changed my email
    $mail->Password = "password";// Changed my password
    $mail->From = 'email@gmail.com';
    $mail->FromName = 'FROM NAME';


    $mail->AddAddress($email);

    $mail->IsHTML(true); // send as HTML
    $mail->Subject = "Subject";
    $mail->Body = "Body";

    if (!$mail->Send()) {
        return false;
    } else {
        return true;
    }
}
不幸的是,它不断返回false。您能告诉我代码有什么问题吗?

编辑:我得到的错误如下所示:

SMTP -> ERROR: Failed to connect to server: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

SMTP Error: Could not connect to SMTP host.
更新代码:

 $Mail = new PHPMailer();
    $Mail->IsSMTP(); // Use SMTP
    $Mail->Host = "smtp.gmail.com"; // Sets SMTP server
    $Mail->SMTPDebug = 2; // 2 to enable SMTP debug information 
    $Mail->SMTPAuth = TRUE; // enable SMTP authentication
    $Mail->SMTPSecure = "tls"; //Secure conection
    $Mail->Port = 587; // set the SMTP port
    $Mail->Username = EMAIL; // SMTP account username
    $Mail->Password = PASS; // SMTP account password
    $Mail->Priority = 1; // Highest priority - Email priority (1 = High, 3 = Normal, 5 = low)
    $Mail->CharSet = 'UTF-8';
    $Mail->Encoding = '8bit';
    $Mail->Subject = 'SUB';
    $Mail->ContentType = 'text/html; charset=utf-8\r\n';
    $Mail->From = EMAIL;
    $Mail->FromName = 'FROM NAME';
    $Mail->WordWrap = 900; // RFC 2822 Compliant for Max 998 characters per line

    $Mail->AddAddress($email); // To:
    $Mail->isHTML(TRUE);
    $Mail->Body = "Hi";
    $Mail->AltBody = "Hi";
    $Mail->Send();
    $Mail->SmtpClose();
试试看


只需替换为您的配置,设置require_一次('class.phpmailer.php');指向正确的位置并替换“contents.html”您的html模板

如果您选择不使用HTML模板,请使用此代码

<?php

$body ='Your HTML message should go here';

require_once('class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded

$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       = "smtp.gmail.com"; // SMTP server
  $mail->SMTPDebug  = 2;                     // enables SMTP debug information (for testing)
  $mail->SMTPAuth   = true;                  // enable SMTP authentication
  $mail->Host       = "smtp.gmail.com"; // sets the SMTP server
  $mail->Port       = 465;                    // set the SMTP port for the GMAIL server
  $mail->Username   = "yourname@yourdomain"; // SMTP account username
  $mail->Password   = "yourpassword";        // SMTP account password
  $mail->AddReplyTo('name@yourdomain.com', 'First Last');
  $mail->AddAddress('whoto@otherdomain.com', 'John Doe');
  $mail->SetFrom('name@yourdomain.com', 'First Last');
  $mail->AddReplyTo('name@yourdomain.com', 'First Last');
  $mail->Subject = 'This is a TEST message';
  $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
  $mail->MsgHTML($body);
  $mail->AddAttachment('images/phpmailer.gif');      // attachment
  $mail->AddAttachment('images/phpmailer_mini.gif'); // attachment
  $mail->Send();
  echo "Message Sent OK</p>\n";
} catch (phpmailerException $e) {
  echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
  echo $e->getMessage(); //Boring error messages from anything else!
}
?>

在此类问题中,在部署到生产环境之前,检查它在开发环境中的运行情况非常重要,因为有许多服务器问题可能与此问题有关

因此,在设置debug为true并检查收到的消息之前

$mail->SMTPDebug = 1;
也就是说,在这种情况下常见的服务器问题如下

  • PHP中缺少SSL支持。您必须启用它

  • 某种防火墙可能会阻止您连接到出站套接字。您可以使用PHP检查这一点

  • -

    $p=fsockopen('127.0.0.1',$errno,$errstr,5);
    如果(!$p)
    //端口已关闭或阻塞
    其他的
    //端口已打开并可用
    fclose(p美元)`
    
    您的代码不起作用,因为您没有将
    SMTPSecure
    选项设置为
    ssl
    ,这是
    gmail
    帐户所必需的

    include_once "/lib/phpmailer/PHPMailer.class.php";
    include_once "/lib/phpmailer/SMTP.class.php";
    include_once "/lib/phpmailer/POP3.class.php";
    
    $mail = new PHPMailer(true);
    $mail->IsSMTP();
    
    try {
        $mail->Host = "smtp.gmail.com"; 
        $mail->SMTPDebug = 2; 
        $mail->SMTPSecure = 'ssl'; //<----------------- You missed this 
        $mail->SMTPAuth = true; 
        $mail->Host = "smtp.gmail.com"; 
        $mail->Port = 465; // 
        $mail->Username = "xxxxxx@gmail.com";
        $mail->Password = "xxxxxx";
        $mail->AddAddress('to@example.com', 'John Doe');
        $mail->SetFrom('xxxxxx@gmail.com', 'First Last');
        $mail->Subject = 'This is a TEST message';
        $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
        $body = "To view the message, please use an HTML compatible email viewer!"; // automatically
        $mail->MsgHTML($body);
        $mail->Send();
        echo "Message Sent OK</p>\n";
    } catch ( phpmailerException $e ) {
        echo $e->errorMessage(); 
    } catch ( Exception $e ) {
        echo $e->getMessage(); 
    }
    

    下面是一个工作示例:

    <?php
    function SendMail( $ToEmail, $MessageHTML, $MessageTEXT ) {
      require_once ( 'class.phpmailer.php' ); // Add the path as appropriate
      $Mail = new PHPMailer();
      $Mail->IsSMTP(); // Use SMTP
      $Mail->Host        = "smtp.gmail.com"; // Sets SMTP server
      $Mail->SMTPDebug   = 2; // 2 to enable SMTP debug information
      $Mail->SMTPAuth    = TRUE; // enable SMTP authentication
      $Mail->SMTPSecure  = "tls"; //Secure conection
      $Mail->Port        = 587; // set the SMTP port
      $Mail->Username    = 'MyGmail@gmail.com'; // SMTP account username
      $Mail->Password    = 'MyGmailPassword'; // SMTP account password
      $Mail->Priority    = 1; // Highest priority - Email priority (1 = High, 3 = Normal, 5 = low)
      $Mail->CharSet     = 'UTF-8';
      $Mail->Encoding    = '8bit';
      $Mail->Subject     = 'Test Email Using Gmail';
      $Mail->ContentType = 'text/html; charset=utf-8\r\n';
      $Mail->From        = 'MyGmail@gmail.com';
      $Mail->FromName    = 'GMail Test';
      $Mail->WordWrap    = 900; // RFC 2822 Compliant for Max 998 characters per line
    
      $Mail->AddAddress( $ToEmail ); // To:
      $Mail->isHTML( TRUE );
      $Mail->Body    = $MessageHTML;
      $Mail->AltBody = $MessageTEXT;
      $Mail->Send();
      $Mail->SmtpClose();
    
      if ( $Mail->IsError() ) { // ADDED - This error checking was missing
        return FALSE;
      }
      else {
        return TRUE;
      }
    }
    
    $ToEmail = 'Name@example.com';
    $ToName  = 'Name';
    
    $Send = SendMail( $ToEmail, $MessageHTML, $MessageTEXT );
    if ( $Send ) {
      echo "<h2> Sent OK</h2>";
    }
    else {
      echo "<h2> ERROR</h2>";
    }
    die;
    ?>
    

    试试这个……)

    我已从本地主机从xampp服务器发送邮件

    这个代码对我来说非常有用

    1:将PHP读取器从

    2:转到xampp并搜索php.ini

    3在php.ini搜索中

    ;extension=php_openssl.dll    
     remove(;)       
     extension=php_openssl.dll 
    
    然后保存并重新启动p.c.的工作

    <%php <br/>
    require_once("C:\\xampp\\phpMailer\\PHPMailer-master\\class.phpmailer.php"); <br/>
    
    $mail = new PHPMailer(); <br/>
    $mail->IsSMTP();  // telling the class to use SMTP    <br/>
    $mail->SMTPAuth = true;         // Enable SMTP authentication  <br/>
    $mail->SMTPSecure = 'ssl' ;   <br/>
    $mail->Host    = "smtp.gmail.com" ;// SMTP server <br/>
    $mail->Port = 465; // or 587   <br/>
    
    $mail->Username = 'senderemailid@gmail.com';    // SMTP username <br/>
    $mail->Password = 'senderpassword';     // SMTP password   <br/>
    
    $mail -> IsHTML(true);  <br/>
    $mail->From    = 'senderemailid@gmail.com'; <br/>
    $mail->FromName = 'sendername';   <br/>
    $mail->addAddress('receiveremailid@domain.com','receivername');  <br/>
    
    $mail->WordWrap = 50;  <br/>
    
    $mail->Subject  = "This mail send from  PhP code xampp"; <br/>
    $mail->Body     = "Hi! \n\n This is my first e-mail sent through PHPMailer."; <br/>
    
    if(!$mail->Send()) {   <br/>
    echo 'Message was not sent.';   <br/>
    echo 'Mailer error: ' . $mail->ErrorInfo;  <br/>
    
    } else    <br/>
     {   <br/>
    echo 'Message has been sent.';  <br/>
    }  <br/>
    ?>  <br/>
    
    IsSMTP();//告诉类使用SMTP
    $mail->SMTPAuth=true;//启用SMTP身份验证
    $mail->SMTPSecure='ssl'
    $mail->Host=“smtp.gmail.com”;//SMTP服务器
    $mail->Port=465;//或587
    $mail->Username=senderemailid@gmail.com'; // SMTP用户名
    $mail->Password='senderpassword';//SMTP密码
    $mail->IsHTML(true)
    $mail->Fromsenderemailid@gmail.com';
    $mail->FromName='sendername'
    $mail->addAddress('receiveremailid@domain.com“,”接收方名称“)
    $mail->WordWrap=50
    $mail->Subject=“此邮件从PhP代码xampp发送”
    $mail->Body=“嗨!\n\n这是我第一封通过PHPMailer发送的电子邮件。”
    如果(!$mail->Send()){
    echo“未发送消息”。;
    回显“邮件错误:”。$mail->ErrorInfo;
    }否则
    {
    回显“消息已发送”。;
    }
    ?>

    2019用Gmail更新phpMailer

    我知道这是一个老问题,但它仍然出现在谷歌,我需要更新这个问题的答案

    如果您遇到phpmailer的问题(很多人都遇到过),即当您尝试使用gmail的SMTP时,phpmailer仅在注释掉
    IsSMTP()
    时才起作用,那么下面就是原因

    当您注释掉
    IsSMTP()
    时,您告诉phpmailer不要使用SMTP,默认情况下,phpmailer会将请求发送到本地
    mail()
    。如果您查看此时发送的电子邮件,并查看电子邮件的标题,您将看到它来自您的本地服务器,而不是您试图发送它的地址/域。因此,是的,注释掉
    IsSMTP()
    会使它工作,但事实并非如此。从本地服务器发送未正确设置的邮件很可能会导致您的电子邮件成为垃圾邮件

    那么我该如何解决这个问题

    简单明了如果您使用的是旧版本的phpmailer,则需要更新的版本。最简单的方法是如何从地址设置
    。如果它看起来像这样
    $mail->From=”name@example.com“
    那么您使用的是旧版本

    phpmailer的最新版本将From定义为
    $mail->setFrom(“name@example.com“,“第一个最后一个”)
    。如果您看到了这一点,那么您正在使用更新版本的phpmailer

    如何正确操作并真正使其工作

  • 请确保防火墙上有587的TCP输出端口

  • SMTP Gmail只适用于tls/587,而不适用于ssl/465(ssl是20世纪90年代的标准)

  • 确保您在gmail中设置正确。如果您使用的是G套件帐户,则必须让管理员启用它(如果尚未启用)

  • (是的,它确实起作用,如果不起作用,那么你这边就出了问题)

  • 如何安装phpmailer

    首先是phpmailer的最新版本

    有两种安装方法。作曲家或手册。你所需要的手动方式是

    use PHPMailer\PHPMailer\PHPMailer; <-- make sure these are not in a function
    use PHPMailer\PHPMailer\Exception;
    
    require 'path/src/Exception.php';
    require 'path/src/PHPMailer.php';
    require 'path/src/SMTP.php';
    

    使用PHPMailer\PHPMailer\PHPMailer;您是否在PHP.ini中设置了服务器上的SMTP设置?在服务器端检查SMTP设置的代码没有问题!您是否设置了
    $mail->Host='smtp.gmail.com'$邮件->端口=465您是否使用telnet进行了测试?确保无需php即可连接。只是想缩小问题的范围。如果您可以通过telnet而不是php连接到端口587,那么我们知道这是一个php配置问题。如果你不能,那是防火墙问题或其他网络问题。是的,如果你能通过telnet连接,那肯定不是防火墙问题。现在我们只需要找出是什么阻止php连接到同一台计算机上。我已经更新了上面的代码,因此它不包含正确的GMil设置
    $mail->Port=26
    。我还插入了正确的SMTP设置。您是否运行此代码,它是否适用于您?首先,谢谢你的回复。我已经添加了SMTPDebug标志
    SMTP -> FROM SERVER:220 mx.google.com ESMTP 20sm6345523qek.6
    SMTP -> FROM SERVER: 250-mx.google.com at your service, [181.155.13.39]
                         250-SIZE 35882577
                         250-8BITMIME
                         250-STARTTLS
                         250 ENHANCEDSTATUSCODES
    SMTP -> FROM SERVER:220 2.0.0 Ready to start TLS
    SMTP -> FROM SERVER: 250-mx.google.com at your service, [181.155.13.39]
                         250-SIZE 35882577
                         250-8BITMIME
                         250-AUTH LOGIN PLAIN XOAUTH XOAUTH2
                         250 ENHANCEDSTATUSCODES
    SMTP -> FROM SERVER:250 2.1.0 OK 20sm6345523qek.6
    SMTP -> FROM SERVER:250 2.1.5 OK 20sm6345523qek.6
    SMTP -> FROM SERVER:354 Go ahead 20sm6345523qek.6
    SMTP -> FROM SERVER:250 2.0.0 OK 1353474062 20sm6345523qek.6
    SMTP -> FROM SERVER:221 2.0.0 closing connection 20sm6345523qek.6
    
    $mail = new PHPMailer();
    
                    // Set up SMTP
                    $mail->IsSMTP();                // Sets up a SMTP connection
                    $mail->SMTPDebug  = 0;          // This will print debugging info
                    $mail->SMTPAuth = true;         // Connection with the SMTP does require authorization
                    $mail->SMTPSecure = "tls";      // Connect using a TLS connection
                    $mail->Host = "smtp.gmail.com";
                    $mail->Port = 587;
                    $mail->Encoding = '7bit';       // SMS uses 7-bit encoding
                    $mail->IsHTML(true);            // Set email format to HTML
    
                    // Authentication
                    $mail->Username   = "xxx@xxx.xxx.xx"; // Login
                    $mail->Password   = "xxxxxx"; // Password
    
                    //$to=
                    $to = "zzz@zzz.zzz.zz";
                    $mail->Subject = "Outstanding Balance Notification ";     // Subject (which isn't required)
                    $mail->Body =  "Dear Sir / Madam";
                    $mail->FromName = "stackoverflow";
                    $mail->From = "noreply@xxx.xxx.xx";
    
                    $mail->AddAddress($row["Email1"]);
    
    ;extension=php_openssl.dll    
     remove(;)       
     extension=php_openssl.dll 
    
    <%php <br/>
    require_once("C:\\xampp\\phpMailer\\PHPMailer-master\\class.phpmailer.php"); <br/>
    
    $mail = new PHPMailer(); <br/>
    $mail->IsSMTP();  // telling the class to use SMTP    <br/>
    $mail->SMTPAuth = true;         // Enable SMTP authentication  <br/>
    $mail->SMTPSecure = 'ssl' ;   <br/>
    $mail->Host    = "smtp.gmail.com" ;// SMTP server <br/>
    $mail->Port = 465; // or 587   <br/>
    
    $mail->Username = 'senderemailid@gmail.com';    // SMTP username <br/>
    $mail->Password = 'senderpassword';     // SMTP password   <br/>
    
    $mail -> IsHTML(true);  <br/>
    $mail->From    = 'senderemailid@gmail.com'; <br/>
    $mail->FromName = 'sendername';   <br/>
    $mail->addAddress('receiveremailid@domain.com','receivername');  <br/>
    
    $mail->WordWrap = 50;  <br/>
    
    $mail->Subject  = "This mail send from  PhP code xampp"; <br/>
    $mail->Body     = "Hi! \n\n This is my first e-mail sent through PHPMailer."; <br/>
    
    if(!$mail->Send()) {   <br/>
    echo 'Message was not sent.';   <br/>
    echo 'Mailer error: ' . $mail->ErrorInfo;  <br/>
    
    } else    <br/>
     {   <br/>
    echo 'Message has been sent.';  <br/>
    }  <br/>
    ?>  <br/>
    
    use PHPMailer\PHPMailer\PHPMailer; <-- make sure these are not in a function
    use PHPMailer\PHPMailer\Exception;
    
    require 'path/src/Exception.php';
    require 'path/src/PHPMailer.php';
    require 'path/src/SMTP.php';
    
    <?php
    /**
     * This example shows settings to use when sending via Google's Gmail servers.
     * This uses traditional id & password authentication - look at the gmail_xoauth.phps
     * example to see how to use XOAUTH2.
     * The IMAP section shows how to save this message to the 'Sent Mail' folder using IMAP commands.
     */
    
    //Import PHPMailer classes into the global namespace
    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\Exception;
    
    require 'path/src/Exception.php';
    require 'path/src/PHPMailer.php';
    require 'path/src/SMTP.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;
    
    //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'), __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!";
        //Section 2: IMAP
        //Uncomment these to save your message in the 'Sent Mail' folder.
        #if (save_mail($mail)) {
        #    echo "Message saved!";
        #}
    }
    
    //Section 2: IMAP
    //IMAP commands requires the PHP IMAP Extension, found at: https://php.net/manual/en/imap.setup.php
    //Function to call which uses the PHP imap_*() functions to save messages: https://php.net/manual/en/book.imap.php
    //You can use imap_getmailboxes($imapStream, '/imap/ssl') to get a list of available folders or labels, this can
    //be useful if you are trying to get this working on a non-Gmail IMAP server.
    function save_mail($mail)
    {
        //You can change 'Sent Mail' to any other folder or tag
        $path = "{imap.gmail.com:993/imap/ssl}[Gmail]/Sent Mail";
    
        //Tell your server to open an IMAP connection using the same username and password as you used for SMTP
        $imapStream = imap_open($path, $mail->Username, $mail->Password);
    
        $result = imap_append($imapStream, $path, $mail->getSentMIMEMessage());
        imap_close($imapStream);
    
        return $result;
    }
    ?>