目录
这里补充一点:QQ邮箱不让自己SMTP发给自己,所以测试时请留意这个问题。" >这里补充一点:QQ邮箱不让自己SMTP发给自己,所以测试时请留意这个问题。
首页 php教程 php手册 简单的PHP邮件发送类

简单的PHP邮件发送类

Jun 06, 2016 pm 08:07 PM
php 分享 发送 框架 简单 自己 邮件

把自己框架里的邮件发送类分享出来,希望对大家有帮助,同时做了一个小例子,方便大家使用。 SMTP类:Smtp.class.php ?php/** * SMTP类 * @package DolrPHP * @author Joy chao * @version v2.0 * @copyright Copyright (c) 2012. DolrPHP.com * @modifier J

把自己框架里的邮件发送类分享出来,希望对大家有帮助,同时做了一个小例子,方便大家使用。

SMTP类:Smtp.class.php

<?php /**
 * SMTP类
 * @package         DolrPHP
 * @author          Joy chao 
 * @version         v2.0
 * @copyright       Copyright (c) 2012. DolrPHP.com
 * @modifier        Joy chao 
 * @lastmodified    Joy chao    2012-4-30
 */
class Smtp {
	public $smtp_host; 	//SMTP主机,如: smtp.qq.com
	public $smtp_port = 25;	//SMTP端口
	public $auth = TRUE;	//是否需要帐户认证
	public $user;		//帐户名
	public $pass;		//帐户密码
	public $debug = FALSE;	//开启调试
	public $time_out;
	public $host_name;
	public $log_file;
	public $sock;
	/**
	 * 构造函数,连接smtp服务器
	 * @param string 	smtp服务器
	 * @param int 		smtp服务器端口
	 * @param bool 		smtp服务器是否需要认证
	 * @param string 	smtp服务器邮件帐号
	 * @param string 	smtp服务器邮件密码
	 */
	function smtp($smtp_host, $smtp_port = 25, $auth = TRUE, $user = '', $pass = '') {
		$this->debug     = FALSE;
		$this->smtp_port = trim ( $smtp_port );
		$this->smtp_host = trim ( $smtp_host );
		$this->time_out  = 30; // is used in fsockopen()
		$this->auth      = trim ( $auth ); // auth
		$this->user      = trim ( $user );
		$this->pass      = trim ( $pass );
		$this->host_name = "localhost"; // is used in HELO command
		$this->log_file  = '';
		$this->sock      = FALSE;
	}
	/**
	 * 发送邮件主方法
	 * @param  string $to                 收件人
	 * @param  string $mail_from          发件人
	 * @param  string $subject            主题
	 * @param  string $body               内容
	 * @param  string $mailtype           邮件类型(HTML/TXT)
	 * @param  string $cc                 抄送
	 * @param  string $bcc                密送
	 * @param  string $additional_headers 额外头信息
	 * @return boolean                    成功或者失败
	 */
	function sendmail($to, $mail_from, $subject = '', $body = '', $mailtype = "HTML", $cc = '', $bcc = '', $additional_headers = '') {
		$to           = trim ( $to );
		$stringEncode = mb_detect_encoding($body, array('UTF-8','GBK','ASCII','GB2312')); 
		$subject      = iconv($stringEncode,'UTF-8',$subject);
		$body         = iconv($stringEncode,'UTF-8',$body);
		$body         = preg_replace ( "/(^|(\r\n))(\.)/", "\\1.\\3", base64_encode($body));
		$header       = "MIME-Version:1.0\r\n";
		if (strtoupper ( $mailtype ) == "HTML") {
			$header .= "Content-Type:text/html;charset=utf-8\r\n";
		}
		$header .= "Content-Transfer-Encoding: base64\n";
		$header .= "To: " . $to . "\r\n";
		if ($cc != '') {
			$header .= "Cc: " . $cc . "\r\n";
		}
		$header .= "From: " . $this->get_mailfrom ( $this->user, $mail_from ) . "\r\n";
		$header .= "Subject: " . $subject . "\r\n";
		$header .= $additional_headers;
		$header .= "Date: " . date ( "r" ) . "\r\n";
		$header .= "X-Mailer:By Apache (PHP/" . phpversion() . ")\r\n";
		list ( $msec, $sec ) = explode ( ' ', microtime() );
		$header .= "Message-ID: \r\n";
		$TO = explode ( ',', $this->strip_comment ( $to ) );
		if ($cc != '') {
			$TO = array_merge ( $TO, explode( ',', $this->strip_comment ( $cc ) ) );
		}
		if ($bcc != '') {
			$TO = array_merge ( $TO, explode ( ',', $this->strip_comment ( $bcc ) ) );
		}
		$sent = TRUE;
		foreach ( $TO as $rcpt_to ) {
			$rcpt_to = $this->get_address ( $rcpt_to );
			if (! $this->smtp_sockopen ( $rcpt_to )) {
				$this->log_write ( "Error: Cannot send email to " . $rcpt_to . "\n" );
				$sent = FALSE;
				continue;
			}
			if ($this->smtp_send ( $this->host_name, $this->user, $rcpt_to, $header, $body )) {
				$this->log_write ( "E-mail has been sent to \n" );
			} else {
				$this->log_write ( "Error: Cannot send email to \n" );
				$sent = FALSE;
			}
			fclose ( $this->sock );
			$this->log_write ( "Disconnected from remote host\n" );
		}
		return $sent;
	}
	/**
	 * 发送邮件
	 * @access public
	 */
	function smtp_send($helo, $from, $to, $header, $body = '') {
		if (! $this->smtp_putcmd ( "HELO", $helo )) {
			return $this->smtp_error ( "sending HELO command" );
		}
		// auth
		if ($this->auth) {
			if (! $this->smtp_putcmd ( "AUTH LOGIN", base64_encode ( $this->user ) )) {
				return $this->smtp_error ( "sending HELO command" );
			}
			if (! $this->smtp_putcmd ( '', base64_encode ( $this->pass ) )) {
				return $this->smtp_error ( "sending HELO command" );
			}
		}
		if (! $this->smtp_putcmd ( "MAIL", "FROM:" )) {
			return $this->smtp_error ( "sending MAIL FROM command" );
		}
		if (! $this->smtp_putcmd ( "RCPT", "TO:" )) {
			return $this->smtp_error ( "sending RCPT TO command" );
		}
		if (! $this->smtp_putcmd ( "DATA" )) {
			return $this->smtp_error ( "sending DATA command" );
		}
		if (! $this->smtp_message ( $header, $body )) {
			return $this->smtp_error ( "sending message" );
		}
		if (! $this->smtp_eom ()) {
			return $this->smtp_error ( "sending . [EOM]" );
		}
		if (! $this->smtp_putcmd ( "QUIT" )) {
			return $this->smtp_error ( "sending QUIT command" );
		}
		return TRUE;
	}
	function smtp_sockopen($address) {
		if ($this->smtp_host == '') {
			return $this->smtp_sockopen_mx ( $address );
		} else {
			return $this->smtp_sockopen_relay ();
		}
	}
	function smtp_sockopen_relay() {
		$this->log_write ( "Trying to " . $this->smtp_host . ":" . $this->smtp_port . "\n" );
		$this->sock = @fsockopen ( $this->smtp_host, $this->smtp_port, $errno, $errstr, $this->time_out );
		if (! ($this->sock && $this->smtp_ok ())) {
			$this->log_write ( "Error: Cannot connenct to relay host " . $this->smtp_host . "\n" );
			$this->log_write ( "Error: " . $errstr . " (" . $errno . ")\n" );
			return FALSE;
		}
		$this->log_write ( "Connected to relay host " . $this->smtp_host . "\n" );
		return TRUE;
	}
	function smtp_sockopen_mx($address) {
		$domain = ereg_replace ( "^.+@([^@]+)$", "\1", $address );
		if (! @getmxrr ( $domain, $MXHOSTS )) {
			$this->log_write ( "Error: Cannot resolve MX \"" . $domain . "\"\n" );
			return FALSE;
		}
		foreach ( $MXHOSTS as $host ) {
			$this->log_write ( "Trying to " . $host . ":" . $this->smtp_port . "\n" );
			$this->sock = @fsockopen ( $host, $this->smtp_port, $errno, $errstr, $this->time_out );
			if (! ($this->sock && $this->smtp_ok ())) {
				$this->log_write ( "Warning: Cannot connect to mx host " . $host . "\n" );
				$this->log_write ( "Error: " . $errstr . " (" . $errno . ")\n" );
				continue;
			}
			$this->log_write ( "Connected to mx host " . $host . "\n" );
			return TRUE;
		}
		$this->log_write ( "Error: Cannot connect to any mx hosts (" . implode ( ", ", $MXHOSTS ) . ")\n" );
		return FALSE;
	}
	function smtp_message($header, $body) {
		fputs ( $this->sock, $header . "\r\n" . $body );
		$this->smtp_debug ( "> " . str_replace ( "\r\n", "\n" . "> ", $header . "\n> " . $body . "\n> " ) );
		return TRUE;
	}
	function smtp_eom() {
		fputs ( $this->sock, "\r\n.\r\n" );
		$this->smtp_debug ( ". [EOM]\n" );
		return $this->smtp_ok ();
	}
	function smtp_ok() {
		$response = str_replace ( "\r\n", '', fgets ( $this->sock, 512 ) );
		$this->smtp_debug ( $response . "\n" );
		if (! preg_match("/^[23]/", $response )) {
			fputs ( $this->sock, "QUIT\r\n" );
			fgets ( $this->sock, 512 );
			$this->log_write ( "Error: Remote host returned \"" . $response . "\"\n" );
			return FALSE;
		}
		return TRUE;
	}
	function smtp_putcmd($cmd, $arg = '') {
		if ($arg != '') {
			if ($cmd == '')
				$cmd = $arg;
			else
				$cmd = $cmd . " " . $arg;
		}
		fputs ( $this->sock, $cmd . "\r\n" );
		$this->smtp_debug ( "> " . $cmd . "\n" );
		return $this->smtp_ok ();
	}
	function smtp_error($string) {
		$this->log_write ( "Error: Error occurred while " . $string . ".\n" );
		return FALSE;
	}
	function log_write($message) {
		$this->smtp_debug ( $message );
		if ($this->log_file == '') {
			return TRUE;
		}
		$message = date ( "M d H:i:s " ) . get_current_user () . "[" . getmypid () . "]: " . $message;
		if (! @file_exists ( $this->log_file ) || ! ($fp = @fopen ( $this->log_file, "a" ))) {
			$this->smtp_debug ( "Warning: Cannot open log file \"" . $this->log_file . "\"\n" );
			return FALSE;
		}
		flock ( $fp, LOCK_EX );
		fputs ( $fp, $message );
		fclose ( $fp );
		return TRUE;
	}
	function strip_comment($address) {
		$comment = "/\([^()]*\)/";
		while ( preg_match( $comment, $address ) ) {
			$address = preg_replace ( $comment, '', $address );
		}
		return $address;
	}
	function get_address($address) {
		return trim ( preg_replace ( "/(.*[]+)[>]?/i", "$2", $address ) );
	}
	function get_mailfrom($address,$mail_from) {
		return $mail_from . "";
	}
	function smtp_debug($message) {
		if ($this->debug) {
			return $message;
		}
	}
}//CLASS SMTP END-----
登录后复制

