PHP发送邮件 技术详解

PHP对邮件的操作处理可能大部分开发者都已经了解,但是对于邮件处理在PHP中到底有几种方式可能只有一个模糊的概念,今天我们针对PHP发送邮件的技术做一次详细的解析,以供大家学习和交流

jesen
1
2020-04-12 19:41:49
文档目录
我的书签
 

PHP 使用PEAR mail发送邮件

在PEAR扩展中的提供的Mail类,功能非常强大:可支持纯文本、HTML格式的内容;各协议字段都可设置编码,正确配置可避免中文乱码的问题;也可以支持附件等功能,官方地址:https://pear.php.net/package/Mail,在安装有pear工具的服务器中可以直接使用命令:pear install -a Mailpear install -a Mail_mime快速安装,没有命令权限或者没有安装pear工具的朋友也可以直接下载此类的PHP源码,然后引入就可以了。(注:Mail类依赖 Net/SMTP.php 和 Mail/mime.php,可以到官网搜查并下载:https://pear.php.net/,最好还是使用pear工具进行安装,这样可以一次性安装所有依赖,否则就需要查找这些Mail接口的依赖并一块下载下来,pear工具的安装及使用请参考《PEAR(PHP Extension and Application Repository) 安装详解》)。如下代码为下载相应类源码并引入的使用示例:
// 引入Pear Mail
/*
//如果使用pear则直接这样写就可以
require_once "Mail.php"; 
require_once "Mail/mime.php";
*/

require_once('Mail.php');
require_once('Mail/mime.php');
require_once('Net/SMTP.php');

$emailInfo = array();
$emailInfo["host"] = "smtp.163.com";//SMTP服务器
$emailInfo["port"] = "25"; //SMTP服务器端口
$emailInfo["username"] = "w3capi@163.com"; //发件人邮箱
$emailInfo["password"] = "password";//发件人邮箱密码
$emailInfo["timeout"] = 10;//网络超时时间,秒
$emailInfo["auth"] = true;//登录验证
$emailInfo["debug"] = true;//调试模式

$mailAddr = array('receiver@163.com'); // 收件人列表
$from = "w3capi@163.com"; // 发件人显示信息,这里必须和发件人邮箱保持一致
$to = implode(',',$mailAddr); // 收件人显示信息

$subject = "这是一封测试邮件"; // 邮件标题
$content = "<h3>this is test.</h3>"; // 邮件正文
$contentType = "text/html; charset=utf-8"; // 邮件正文类型,格式和编码
$crlf = PHP_EOL; //换行符号 Linux: \n Windows: \r\n
$mime = new Mail_mime($crlf);
$mime->setHTMLBody($content);

$param['text_charset'] = 'utf-8';
$param['html_charset'] = 'utf-8';
$param['head_charset'] = 'utf-8';
$body = $mime->get($param);

$headers = array();
$headers["From"] = $from;
$headers["To"] = $to;
$headers["Subject"] = $subject;
$headers["Content-Type"] = $contentType;
$headers = $mime->headers($headers);

$smtp = Mail::factory("smtp", $emailInfo);
$mail = $smtp->send($mailAddr, $headers, $body);
$smtp->disconnect();
if (PEAR::isError($mail)) {
    echo 'Email sending failed: ' . $mail->getMessage()."\n";  //发送失败
} else{
    echo "success!\n"; //发送成功
}
注:此方式需要我们注册一个邮箱账号,并开启这个账号的SMTP协议,所有的主流邮箱都支持 SMTP 协议,但并非所有邮箱都默认开启,您可以在邮箱的设置里面手动开启。第三方服务在提供了账号和密码之后就可以登录 SMTP 服务器,通过这个账号就可以发送邮件了。
友情提示