찾다
php教程php手册php 邮件类,php邮件

php 邮件类,php邮件

编写一个用php socket 发送邮件的类,简单好用,当用到php程序发送邮件时,

而在163服务器中,可以在RCPT命令中还可以验证163邮箱是否存在,还有很多用处,

我现在暂时还没想到。

记录下,有需要的朋友可以参考下

class mail {

    /**
    * 这些即可发送email
    */
    public $host;
    public $port;
    public $user;
    public $password;
    public $mail_form;
    public $rcpt;

    public $body;

    /**
    * 附属在 header 中信息
    */
    public $to_name;
    public $from_name;
    public $subject;
    public $html;
 
    public $connection;

    public $msg = array();


    // 进行参数初始化
    public function __construct($conf, $rcpt, $header, $body, $html = true) {

        try {

            $this->host = $conf['host'];
            $this->port = $conf['port'];
            $this->user = $conf['user'];
            $this->password = $conf['password'];

            $this->rcpt = $rcpt;

            $this->to_name   = $header['to_name'];
            $this->from_name = $header['from_name'];
            $this->subject   = $header['subject'];
            $this->html      = $html;

            $this->body = base64_encode($body);

        } catch (Exception $e) {
            throw new Exception($e->getMessage());            
        }

    }



    public function connect() {
        $this->connection = @fsockopen($this->host, '25', $errno, $errstr, 10);
        if (!$this->connection) {            
            throw new Exception('connect failed!');
        }
        $greet = $this->callback_code();
        
    }

    public function helo() {
        if($this->is_connect() &&
            $this->send_data('HELO ' . $this->host) &&
            $this->callback_code() == 250
            ) {
             return true;
        } else {
            throw new Exception($this->get_callback_msg_lastest());
            
        }
    }

    public function send_data($cmd) {
        if (is_resource($this->connection)) {
            return @fwrite($this->connection, $cmd."\r\n", strlen($cmd) + 2);
        }
    }

    public function auth(){
        if ($this->is_connect() &&
            $this->send_data('AUTH LOGIN') && $this->callback_code() == 334 &&
            $this->send_data(base64_encode($this->user)) && $this->callback_code() == 334 &&
            $this->send_data(base64_encode($this->password)) && $this->callback_code() == 235 ) {    
            return true;
        } else {
            throw new Exception($this->get_callback_msg_lastest());            
        }
    }

   public function Mail() {
        
        if ($this->is_connect() &&
            $this->send_data("MAIL FROM:user>") &&
            $this->callback_code() == 250
            ) {
            return true;
        } else  {
           throw new Exception($this->get_callback_msg_lastest());            
        }
   }

    public function is_connect() {
        return is_resource($this->connection);
    }

    public function callback_code() {
        if ($this->is_connect()) {
            $msg = fgets($this->connection);
            if (!empty($msg)) {
                $code = substr($msg, 0, strpos($msg, ' '));
            } else {
                return '';
            }
            $this->msg[] = $msg;
            return $code;
        }
    }

    public function get_callback_msg_lastest() {
        return end($this->msg);
    }

    public function rcpt($rcpt) {
        if ($this->is_connect() &&
            $this->send_data("RCPT TO:") &&
            $this->callback_code() == 250
            ) {
            return true;
        } else  {
            throw new Exception($this->get_callback_msg_lastest());            
        }
    }

    public function data() {
        if ($this->is_connect() &&
            $this->send_data('DATA') &&
            $this->callback_code() == 354) {
            return true;
        } else {
            throw new Exception($this->get_callback_msg_lastest());
        }
    }


    public function send_mail() {

        try {
            
            $this->connect();
            $this->helo();
            $this->auth();
            $this->Mail();

            if (is_array($this->rcpt)) {
                foreach ($this->rcpt as $rcpt) {
                    $this->rcpt($rcpt);
                }

            } else {
                $this->rcpt($this->rcpt);
            }

            $this->data();

            $header = str_replace("\r\n" . '.', "\r\n" . '..', trim(implode("\r\n", $this->get_header())));
            $body   = str_replace("\r\n" . '.', "\r\n" . '..', $this->body);
            $body   = substr($body, 0, 1) == '.' ? '.' . $body : $body;

            $this->send_data($header);
            $this->send_data('');
            $this->send_data($body);            
            $this->send_data('.');

            if ($this->callback_code()  != 250) {
                throw new Exception('send mail falied!');                
            }
            return true;
        } catch (Exception $e) {
            throw new Exception($e->getMessage());            
        }


    }



    //只能检测同一邮件服务器上email address
    public  function is_email_exist() {




    }


    public function get_header() {

        $header = array();
        $content_type = $this->html ? 'text/html;' : 'text/plain;' ;

        $headers [] = 'Date: ' . gmdate('D, j M Y H:i:s') . ' +0000';
        $to_mail = is_array($this->rcpt) ? implode(',', $this->rcpt) : $this->rcpt;
        $headers [] = 'To: "' . '=? utf8?B?' . base64_encode($this->to_name) . '?=' . '" ';
        $headers [] = 'From: "' . '=?utf8?B?' . base64_encode($this->from_name) . '?=' . '" user . '>';
        $headers [] = 'Subject: ' . '=?utf8?B?' . base64_encode($this->subject) . '?=';
        $headers [] = 'Content-Type:'.$content_type . ' charset=utf8; format=flowed';
        $headers [] = 'Content-Transfer-Encoding: base64';
        $headers [] = 'Content-Disposition: inline';

        return $headers;
    }



}


/**
* 用函数封装类
*/
function send_mail($conf, $rcpt, $header, $body) {
    
    $mail = new mail($conf, $rcpt, $header, $body);

    if ($mail->send_mail()) {
        echo 'send email successfully!';
    } else {
        echo 'falied!';
    }


}


$conf = array(
    'host'     => 'smtp.163.com',
    'port'     => '25',
    'user'     => 'z1298703836@163.com',
    'password' => 'zeiwei123',
     );

$rcpt = array(
    'z1298703836@sina.com',
    'wei.zen@baisonmail.com'
    );

$header = array(
    'to_name'   => 'willstang',
    'from_name' => 'sinawill',
    'subject'   => 'tst of reo ',
    );

$body = '

sfsfsd

';

$mail = new mail($conf, $rcpt, $header, $body);

$mail->send_mail();


echo '
';<br>print_r($mail->msg);
<p> </p>
<p>熟悉邮件发送的过程,它的stmp协议,</p>
<p>还有一些发送的细节,如:发送的内容分为两部分, 一部分在头部,另一部分是email的正文,</p>
<p> </p>
성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

안전한 시험 브라우저

안전한 시험 브라우저

안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기