使用范例: mail.php

<?php /**
 * SMTP邮件发送演示
 *
 * @author  Joychao 
 **/
//包含SMTP类文件
include './Smtp.class.php';
$smtpserver   = "smtp.exmail.qq.com";	//SMTP服务器 
$smtpport     = 25;						//SMTP服务器端口 
$smtpusermail = "admin@joychao.cc";		//SMTP服务器的用户邮箱 
$smtpuser     = "admin@joychao.cc";		//SMTP服务器的用户帐号 
$smtppass     = "123456";				//SMTP服务器的用户密码 
$mailfrom     =	"Joychao'Blog";			//发送者名称
$mailto       = '44294631@qq.com';		//发送给谁(QQ邮箱情况下不能和上面的登录帐户一样,否则发不出去)
$mailsubject  = "Hello world!这是一封测试邮件的标题";	//邮件主题 
$mailbody     = '您好!这是一封测试邮件来自Joychao\'Blog';//邮件内容,支持HTML
$mailtype     = "HTML";					//邮件格式(HTML/TXT),TXT为文本邮件 
########################################## 
//这里面的一个true是表示使用身份验证,否则不使用身份验证. 
$smtp = new Smtp($smtpserver,$smtpport,true,$smtpuser,$smtppass);//实例化SMTP类
//是否显示调试信息 
$smtp->debug = 1;
//发送邮件
$res=$smtp->sendmail($mailto, $mailfrom, $mailsubject, $mailbody, $mailtype);
if($res){
	echo '发送成功';
}else{
	echo '发送失败';
}
登录后复制

