PHP对邮件的操作处理可能大部分开发者都已经了解,但是对于邮件处理在PHP中到底有几种方式可能只有一个模糊的概念,今天我们针对PHP发送邮件的技术做一次详细的解析,以供大家学习和交流
https://pear.php.net/package/Mail
,在安装有pear工具的服务器中可以直接使用命令:pear install -a Mail
和 pear 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"; //发送成功 }