PHP邮件使用Gmail

11

在我的PHP Web应用程序中,当某些错误发生时,我希望通过电子邮件通知。我想使用我的Gmail帐户来发送这些邮件。如何实现?

2个回答

10

Gmail的SMTP服务器需要非常特定的配置。

来自Gmail帮助页面

Outgoing Mail (SMTP) Server (requires TLS)
 - smtp.gmail.com
 - Use Authentication: Yes
 - Use STARTTLS: Yes (some clients call this SSL)
 - Port: 465 or 587
Account Name:   your full email address (including @gmail.com)
Email Address:  your email address (username@gmail.com)
Password:     your Gmail password 

您可以在Pear::MailPHPMailer中设置这些设置。请查看它们的文档以获取更多详细信息。


4

你可以使用PEAR的邮件函数与Gmail的SMTP服务器一起使用。

请注意,当使用Gmail的SMTP服务器发送电子邮件时,无论$from的值是什么,它看起来都像来自您的Gmail地址。

(以下代码取自About.com编程技巧

<?php
require_once "Mail.php";

$from = "Sandra Sender <sender@example.com>";
$to = "Ramona Recipient <recipient@example.com>";
$subject = "Hi!";
$body = "Hi,\n\nHow are you?";

// stick your GMAIL SMTP info here! ------------------------------
$host = "mail.example.com";
$username = "smtp_username";
$password = "smtp_password";
// --------------------------------------------------------------

$headers = array ('From' => $from,
  'To' => $to,
  'Subject' => $subject);
$smtp = Mail::factory('smtp',
  array ('host' => $host,
    '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>");
 }
?>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接