在 Windows 中使用 sendmail
PHP 的 mail 函数是 PHP 中一个很好的特性,但就像生活中的所有好东西一样,这个函数也有许多缺点。在 Linux 平台上,它需要安装 sendmail,但在 windows 上,需要 SMTP 服务器来发送电子邮件。因此,如果打开 php.ini
文件,你会发现以下行:
[mail function]
; For Win32 only.
SMTP = localhost
smtp_port = 25
但此处的限制是,你只能指定 SMTP 服务器名称和端口,如果服务器需要身份验证,则没有指定用户名和密码的地方。因此,除非你将邮件服务器配置为在没有身份验证的情况下发送本地电子邮件,否则无法使用 php 的 mail()
发送电子邮件。
这就是 sendmail for windows 的用武之地。它由 Byron Jones 创建,也被称为 fake sendmail。使用此工具,你可以将PHP配置为使用具有身份验证的外部 SMTP 服务器,通过 PHP 邮件功能发送电子邮件。本文将逐步指导你为 windows 配置 sendmail。
步骤 1:- 下载并配置 windows 版 sendmail
下载 windows 版 sendmail 并解压缩 sendmail.zip 并将内容放在易于访问的地方。本例中 ,我将把它放在 C:\sendmail
目录中。接下来配置 sendmail.ini
文件。使用记事本等文本编辑器打开 sendmail.ini
文件。编辑以下值:
[sendmail]
smtp_server=localhost
smtp_port=25
;auth_username=
;auth_password=
本教程将使用 gmail 的 SMTP 服务器,因此值为
[sendmail]
smtp_server=ssl://smtp.gmail.com
smtp_port=465
auth_username=username@gmail.com
auth_password=gmailpassword
保存文件进入下一步。
步骤 2:- 编辑 php.ini 文件
在这一步中,需要在 php.ini
文件中设置 sendmail_path
值,在此之前,注释掉不必要的行,找到以下行并在它们前面加一个分号(;)
[mail function]
; For Win32 only.
;SMTP = localhost
;smtp_port = 25
; For Win32 only.
;sendmail_from =
现在修改以下内容,并将 sendmail 路径设置为 sendmail.exe
文件所在的位置
; For Unix only. You may supply arguments as well (default: "sendmail -t -i").
sendmail_path = C:\sendmail\sendmail.exe
保存 php.ini 文件并重启 apache web 服务器,或者其他你使用的 web 服务器
步骤 3:- 使用 mail() 函数测试设置
在文档根目录中(htdocs 或 public_html 或者 www 目录)创建一个名为 mail.php
的文件,并输入如下代码:
<?php
mail("youremail@domain.com","Subject","Email message","From: username@gmail.com");
?>
保存文件,并通过 url (http://example.com/mail.php) 进行访问,你将看到一个空白页面。登录你的邮箱 youremail@domain.com 在收件箱中查看新邮件。
注意:要通过外部 SMTP 服务器发送电子邮件,你的电脑必须联网。