Проблемы с PHPMailer - программирование
Подтвердить что ты не робот

Проблемы с PHPMailer

Я пытаюсь использовать 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 protected]'; // Changed my email
    $mail->Password = "password";// Changed my password
    $mail->From = '[email protected]';
    $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();
4b9b3361

Ответ 1

Вот рабочий пример:

<?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    = '[email protected]'; // 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        = '[email protected]';
  $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 = '[email protected]';
$ToName  = 'Name';

$Send = SendMail( $ToEmail, $MessageHTML, $MessageTEXT );
if ( $Send ) {
  echo "<h2> Sent OK</h2>";
}
else {
  echo "<h2> ERROR</h2>";
}
die;
?>

Я пробовал этот script и не испытывал проблем с отправкой нескольких сообщений.

ОБНОВЛЕНО:

Это типичный ответ Gmail на успех:

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

Ответ 2

Ваш код не работает, потому что вы не установили для параметра SMTPSecure значение ssl, которое требуется для gmail account

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 = "[email protected]";
    $mail->Password = "xxxxxx";
    $mail->AddAddress('[email protected]', 'John Doe');
    $mail->SetFrom('[email protected]', '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(); 
}

Выход

SMTP -> FROM SERVER:220 mx.google.com ESMTP q22sm2927759bkv.16 
SMTP -> FROM SERVER: 250-mx.google.com at your service, [62.173.54.190] 250-SIZE 35882577 250-8BITMIME 250-AUTH LOGIN PLAIN XOAUTH XOAUTH2 250 ENHANCEDSTATUSCODES 
SMTP -> FROM SERVER:250 2.1.0 OK q22sm2927759bkv.16 
SMTP -> FROM SERVER:250 2.1.5 OK q22sm2927759bkv.16 
SMTP -> FROM SERVER:354 Go ahead q22sm2927759bkv.16 
SMTP -> FROM SERVER:250 2.0.0 OK 1353341553 q22sm2927759bkv.16 
Message Sent OK

Ответ 3

При таких проблемах важно проверить, как он работает в среде разработки, прежде чем развертывать его на производство, поскольку существует множество проблем с сервером, которые могут быть связаны с проблемой.

Из-за этого перед тем, как установить отладку в true и проверьте полученные сообщения.

$mail->SMTPDebug = 1;

Тем не менее, общие проблемы с сервером в таких ситуациях следующие.

  • Отсутствие поддержки SSL в PHP. Вы должны включить его.

  • Какой-то брандмауэр может блокировать вас от подключения к исходящим сокетам. Вы можете проверить это с помощью PHP.

-

$p = fsockopen( '127.0.0.1', <port number>, $errno, $errstr, 5 );
if ( !$p )
    // port is closed or blocked
else
    // port is open and available
    fclose( $p );`

Ответ 4

Try...

<?php
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   = "[email protected]"; // SMTP account username
  $mail->Password   = "yourpassword";        // SMTP account password
  $mail->AddReplyTo('[email protected]', 'First Last');
  $mail->AddAddress('[email protected]', 'John Doe');
  $mail->SetFrom('[email protected]', 'First Last');
  $mail->AddReplyTo('[email protected]', '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($obdy);
  $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!
}
?>

Просто замените конфигурацию, установите require_once ('class.phpmailer.php'); чтобы указать на нужное место и заменить "content.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   = "[email protected]"; // SMTP account username
  $mail->Password   = "yourpassword";        // SMTP account password
  $mail->AddReplyTo('[email protected]', 'First Last');
  $mail->AddAddress('[email protected]', 'John Doe');
  $mail->SetFrom('[email protected]', 'First Last');
  $mail->AddReplyTo('[email protected]', '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!
}
?>

Ответ 5

$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   = "[email protected]"; // Login
                $mail->Password   = "xxxxxx"; // Password

                //$to=
                $to = "[email protected]";
                $mail->Subject = "Outstanding Balance Notification ";     // Subject (which isn't required)
                $mail->Body =  "Dear Sir / Madam";
                $mail->FromName = "stackoverflow";
                $mail->From = "[email protected]";

                $mail->AddAddress($row["Email1"]);

попробуйте это.:)

Ответ 6

Я отправил почту с сервера xampp из localhost

Этот код отлично работает для меня

1: загрузка phpmailer вниз с https://github.com/PHPMailer/PHPMailer

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 = '[email protected]';    // SMTP username <br/>
$mail->Password = 'senderpassword';     // SMTP password   <br/>

$mail -> IsHTML(true);  <br/>
$mail->From    = '[email protected]'; <br/>
$mail->FromName = 'sendername';   <br/>
$mail->addAddress('[email protected]','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/>

Ответ 7

2019 Обновление phpMailer с помощью Gmail

Я знаю, что это старый вопрос, но он все еще возникает в Google, и мне нужно обновить ответ на этот вопрос.

Если у вас возникла проблема (с которой многие сталкиваются) с phpmailer, то он работает только тогда, когда вы комментируете IsSMTP() при попытке использовать SMTP gmail, вот почему.

Когда вы комментируете IsSMTP() вы говорите phpmailer НЕ ИСПОЛЬЗОВАТЬ SMTP, который по умолчанию phpmailer будет отправлять запрос на вашу локальную mail(). Если вы посмотрите на письма, отправленные в этот момент, и посмотрите на заголовок письма, вы увидите, что оно приходит с вашего локального сервера, а не с адреса/домена, на который вы пытаетесь его отправить. Так что да, комментирование IsSMTP() заставит его работать, но на самом деле это не так. А отправка с вашего локального сервера, который не настроен правильно, скорее всего, приведет к тому, что ваши электронные письма станут спамом.

Так как мне это исправить

Просто и понятно, что вы, скорее всего, используете старую версию phpmailer, вам нужна более новая версия. Самый простой способ сказать это, как вы установите From адреса. Если это выглядит так $mail->From = "[email protected]" то вы используете старую версию.

Новейшие версии phpmailer определяют From как $mail->setFrom("[email protected]", "First Last"). Если вы видите это, то вы используете более новую версию phpmailer.

Как сделать это правильно и реально заставить это работать

  1. Пожалуйста, убедитесь, что у вас есть порт TCP OUT для 587 на брандмауэре

  2. SMTP Gmail будет работать только с tls/587, а не с ssl/465 (ssl - это 1990-е годы)

  3. Убедитесь, что в gmail правильно настроены менее безопасные приложения. Если вы используете учетную запись G Suite, то вам нужно, чтобы администратор включил ее, если это еще не сделано.

  4. Это прекрасный пример того, как использовать новый phpmailer с gmail smtp (и да, он работает, если нет, то что-то не так с вашей стороны)

Как установить phpmailer

Сначала скачайте последнюю версию phpmailer

Есть 2 способа установить его. Композитор или руководство. Ручной способ все, что вам нужно, это

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 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 = "[email protected]";

//Password to use for SMTP authentication
$mail->Password = "yourpassword";

//Set who the message is to be sent from
$mail->setFrom('[email protected]', 'First Last');

//Set an alternative reply-to address
$mail->addReplyTo('[email protected]', 'First Last');

//Set who the message is to be sent to
$mail->addAddress('[email protected]', '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;
}
?>