目錄
这里补充一点: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 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++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教學
1664
14
CakePHP 教程
1423
52
Laravel 教程
1318
25
PHP教程
1269
29
C# 教程
1248
24
在PHP API中說明JSON Web令牌(JWT)及其用例。 在PHP API中說明JSON Web令牌(JWT)及其用例。 Apr 05, 2025 am 12:04 AM

JWT是一種基於JSON的開放標準,用於在各方之間安全地傳輸信息,主要用於身份驗證和信息交換。 1.JWT由Header、Payload和Signature三部分組成。 2.JWT的工作原理包括生成JWT、驗證JWT和解析Payload三個步驟。 3.在PHP中使用JWT進行身份驗證時,可以生成和驗證JWT,並在高級用法中包含用戶角色和權限信息。 4.常見錯誤包括簽名驗證失敗、令牌過期和Payload過大,調試技巧包括使用調試工具和日誌記錄。 5.性能優化和最佳實踐包括使用合適的簽名算法、合理設置有效期、

php程序在字符串中計數元音 php程序在字符串中計數元音 Feb 07, 2025 pm 12:12 PM

字符串是由字符組成的序列,包括字母、數字和符號。本教程將學習如何使用不同的方法在PHP中計算給定字符串中元音的數量。英語中的元音是a、e、i、o、u,它們可以是大寫或小寫。 什麼是元音? 元音是代表特定語音的字母字符。英語中共有五個元音,包括大寫和小寫: a, e, i, o, u 示例 1 輸入:字符串 = "Tutorialspoint" 輸出:6 解釋 字符串 "Tutorialspoint" 中的元音是 u、o、i、a、o、i。總共有 6 個元

解釋PHP中的晚期靜態綁定(靜態::)。 解釋PHP中的晚期靜態綁定(靜態::)。 Apr 03, 2025 am 12:04 AM

靜態綁定(static::)在PHP中實現晚期靜態綁定(LSB),允許在靜態上下文中引用調用類而非定義類。 1)解析過程在運行時進行,2)在繼承關係中向上查找調用類,3)可能帶來性能開銷。

什麼是PHP魔術方法(__ -construct,__destruct,__call,__get,__ set等)並提供用例? 什麼是PHP魔術方法(__ -construct,__destruct,__call,__get,__ set等)並提供用例? Apr 03, 2025 am 12:03 AM

PHP的魔法方法有哪些? PHP的魔法方法包括:1.\_\_construct,用於初始化對象;2.\_\_destruct,用於清理資源;3.\_\_call,處理不存在的方法調用;4.\_\_get,實現動態屬性訪問;5.\_\_set,實現動態屬性設置。這些方法在特定情況下自動調用,提升代碼的靈活性和效率。

PHP和Python:比較兩種流行的編程語言 PHP和Python:比較兩種流行的編程語言 Apr 14, 2025 am 12:13 AM

PHP和Python各有優勢,選擇依據項目需求。 1.PHP適合web開發,尤其快速開發和維護網站。 2.Python適用於數據科學、機器學習和人工智能,語法簡潔,適合初學者。

PHP行動:現實世界中的示例和應用程序 PHP行動:現實世界中的示例和應用程序 Apr 14, 2025 am 12:19 AM

PHP在電子商務、內容管理系統和API開發中廣泛應用。 1)電子商務:用於購物車功能和支付處理。 2)內容管理系統:用於動態內容生成和用戶管理。 3)API開發:用於RESTfulAPI開發和API安全性。通過性能優化和最佳實踐,PHP應用的效率和可維護性得以提升。

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:12 AM

PHP仍然具有活力,其在現代編程領域中依然佔據重要地位。 1)PHP的簡單易學和強大社區支持使其在Web開發中廣泛應用;2)其靈活性和穩定性使其在處理Web表單、數據庫操作和文件處理等方面表現出色;3)PHP不斷進化和優化,適用於初學者和經驗豐富的開發者。

See all articles