使用GMail SMTP服务器从PHP页面发送电子邮件

时间:2022-09-04 18:14:10

I am trying to send an email via GMail's SMTP server from a PHP page, but I get this error:

我试图通过一个PHP页面通过GMail的SMTP服务器发送邮件,但是我得到了这个错误:

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)]

身份验证失败[SMTP: SMTP服务器不支持身份验证(代码:250,响应:mx.google.com,在您的服务上,[98.117.99.235]

Can anyone help? Here is my code:

谁能帮忙吗?这是我的代码:

<?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>");
 }
?>

12 个解决方案

#1


330  

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

#2


95  

Using Swift mailer, it is quite easy to send a mail through Gmail credentials:

使用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);
?>

#3


53  

Your code does not appear to be using TLS (SSL), which is necessary to deliver mail to Google (and using ports 465 or 587).

您的代码似乎没有使用TLS (SSL),这是将邮件发送到谷歌(并使用端口465或587)的必要条件。

You can do this by setting

可以通过设置来实现

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

$主机=“ssl:/ / smtp.gmail.com”;

Your code looks suspiciously like this example which refers to ssl:// in the hostname scheme.

您的代码看起来很像这个示例,它引用了主机名方案中的ssl://。

#4


32  

I don't recommend Pear Mail. It has not been updated since 2010. Also read the source files; the source code is almost outdated, written in PHP 4 style and many errors / bugs have been posted (Google it). I am using Swift Mailer.

我不推荐梨邮件。它自2010年以来就没有更新过。也要阅读源文件;源代码几乎已经过时,以PHP 4的风格编写,并且有许多错误/ bug被发布(谷歌it)。我使用的是Swift邮件。

Swift Mailer integrates into any web application written in PHP 5, offering a flexible and elegant object-oriented approach to sending emails with a multitude of features.

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

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

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

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.

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

Use event-driven plugins to customize the library.

使用事件驱动的插件来定制库。

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

处理大的附件和内联/嵌入式的低内存使用图像。

It is a free and open source you can Download Swift Mailer and upload to your server. (The feature list is copied from owner website).

这是一个免费的开放源码,你可以下载Swift邮件并上传至你的服务器。(功能列表是从所有者网站拷贝的)。

The working example of Gmail SSL/SMTP and Swift Mailer is here...

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. :(';
}

I hope this helps. Happy coding... :)

我希望这可以帮助。快乐的编码…:)

#5


28  

<?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!";
}

?>

#6


20  

SwiftMailer can send E-Mail using external servers.

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

here is an example that shows how to use a Gmail server:

下面是一个演示如何使用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


13  

The code as listed in the question needs two changes

问题中列出的代码需要做两个更改

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

Port 465 is required for an SSL connection.

SSL连接需要端口465。

#8


5  

Send Mail using phpMailer library through Gmail Please donwload library files from Github

使用phpMailer库通过Gmail发送邮件,请不要从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!";
}

#9


4  

Gmail requires port 465, and also it's the code from phpmailer :)

Gmail需要端口465,也是phpmailer:)

#10


3  

I had this problem also. I set the correct settings and have enabled less secure apps but it still did not work. Finally, I enabled this https://accounts.google.com/UnlockCaptcha, and it worked for me. I hope this helps someone.

我也有这个问题。我设置了正确的设置,并启用了不太安全的应用程序,但它仍然不起作用。最后,我启用了这个https://accounts.google.com/UnlockCaptcha,它对我很有用。我希望这能帮助某人。

#11


1  

To install PEAR's Mail.php in Ubuntu, run following set of commands:

安装梨的邮件。php在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

#12


-2  

Set

'auth' => false,

Also, see if port 25 works.

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

#1


330  

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

#2


95  

Using Swift mailer, it is quite easy to send a mail through Gmail credentials:

使用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);
?>

#3


53  

Your code does not appear to be using TLS (SSL), which is necessary to deliver mail to Google (and using ports 465 or 587).

您的代码似乎没有使用TLS (SSL),这是将邮件发送到谷歌(并使用端口465或587)的必要条件。

You can do this by setting

可以通过设置来实现

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

$主机=“ssl:/ / smtp.gmail.com”;

Your code looks suspiciously like this example which refers to ssl:// in the hostname scheme.

您的代码看起来很像这个示例,它引用了主机名方案中的ssl://。

#4


32  

I don't recommend Pear Mail. It has not been updated since 2010. Also read the source files; the source code is almost outdated, written in PHP 4 style and many errors / bugs have been posted (Google it). I am using Swift Mailer.

我不推荐梨邮件。它自2010年以来就没有更新过。也要阅读源文件;源代码几乎已经过时,以PHP 4的风格编写,并且有许多错误/ bug被发布(谷歌it)。我使用的是Swift邮件。

Swift Mailer integrates into any web application written in PHP 5, offering a flexible and elegant object-oriented approach to sending emails with a multitude of features.

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

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

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

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.

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

Use event-driven plugins to customize the library.

使用事件驱动的插件来定制库。

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

处理大的附件和内联/嵌入式的低内存使用图像。

It is a free and open source you can Download Swift Mailer and upload to your server. (The feature list is copied from owner website).

这是一个免费的开放源码,你可以下载Swift邮件并上传至你的服务器。(功能列表是从所有者网站拷贝的)。

The working example of Gmail SSL/SMTP and Swift Mailer is here...

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. :(';
}

I hope this helps. Happy coding... :)

我希望这可以帮助。快乐的编码…:)

#5


28  

<?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!";
}

?>

#6


20  

SwiftMailer can send E-Mail using external servers.

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

here is an example that shows how to use a Gmail server:

下面是一个演示如何使用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


13  

The code as listed in the question needs two changes

问题中列出的代码需要做两个更改

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

Port 465 is required for an SSL connection.

SSL连接需要端口465。

#8


5  

Send Mail using phpMailer library through Gmail Please donwload library files from Github

使用phpMailer库通过Gmail发送邮件,请不要从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!";
}

#9


4  

Gmail requires port 465, and also it's the code from phpmailer :)

Gmail需要端口465,也是phpmailer:)

#10


3  

I had this problem also. I set the correct settings and have enabled less secure apps but it still did not work. Finally, I enabled this https://accounts.google.com/UnlockCaptcha, and it worked for me. I hope this helps someone.

我也有这个问题。我设置了正确的设置,并启用了不太安全的应用程序,但它仍然不起作用。最后,我启用了这个https://accounts.google.com/UnlockCaptcha,它对我很有用。我希望这能帮助某人。

#11


1  

To install PEAR's Mail.php in Ubuntu, run following set of commands:

安装梨的邮件。php在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

#12


-2  

Set

'auth' => false,

Also, see if port 25 works.

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