使用Gmail的PHP邮件
时间:2020-03-05 18:45:28 来源:igfitidea点击:
在我的PHP webapp中,我希望每当发生某些错误时通过电子邮件收到通知。我想用我的Gmail帐户发送这些。怎么办呢?
解决方案
回答
我们可以将PEAR的邮件功能与Gmail的SMTP服务器一起使用
请注意,使用Gmail的SMTP服务器发送电子邮件时,尽管价值来自$ from,但看起来还是来自Gmail地址。
(以下代码取自About.com编程技巧)
<?php require_once "Mail.php"; $from = "Sandra Sender <[email protected]>"; $to = "Ramona Recipient <[email protected]>"; $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>"); } ?>
回答
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 ([email protected]) Password: your Gmail password
我们可能可以在Pear :: Mail或者PHPMailer中设置这些设置。查看其文档以获取更多详细信息。