2015-05-19 5 views
0

Привет Я новичок в PHPMailer и SMTP-серверов .. вот мой код:как я могу отправить почту с помощью PHPMailer через GMAIL SMTP сервер

require 'class/PHPMailerAutoload.php'; 

    $mail = new PHPMailer(); // create a new object 
    $mail->IsSMTP(); // enable SMTP 
    $mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only 
    $mail->SMTPAuth = true; // authentication enabled 
    $mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail 
    $mail->Host = "smtp.gmail.com"; 
    $mail->Port = 465; // or 587 
    $mail->IsHTML(true); 
    $mail->Username = "[email protected]"; 
    $mail->Password = "gmailpw"; 
    $mail->SetFrom("[email protected]"); 
    $mail->Subject = "Test"; 
    $mail->Body = "hello"; 
    $mail->AddAddress("[email protected]"); 
    if(!$mail->Send()){ 
      echo "Mailer Error: " . $mail->ErrorInfo; 
    } else { 
    echo "Message has been sent"; 
    } 

, когда я пытаюсь запустить программу, вернуть ошибку сообщение:

Ошибка SMTP connect(). https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

Я действительно не знаю, что это проблема я надеюсь, что кто-то может помочь.

Обновление: вот полное сообщение об ошибке вот полное сообщение об ошибке.

2015-05-19 07:28:50 CLIENT -> SERVER: EHLO localhost 
2015-05-19 07:28:50 CLIENT -> SERVER: AUTH LOGIN 
2015-05-19 07:28:50 CLIENT -> SERVER: Y2FtcHVzbWVzc2FnaW5nLmRwY0BnbWFpbC5jb20= 
2015-05-19 07:28:50 CLIENT -> SERVER: ODA1Q01TdXBwb3J0 
2015-05-19 07:28:51 SMTP ERROR: Password command failed: 534-5.7.14 Please log in via your web browser and 534-5.7.14 then try again. 534-5.7.14 Learn more at 534 5.7.14 https://support.google.com/mail/bin/answer.py?answer=78754 t7sm7761459oie.22 - gsmtp 
2015-05-19 07:28:51 SMTP Error: Could not authenticate. 
2015-05-19 07:28:51 CLIENT -> SERVER: QUIT 2015-05-19 07:28:52 
+0

возможно дубликат [Невозможно отправить электронную почту через Gmail с помощью PHPMailer \ _v5.1] (http://stackoverflow.com/questions/2098718/unable-to-send-email-through-gmail -using-phpmailer-v5-1) – vps

+0

еще. Нужно ли мне настроить мою учетную запись GMAIL в качестве SMTP-сервера? извините за вопрос новичков. Благодаря! – JCP

+0

Здесь уже много похожих вопросов, пожалуйста, ищите. – vps

ответ

1
<?php 

//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'; 

//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'), 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!"; 
} 
+0

Хотя это рекомендуемый сейчас способ отправки через gmail с помощью PHPMailer, он все еще ломается в том, что OP говорит, потому что система auth Google нарушает его, поэтому это не ответ. – Synchro

+0

Почему? Он отлично работает у меня? – DesignStudios

+0

Вам просто повезло - Google изменил способ управления auth, особенно если вы используете приложения Google для бизнеса. Если в вопросе вы найдете ссылку на устранение неполадок, вы увидите объяснение. – Synchro

Смежные вопросы