php smtp 发送邮件

一、准备工作
1、开启邮箱的smtp服务器
例如qq邮箱 在设置中开启smtp
在这里插入图片描述
拿到授权码

smtp.php


class Mailer
{
  private $host;
  private $port = 25;
  private $user;
  private $pass;
  private $debug = false;
  private $sock;
 
  public function __construct($host,$port,$user,$pass,$debug = false)
  {
    $this->host = $host;
    $this->port = $port;
    $this->user = base64_encode($user); //用户名密码base64编码才行
    $this->pass = base64_encode($pass);
    $this->debug = $debug;
   //socket连接
    $this->sock = fsockopen($this->host,$this->port);
    if(!$this->sock){
      exit('连接有误');
    }
    //读取smtp服务返回给我们的数据
    $response = fgets($this->sock);
    $this->debug($response);
        //如果响应中有220返回码,说明我们连接成功了
    if(strstr($response,'220') === false){
      exit('连接有误');
    }
  }
  //发送SMTP指令
  public function execCommand($cmd,$return_code){
    fwrite($this->sock,$cmd);
 
    $response = fgets($this->sock);
    //打印调试信息
    $this->debug('cmd:'.$cmd .';response:'.$response);
    if(strstr($response,$return_code) === false){
      return false;
    }
    return true;
  }
 
  public function sendMail($from,$to,$subject,$body){
   //邮件的内容,协议规定
    $smtpInfo = 'From:'.$from."\r\n";
    $smtpInfo .= 'To:'.$to."\r\n";
    $smtpInfo .= 'Subject:'.$subject."\r\n";
    $smtpInfo .= 'Content-Type:text/html'."\r\n\r\n";
    $smtpInfo .= $body;
    $this->execCommand("HELO ".$this->host."\r\n",250);
    $this->execCommand("AUTH LOGIN\r\n",334);
    $this->execCommand($this->user."\r\n",334);
    $this->execCommand($this->pass."\r\n",235);
    $this->execCommand("MAIL FROM:<".$from.">\r\n",250);
    $this->execCommand("RCPT TO:<".$to.">\r\n",250);
    $this->execCommand("DATA\r\n",354);
    $this->execCommand($smtpInfo."\r\n.\r\n",250);
    $this->execCommand("QUIT\r\n",221);
  }
 
  public function debug($message){
    if($this->debug){
      echo '

Debug:'.$message . PHP_EOL .'

'
; } } public function __destruct() { fclose($this->sock); } } ?>

调用发送邮件

代码


 require("smtp.php");
$port = 587; //端口号 默认25 可能是587 也可能是 465 连接失败时调试下端口号
$user = '[email protected]'; //请替换成你自己的smtp用户名
$pass = '授权码'; // smtp授权码 第一步获取到的
$host = 'smtp.qq.com'; //smtp服务器
$from = '[email protected]'; //发送者邮箱就是开启授权的QQ邮箱
$to = '接受者邮箱';
$body = '内容';
$subjet = '标题';
$mailer = new Mailer($host,$port,$user,$pass,true);
$mailer->sendMail($from,$to,$subjet,$body);

你可能感兴趣的:(php,开发语言)