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

Send email using the GMail SMTP server from a PHP page

我试图通过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)]

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?php
require_once"Mail.php";

$from ="Sandra Sender <[email protected]>";
$to ="Ramona Recipient <[email protected]>";
$subject ="Hi!";
$body ="Hi,

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Pear Mail Library
require_once"Mail.php";

$from = '<[email protected]>';
$to = '<[email protected]>';
$subject = 'Hi!';
$body ="Hi,

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


您的代码似乎没有使用tls(ssl),这是向Google传递邮件所必需的(并使用端口465或587)。

你可以通过设置

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

您的代码看起来可疑地像这个例子,它在主机名方案中引用了ssl/。


我不推荐Pearmail。自2010年以来未更新。同时读取源文件;源代码几乎过时,用php 4样式编写,并且发布了许多错误/错误(google it)。我用的是斯威夫特邮递员。

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

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.

它是一个免费的开源软件,你可以下载Swift邮件并上传到你的服务器。(功能列表从所有者网站复制)。

下面是gmail ssl/smtp和swift mailer的工作示例…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 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 message itself. It can be text or HTML.', 'text/html');

// Send the message
if ($mailer->send($message)) {
    echo 'Mail sent successfully.';
} else {
    echo 'I am sure, your configuration are not correct. :(';
}

我希望这有帮助。快乐编码…:)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?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!";
}

?>


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

下面是一个演示如何使用Gmail服务器的示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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));


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

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

SSL连接需要端口465。


通过gmail使用phpmailer库发送邮件请不要从GitHub加载库文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?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!";
}

要在Ubuntu中安装pear的mail.php,请运行以下命令集:

1
2
3
4
5
    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


gmail需要端口465,这也是phpmailer的代码:)


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


我为没有"@gmail.com"sufix的gsuite帐户提供了解决方案。另外,我认为这对gsuite的@gmail.com账户有效,但还没有尝试过。首先,您应该具有更改选项"allos"的权限。为您的GSuite帐户提供"不太安全的应用程序"。如果您有权限(您可以签入帐户设置->安全),那么您必须停用"两步因素身份验证",转到页面的末尾,并将允许不太安全的应用程序设置为"是"。这就是全部。如果您没有更改这些选项的特权,此线程的解决方案将无法工作。查看https://support.google.com/a/answer/6260879?hl=en更改"允许更少…"选项。


集合

1
'auth' => false,

另外,查看端口25是否工作。