0

0

php:smtp方式或mail函数方式发送邮件

伊谢尔伦

伊谢尔伦

发布时间:2017-06-27 11:10:17

|

2089人浏览过

|

来源于php中文网

原创

php实现的邮件发送类,二种方式:
smtp方式与mail函数方式。

代码:

<?php 
/**
* 邮件发送类
*/
Class sendmail{ 
    public $smtp_host; 
    public $smtp_port = 25; 
    public $smtp_user; 
    public $smtp_password; 
    public $from_name; 
    public $SendFromMail; 
    public $mail_to; 
    public $subject; 
    public $message; 
    public $headers = ''; 
    public $ContentType = 'html'; 
    public $charset = 'windows-1251'; 
    public $smtp_debug = true; 
    public $socket; 
    public $error; 
    public $SendMailVia  = 'smtp'; 
     
  public function construct() 
    { 
            if($this->SendFromMail == ''){ 
               $this->SendFromMail = $this->smtp_user; 
            } 
    } 
     
    public function Send($mail_to = '', $subject = '', $message = '') 
    { 
        if($mail_to!=''){$this->mail_to = stripslashes($mail_to);} 
            if($subject!=''){$this->subject = stripslashes($subject);} 
            if($message!=''){$this->message = $message;} 
            $meilsArr = array_filter($this->GetMailAndNameArr()); 
            if(trim($this->mail_to)==''){$this->error = 'Enter the recipient address'; } 
            if($meilsArr == array()){$this->error = 'Please enter a valid recipient address'; } 
            foreach ($meilsArr as $val) 
            { 
                $validEmail = $this->validEmail($val[2]); 
                if($validEmail) 
                { 
                  if($this->SendMailVia=='smtp'){ 
                      return $this->SMTPsend($mail_to = $val[2], $name_to = $val[1]); 
                    } 
                    else{ 
                      return $this->MAILsend($mail_to = $val[2], $name_to = $val[1]); 
                    }     
                } 
            } 
    } 
     
    public function MAILsend($mail_to, $name_to) 
    { 
    if($this->ContentType=="text"){ 
        $header="Content-Type: text/plain; charset=".$this->charset.""; 
      } 
        else{ 
        $header="Return-Path: ".$this->smtp_user."
". 
      "Reply-To: ".$this->SendFromMail."
". 
      "From: ".$this->from_name." <".$this->SendFromMail.">
". 
      "Subject: ".$this->subject."
". 
        "Content-Type: text/html; charset=".$this->charset."
"; 
      } 
      if(mail("$name_to <$mail_to>",$this->subject,$this->message,$header)){ 
         return true; 
        }else{ 
         return false; 
        } 
  } 
     
    public function SMTPsend($mail_to, $name_to) 
    { 
            $SEND =   "Date: ".date("D, d M Y H:i:s") . "
"; 
            $SEND .=   'Subject: =?'.$this->charset.'?B?'.base64_encode($this->subject)."=?=
"; 
            if ($this->headers!=''){ $SEND .= $this->headers."

"; } 
      else 
      { 
         $SEND .= "Reply-To: ".$this->SendFromMail."
"; 
         $SEND .= "MIME-Version: 1.0
"; 
         $SEND .= "Content-Type: text/".$this->ContentType."; charset="".$this->charset.""
"; 
         $SEND .= "Content-Transfer-Encoding: 8bit
"; 
         $SEND .= "From: "".$this->from_name."" <".$this->SendFromMail.">
"; 
         $SEND .= "To: $name_to <$mail_to>
"; 
         $SEND .= "X-Priority: 3

"; 
      } 
      $SEND .=  $this->message."
"; 
         
                $socket = fsockopen($this->smtp_host, $this->smtp_port, $errno, $errstr, 30); 
          if(!socket) 
            { 
          if($this->smtp_debug) $this->error = $errno." - ".$errstr; 
          return false; 
        } 
                 
                if (!$this->server_parse($socket, "220", LINE)){ return false; } 
                 
            fputs($socket, "HELO ".$this->smtp_host. "
"); 
            if (!$this->server_parse($socket, "250", LINE)) { 
               if ($this->smtp_debug) $this->error = '<p>Can not send HELO!</p>'; 
               fclose($socket); 
               return false; 
            } 
            fputs($socket, "AUTH LOGIN
"); 
            if (!$this->server_parse($socket, "334", LINE)) { 
               if ($this->smtp_debug) $this->error = '<p>Can not find an answer to a request authorization.</p>'; 
               fclose($socket); 
               return false; 
            } 
            fputs($socket, base64_encode($this->smtp_user) . "
"); 
            if (!$this->server_parse($socket, "334", LINE)) { 
               if ($this->smtp_debug) $this->error = '<p>Login authorization was not accepted by server!</p>'; 
               fclose($socket); 
               return false; 
            } 
            fputs($socket, base64_encode($this->smtp_password) . "
"); 
            if (!$this->server_parse($socket, "235", LINE)) { 
               if ($this->smtp_debug) $this->error = '<p>No password was not accepted as a true server! Authorization Error!</p>'; 
               fclose($socket); 
               return false; 
            } 
            fputs($socket, "MAIL FROM: <".$this->smtp_user.">
"); 
            if (!$this->server_parse($socket, "250", LINE)) { 
               if ($this->smtp_debug) $this->error = '<p>Unable to send command MAIL FROM: </p>'; 
               fclose($socket); 
               return false; 
            } 
            fputs($socket, "RCPT TO: <" . $mail_to . ">
"); 
            if (!$this->server_parse($socket, "250", LINE)) { 
               if ($this->smtp_debug) $this->error = '<p>Unable to send command RCPT TO: </p>'; 
               fclose($socket); 
               return false; 
            } 
            fputs($socket, "DATA
"); 
            if (!$this->server_parse($socket, "354", LINE)) { 
               if ($this->smtp_debug) $this->error = '<p>Unable to send command DATA</p>'; 
               fclose($socket); 
               return false; 
            } 
            fputs($socket, $SEND."
.
"); 
            if (!$this->server_parse($socket, "250", LINE)) { 
               if ($this->smtp_debug) $this->error = '<p>Unable to send the message body. The letter was sent!</p>'; 
               fclose($socket); 
               return false; 
            } 
            fputs($socket, "QUIT
"); 
            fclose($socket); 
            return TRUE; 
    } 
       
    private function GetMailAndNameArr(){ 
        $mailingArr = array(); 
            $tos = preg_split("/;|,/",$this->mail_to); 
            $pregcode = '/(.*?)<(.*?)>/i'; 
            foreach($tos as $to) 
            { 
              if(preg_match('/(.*?)<(.*?)>/i',$to,$matches)) 
                { 
                  unset($matches[0]);     
                  $matches[1] = trim(str_replace('"','',$matches[1])); 
                  $matches[2] = trim($matches[2]); 
                  $mailingArr[] =$matches;  
                } 
                elseif(preg_match('/([A-Z0-9._%-]+)@([A-Z0-9.-]+.[A-Z]{2,4})/i',$to,$matches2)) 
                { 
                     unset($matches[0]);     
                     $matches[1] = trim(str_replace('"','',$matches2[1])); 
                     $matches[2] = trim($matches2[0]); 
                     $mailingArr[] =$matches; 
                } 
            } 
            return $mailingArr; 
    } 
     
    private function server_parse($socket, $response, $line = LINE) { 
    while (substr($server_response, 3, 1) != ' ') { 
          if (!($server_response = fgets($socket, 256))) { 
               if ($this->smtp_debug) $this->error = "<p>$line Problems sending mail! $response</p>"; 
               return false; 
          } 
    } 
    if (!(substr($server_response, 0, 3) == $response)) { 
           if ($this->smtp_debug) $this->error = "<p>$line Problems sending mail! $response</p>"; 
           return false; 
        } 
    return true; 
  } 
  function validEmail($email) 
  { 
    $isValid = true; 
    $atIndex = strrpos($email, "@"); 
      $msg = ''; 
    if (is_bool($atIndex) && !$atIndex) 
    { 
      $isValid = false; 
    } 
    else 
    { 
      $domain = substr($email, $atIndex+1); 
      $local = substr($email, 0, $atIndex); 
      $localLen = strlen($local); 
      $domainLen = strlen($domain); 
      if ($localLen < 1 || $localLen > 64){ 
                 $msg = 'local part length exceeded'; 
         $isValid = false; 
      } 
      else if ($domainLen < 1 || $domainLen > 255){ 
                 $msg = ' domain part length exceeded '; 
         $isValid = false; 
      } 
      else if ($local[0] == '.' || $local[$localLen-1] == '.'){ 
                 $msg = ' local part starts or ends with .'; 
         $isValid = false; 
      } 
      else if (preg_match('/\.\./', $local)){ 
                 $msg = 'local part has two consecutive dots'; 
         $isValid = false; 
      } 
      else if (!preg_match('/^[A-Za-z0-9\-\.]+$/', $domain)){ 
                 $msg = 'character not valid in domain part'; 
         $isValid = false; 
      } 
      else if (preg_match('/\.\./', $domain)){ 
                 $msg = '  domain part has two consecutive dots'; 
         $isValid = false; 
      } 
      else if(!preg_match('/^(\\.|[A-Za-z0-9!#%&`_=\/$'*+?^{}|~.-])+$/', str_replace("\\","",$local))){ 
                 $msg = '  character not valid in local part unless local part is quoted'; 
         if (!preg_match('/^"(\\"|[^"])+"$/',str_replace("\\","",$local))){ 
            $isValid = false; 
         } 
      } 
      if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"))){ 
                 $msg = '  domain <b>'.$domain.'</b> not found in DNS'; 
         $isValid = false; 
      } 
    } 
      $this->error = $msg; 
    return $isValid; 
  } 
} 
?>

调用示例:

PathFinder
PathFinder

AI驱动的销售漏斗分析工具

下载
<?php  
include "sendmail.class.php"; 
$Mail = new sendmail(); 
// Set congif 
$Mail->SendMailVia = 'smtp';  // Send via smtp server or mail function 
$Mail->smtp_host = 'mail.myhost.com'; 
$Mail->smtp_port = 25; 
$Mail->smtp_user = 'user@myhost.com'; 
$Mail->smtp_password = 'mypassw'; 
// 例1 (mail from me) 
if($Mail->Send('mymail1@mydomain.com; recipient2 name <recipientmail2@mydomain.com>,"recipient name" <recipient@mail.com>',
'My subject','My message here.')) 
{ 
  echo '邮件已发送!'; 
} 
else 
{ 
  echo $Mail->error; 
} 
// 例2 (mail from me) 
$Mail->mail_to = 'mymail1@mydomain.com; recipient2 name <recipientmail2@mydomain.com>,"recipient name" <recipient@mail.com>'; 
$Mail->subject = 'My subject'; 
$Mail->message = 'My message here'; 
if($Mail->Send()) 
{ 
  echo '邮件已发送!'; 
} 
else 
{ 
  echo $Mail->error; 
} 
// 例3 (mail from another user: example user2@site2.com) 
$Mail->mail_to = 'Recipient Name <recipientmail@domain.com>'; 
$Mail->subject = 'My subject'; 
$Mail->message = 'My message here'; 
$Mail->from_name = 'User2 Name'; 
$Mail->SendFromMail = 'user2@site2.com'; 
if($Mail->Send()) 
{ 
  echo 'message Mail send!'; 
} 
else 
{ 
  echo $Mail->error; 
} 
?>

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

WorkBuddy
WorkBuddy

腾讯云推出的AI原生桌面智能体工作台

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
TypeScript类型系统进阶与大型前端项目实践
TypeScript类型系统进阶与大型前端项目实践

本专题围绕 TypeScript 在大型前端项目中的应用展开,深入讲解类型系统设计与工程化开发方法。内容包括泛型与高级类型、类型推断机制、声明文件编写、模块化结构设计以及代码规范管理。通过真实项目案例分析,帮助开发者构建类型安全、结构清晰、易维护的前端工程体系,提高团队协作效率与代码质量。

1

2026.03.13

Python异步编程与Asyncio高并发应用实践
Python异步编程与Asyncio高并发应用实践

本专题围绕 Python 异步编程模型展开,深入讲解 Asyncio 框架的核心原理与应用实践。内容包括事件循环机制、协程任务调度、异步 IO 处理以及并发任务管理策略。通过构建高并发网络请求与异步数据处理案例,帮助开发者掌握 Python 在高并发场景中的高效开发方法,并提升系统资源利用率与整体运行性能。

39

2026.03.12

C# ASP.NET Core微服务架构与API网关实践
C# ASP.NET Core微服务架构与API网关实践

本专题围绕 C# 在现代后端架构中的微服务实践展开,系统讲解基于 ASP.NET Core 构建可扩展服务体系的核心方法。内容涵盖服务拆分策略、RESTful API 设计、服务间通信、API 网关统一入口管理以及服务治理机制。通过真实项目案例,帮助开发者掌握构建高可用微服务系统的关键技术,提高系统的可扩展性与维护效率。

140

2026.03.11

Go高并发任务调度与Goroutine池化实践
Go高并发任务调度与Goroutine池化实践

本专题围绕 Go 语言在高并发任务处理场景中的实践展开,系统讲解 Goroutine 调度模型、Channel 通信机制以及并发控制策略。内容包括任务队列设计、Goroutine 池化管理、资源限制控制以及并发任务的性能优化方法。通过实际案例演示,帮助开发者构建稳定高效的 Go 并发任务处理系统,提高系统在高负载环境下的处理能力与稳定性。

47

2026.03.10

Kotlin Android模块化架构与组件化开发实践
Kotlin Android模块化架构与组件化开发实践

本专题围绕 Kotlin 在 Android 应用开发中的架构实践展开,重点讲解模块化设计与组件化开发的实现思路。内容包括项目模块拆分策略、公共组件封装、依赖管理优化、路由通信机制以及大型项目的工程化管理方法。通过真实项目案例分析,帮助开发者构建结构清晰、易扩展且维护成本低的 Android 应用架构体系,提升团队协作效率与项目迭代速度。

90

2026.03.09

JavaScript浏览器渲染机制与前端性能优化实践
JavaScript浏览器渲染机制与前端性能优化实践

本专题围绕 JavaScript 在浏览器中的执行与渲染机制展开,系统讲解 DOM 构建、CSSOM 解析、重排与重绘原理,以及关键渲染路径优化方法。内容涵盖事件循环机制、异步任务调度、资源加载优化、代码拆分与懒加载等性能优化策略。通过真实前端项目案例,帮助开发者理解浏览器底层工作原理,并掌握提升网页加载速度与交互体验的实用技巧。

102

2026.03.06

Rust内存安全机制与所有权模型深度实践
Rust内存安全机制与所有权模型深度实践

本专题围绕 Rust 语言核心特性展开,深入讲解所有权机制、借用规则、生命周期管理以及智能指针等关键概念。通过系统级开发案例,分析内存安全保障原理与零成本抽象优势,并结合并发场景讲解 Send 与 Sync 特性实现机制。帮助开发者真正理解 Rust 的设计哲学,掌握在高性能与安全性并重场景中的工程实践能力。

226

2026.03.05

PHP高性能API设计与Laravel服务架构实践
PHP高性能API设计与Laravel服务架构实践

本专题围绕 PHP 在现代 Web 后端开发中的高性能实践展开,重点讲解基于 Laravel 框架构建可扩展 API 服务的核心方法。内容涵盖路由与中间件机制、服务容器与依赖注入、接口版本管理、缓存策略设计以及队列异步处理方案。同时结合高并发场景,深入分析性能瓶颈定位与优化思路,帮助开发者构建稳定、高效、易维护的 PHP 后端服务体系。

506

2026.03.04

AI安装教程大全
AI安装教程大全

2026最全AI工具安装教程专题:包含各版本AI绘图、AI视频、智能办公软件的本地化部署手册。全篇零基础友好,附带最新模型下载地址、一键安装脚本及常见报错修复方案。每日更新,收藏这一篇就够了,让AI安装不再报错!

170

2026.03.04

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
燕十八Nginx视频教程
燕十八Nginx视频教程

共23课时 | 5.8万人学习

Nginx基础入门视频教程
Nginx基础入门视频教程

共23课时 | 7万人学习

PHP课程
PHP课程

共137课时 | 13.4万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号