PHP 邮件发送

简单的把代码贴上,这个是没有使用什么PHP第三方库的例子来实现发送邮件

email.class.php

<?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){
//detail是邮件的内容,一定要严格按照下面的格式,这是协议规定的
        $detail = 'From:'.$from."\r\n";
        $detail .= 'To:'.$to."\r\n";
        $detail .= 'Subject:'.$subject."\r\n";
        $detail .= 'Content-Type: Text/html;'."\r\n";
        $detail .= 'charset=gb2312'."\r\n\r\n";
        $detail .= $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($detail."\r\n.\r\n",250);
        $this->execCommand("QUIT\r\n",221);
    }

    public function debug($message){
        if($this->debug){
            echo '<p>Debug:'.$message . PHP_EOL .'</p>';
        }
    }

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

}

email.php

<?php
require_once("./phpmail/email.class.php");

$port = 25;
$user = 'xxx@163.com';     //请替换成你的账号
$pass = 'dss55dsd55';      //请替换成你的授权码
$host = 'smtp.163.com';    //邮箱服务器
$from = 'xxx@163.com';     //发送人的邮箱
$to = 'xxx@qq.com';        //接收人的邮箱
$body = 'hello world';     //内容
$subjet = '我是标题';       //标题
$mailer = new Mailer($host,$port,$user,$pass,true);
$mailer->sendMail($from,$to,$subjet,$body);

通过以上方式就可以实现简单的邮件发送了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值