这里补充一点:QQ邮箱不让自己SMTP发给自己,所以测试时请留意这个问题。

代码呢?百度网盘:http://pan.baidu.com/share/link?shareid=78838&uk=453059967

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

<🎜>:泡泡胶模拟器无穷大 - 如何获取和使用皇家钥匙
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系统,解释
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆树的耳语 - 如何解锁抓钩
3 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Java教程
1666
14
CakePHP 教程
1425
52
Laravel 教程
1325
25
PHP教程
1273
29
C# 教程
1252
24
PHP和Python:比较两种流行的编程语言 PHP和Python:比较两种流行的编程语言 Apr 14, 2025 am 12:13 AM

PHP和Python各有优势,选择依据项目需求。1.PHP适合web开发,尤其快速开发和维护网站。2.Python适用于数据科学、机器学习和人工智能,语法简洁,适合初学者。

PHP:网络开发的关键语言 PHP:网络开发的关键语言 Apr 13, 2025 am 12:08 AM

PHP是一种广泛应用于服务器端的脚本语言,特别适合web开发。1.PHP可以嵌入HTML,处理HTTP请求和响应,支持多种数据库。2.PHP用于生成动态网页内容,处理表单数据,访问数据库等,具有强大的社区支持和开源资源。3.PHP是解释型语言,执行过程包括词法分析、语法分析、编译和执行。4.PHP可以与MySQL结合用于用户注册系统等高级应用。5.调试PHP时,可使用error_reporting()和var_dump()等函数。6.优化PHP代码可通过缓存机制、优化数据库查询和使用内置函数。7

