2009-04-03 1 views
342

Я пытаюсь отправить почту через SMTP-сервер в Gmail из PHP-страницы, но я получаю эту ошибку:Отправить по электронной почте с помощью сервера GMail SMTP с PHP страницы

authentication failure [SMTP: SMTP server does no support authentication (code: 250, response: mx.google.com at your service, [98.117.99.235] SIZE 35651584 8BITMIME STARTTLS ENHANCEDSTATUSCODES PIPELINING)]

Может кто-нибудь помочь? Вот мой код:

<?php 
require_once "Mail.php"; 

$from = "Sandra Sender <[email protected]>"; 
$to = "Ramona Recipient <[email protected]>"; 
$subject = "Hi!"; 
$body = "Hi,\n\nHow are you?"; 

$host = "smtp.gmail.com"; 
$port = "587"; 
$username = "[email protected]"; 
$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>"); 
} 
?> 

ответ

326
// Pear Mail Library 
require_once "Mail.php"; 

$from = '<[email protected]>'; 
$to = '<[email protected]>'; 
$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' => '[email protected]', 
     'password' => 'passwordxxx' 
    )); 

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

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

что такое 'Mail.php' ?? где я могу получить этот файл? –

+75

Он использует пакет [Pear Mail] (http://pear.php.net/package/Mail/docs). – Xavi

+17

может кто-нибудь, пожалуйста, дать мне ссылку, где я могу получить файл Mail.php. Потому что я попробовал, и это не сработает. Спасибо. – Yoosuf

-2

Set

'auth' => false, 

Кроме того, видеть, если порт 25 работ.

+2

Это не будет - Google требует доставки на 465 или 587. См http://mail.google.com/support /bin/answer.py?hl=en&answer=13287. – crb

4

Gmail требует порта 465, а также это код из PHPMailer :)

12

код, перечисленные в вопросе необходимы два изменения

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

порт 465 требуется для подключения к SSL.

20

SwiftMailer может отправлять E-Mail с помощью внешних серверов.

здесь пример, который показывает, как использовать сервер 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)); 
26
<?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 = "[email protected]"; // GMAIL username 
$mail->Password = "password";   // GMAIL password 

$mail->SetFrom('[email protected]', 'PRSPS'); 

//$mail->AddReplyTo("[email protected]', '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 = "[email protected]"; 
$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!"; 
} 

?> 
+0

Почему вы устанавливаете хост дважды и какой из них правильный? –

+1

Я отредактировал ответ. Happy Coding :) –

+0

Где я могу получить файл class.phpmailer.php? Вклеивание кода только не так полезно PLS включать больше описания на код тоже! – GeneCode

92

Использование 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('[email protected]' => 'ABC')) 
    ->setTo(array('[email protected]')) 
    ->setBody('This is a test mail.'); 

$result = $mailer->send($message); 
?> 
+2

Это сработало «до первого», просто изменив GMAIL_USERNAME, GMAIL_PASSWORD и адреса From и To. Никакое другое решение не работало для меня. Благодарю. –

+7

Я согласен, быстрая почтовая рассылка - это решение для отправки почты, которое намного проще, чем возиться с грушей. Не забудьте включить расширение PHP php_openssl. – Soth

+1

Хорошее решение с использованием SwiftMailer! +1 –

31

I не рекомендую грушевую почту. Он не обновлялся с 2010 года. Также читайте исходные файлы; исходный код почти устарел, написан в стиле PHP 4, и многие ошибки/ошибки были опубликованы (Google). Я использую Swift Mailer.

Swift Mailer интегрирован в любое веб-приложение, написанное на PHP 5, предлагая гибкий и элегантный объектно-ориентированный подход к отправке электронных писем с множеством функций.

Send emails using SMTP, sendmail, postfix or a custom Transport implementation of your own.

Support servers that require username & password and/or encryption.

Protect from header injection attacks without stripping request data content.

Send MIME compliant HTML/multipart emails.

Use event-driven plugins to customize the library.

Handle large attachments and inline/embedded images with low memory use.

Это бесплатно и с открытым исходным кодом вы можете 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('[email protected]') // 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('[email protected]' => 'Sender Name')) // can be $_POST['email'] etc... 
    ->setTo(array('[email protected]' => '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. :('; 
} 

Я надеюсь, что это помогает. Счастливое кодирование ...:)

+1

Это больше не работает, я всегда получаю сообщение «535-5.7.8 Username и пароль не принимается ». Мои учетные данные в порядке, и я установил «Разрешить менее безопасные приложения» в положение «ВКЛ». Кто-нибудь знает об этом? – AndrewB

+0

Swift, похоже, не работает в PHP 5.x - не понимает ?? сливается - просто взрывается. – HerrimanCoder

4

Написать письмо с использованием библиотеки PHPMailer через Gmail Пожалуйста DONWLOAD библиотечные файлы из 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 = "[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!"; 
} 
3

Я имел эту проблему тоже. Я установил правильные настройки и включил менее безопасные приложения, но он все еще не работает. Наконец, я включил этот https://accounts.google.com/UnlockCaptcha, и это сработало для меня. Я надеюсь, что это помогает кому-то.

+1

Это работает, спасибо – pokeybit

1

Чтобы установить Mail.php PEAR в Ubuntu, запустите следующий набор команд:

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 
Смежные вопросы