PHP行动:现实世界中的示例和应用程序 PHP行动:现实世界中的示例和应用程序 Apr 14, 2025 am 12:19 AM

PHP在电子商务、内容管理系统和API开发中广泛应用。1)电子商务:用于购物车功能和支付处理。2)内容管理系统:用于动态内容生成和用户管理。3)API开发:用于RESTfulAPI开发和API安全性。通过性能优化和最佳实践,PHP应用的效率和可维护性得以提升。

PHP与Python:了解差异 PHP与Python:了解差异 Apr 11, 2025 am 12:15 AM

PHP和Python各有优势,选择应基于项目需求。1.PHP适合web开发,语法简单,执行效率高。2.Python适用于数据科学和机器学习,语法简洁,库丰富。

PHP的持久相关性:它还活着吗? PHP的持久相关性:它还活着吗? Apr 14, 2025 am 12:12 AM

PHP仍然具有活力,其在现代编程领域中依然占据重要地位。1)PHP的简单易学和强大社区支持使其在Web开发中广泛应用;2)其灵活性和稳定性使其在处理Web表单、数据库操作和文件处理等方面表现出色;3)PHP不断进化和优化,适用于初学者和经验丰富的开发者。

PHP和Python:代码示例和比较 PHP和Python:代码示例和比较 Apr 15, 2025 am 12:07 AM

PHP和Python各有优劣,选择取决于项目需求和个人偏好。1.PHP适合快速开发和维护大型Web应用。2.Python在数据科学和机器学习领域占据主导地位。

PHP与其他语言:比较 PHP与其他语言:比较 Apr 13, 2025 am 12:19 AM

PHP适合web开发,特别是在快速开发和处理动态内容方面表现出色,但不擅长数据科学和企业级应用。与Python相比,PHP在web开发中更具优势,但在数据科学领域不如Python;与Java相比,PHP在企业级应用中表现较差,但在web开发中更灵活;与JavaScript相比,PHP在后端开发中更简洁,但在前端开发中不如JavaScript。

PHP和Python:解释了不同的范例 PHP和Python:解释了不同的范例 Apr 18, 2025 am 12:26 AM

PHP主要是过程式编程,但也支持面向对象编程(OOP);Python支持多种范式,包括OOP、函数式和过程式编程。PHP适合web开发,Python适用于多种应用,如数据分析和机器学习。

See all articles