Home php教程 php手册 php socket通过SMTP发送邮件

php socket通过SMTP发送邮件

Jun 06, 2016 pm 07:31 PM
php smtp socket send pass mail

phpsocket用过SMTP发送邮件。 用的是php的php-sockets扩展,可以发送纯文本和html格式的邮件。 欢迎提出意见! PHP 源码与演示: 源码出处演示出处 ?php/*** 邮件发送类* 支持发送纯文本邮件和HTML格式的邮件* @example* $config = array(*"from" = "*****",*

php socket用过SMTP发送邮件。
用的是php的php-sockets扩展,可以发送纯文本和html格式的邮件。
欢迎提出意见! PHP

源码与演示:源码出处 演示出处

<?php
/**
* 邮件发送类
* 支持发送纯文本邮件和HTML格式的邮件
* @example
* $config = array(
*		"from" => "*****",
*		"to" => "***",
*		"subject" => "test",
*		"body" => "<b>test</b>",
*		"username" => "***",
*		"password" => "****",
*		"isHTML" => true
*	);
*
* $mail = new MySendMail();
*
* $mail->setServer("smtp.126.com");
*
* $mail->setMailInfo($config);
* if(!$mail->sendMail()) {
*	echo $mail->error();
*	return 1;
* }
*/
class MySendMail {
	/**
	* @var 邮件传输代理用户名
	* @access private
	*/
	private $_userName;

	/**
	* @var 邮件传输代理密码
	* @access private
	*/
	private $_password;

	/**
	* @var 邮件传输代理服务器地址
	* @access protected
	*/
	protected $_sendServer;

	/**
	* @var 邮件传输代理服务器端口
	* @access protected
	*/
	protected $_port=25;

	/**
	* @var 发件人
	* @access protected
	*/
	protected $_from;

	/**
	* @var 收件人
	* @access protected
	*/
	protected $_to;

	/**
	* @var 主题
	* @access protected
	*/
	protected $_subject;

	/**
	* @var 邮件正文
	* @access protected
	*/
	protected $_body;

	/**
	* @var 是否是HTML格式的邮件
	* @access protected
	*/
	protected $_isHTML=false;

	/**
	* @var socket资源
	* @access protected
	*/
	protected $_socket;

	/**
	* @var 错误信息
	* @access protected
	*/
	protected $_errorMessage;

	public function __construct($from="", $to="", $subject="", $body="", $server="", $username="", $password="",$isHTML="", $port="") {
		if(!empty($from)){
			$this->_from = $from;
		}
		if(!empty($to)){
			$this->_to = $to;
		}
		if(!empty($subject)){
			$this->_subject = $subject;
		}
		if(!empty($body)){
			$this->_body = $body;
		}
		if(!empty($isHTML)){
			$this->_isHTML = $isHTML;
		}
		if(!empty($server)){
			$this->_sendServer = $server;
		}
		if(!empty($port)){
			$this->_port = $port;
		}
		if(!empty($username)){
			$this->_userName = $username;
		}
		if(!empty($password)){
			$this->_password = $password;
		}
	}

	/**
	* 设置邮件传输代理
	* @param string $server 代理服务器的ip或者域名
	* @param int $port 代理服务器的端口,smtp默认25号端口
	* @param int $localPort 本地端口
	* @return boolean
	*/
	public function setServer($server, $port=25) {
		if(!isset($server) || empty($server) || !is_string($server)) {
			$this->_errorMessage = "first one is an invalid parameter";
			return false;
		}
		if(!is_numeric($port)){
			$this->_errorMessage = "first two is an invalid parameter";
			return false;
		}
		$this->_sendServer = $server;
		$this->_port = $port;
		return true;
	}

	/**
	* 设置邮件
	* @access public
	* @param array $config 邮件配置信息
	* 包含邮件发送人、接收人、主题、内容、邮件传输代理的验证信息
	* @return boolean
	*/
	public function setMailInfo($config) {
		if(!is_array($config) || count($config) < 6){
			$this->_errorMessage = "parameters are required";
			return false;
		}

		$this->_from = $config['from'];
		$this->_to = $config['to'];
		$this->_subject = $config['subject'];
		$this->_body = $config['body'];
		$this->_userName = $config['username'];
		$this->_password = $config['password'];
		if(isset($config['isHTML'])){
			$this->_isHTML = $config['isHTML'];
		}

		return true;
	}

	/**
	* 发送邮件
	* @access public
	* @return boolean
	*/
	public function sendMail() {
		$command = $this->getCommand();
		$this->socket();
		
		foreach ($command as $value) {
			if($this->sendCommand($value[0], $value[1])) {
				continue;
			}
			else{
				return false;
			}
		}
		
		$this->close(); //其实这里也没必要关闭,smtp命令:QUIT发出之后,服务器就关闭了连接,本地的socket资源会自动释放
		echo 'Mail OK!';
		return true;
	}

	/**
	* 返回错误信息
	* @return string
	*/
	public function error(){
		if(!isset($this->_errorMessage)) {
			$this->_errorMessage = "";
		}
		return $this->_errorMessage;
	}

	/**
	* 返回mail命令
	* @access protected
	* @return array
	*/
	protected function getCommand() {
		if($this->_isHTML) {
			$mail = "MIME-Version:1.0\r\n";
			$mail .= "Content-type:text/html;charset=utf-8\r\n";
			$mail .= "FROM:test<" . $this->_from . ">\r\n";
			$mail .= "TO:<" . $this->_to . ">\r\n";
			$mail .= "Subject:" . $this->_subject ."\r\n\r\n";
			$mail .= $this->_body . "\r\n.\r\n";
		}
		else{
			$mail = "FROM:test<" . $this->_from . ">\r\n";
			$mail .= "TO:<" . $this->_to . ">\r\n";
			$mail .= "Subject:" . $this->_subject ."\r\n\r\n";
			$mail .= $this->_body . "\r\n.\r\n";
		}
		$command = array(
				array("HELO sendmail\r\n", 250),
				array("AUTH LOGIN\r\n", 334),
				array(base64_encode($this->_userName) . "\r\n", 334),
				array(base64_encode($this->_password) . "\r\n", 235),
				array("MAIL FROM:<" . $this->_from . ">\r\n", 250),
				array("RCPT TO:<" . $this->_to . ">\r\n", 250),
				array("DATA\r\n", 354),
				array($mail, 250),
				array("QUIT\r\n", 221)
		);
		return $command;
	}

	/**
	* @access protected
	* @param string $command 发送到服务器的smtp命令
	* @param int $code 期望服务器返回的响应吗
	* @param boolean
	*/
	protected function sendCommand($command, $code) {
		echo 'Send command:' . $command . ',expected code:' . $code . '<br />';
		//发送命令给服务器
		try{
			if(socket_write($this->_socket, $command, strlen($command))){
				//读取服务器返回
				$data = trim(socket_read($this->_socket, 1024));
				echo 'response:' . $data . '<br /><br />';
				if($data) {
					$pattern = "/^".$code."/";
					if(preg_match($pattern, $data)) {
						return true;
					}
					else{
						$this->_errorMessage = "Error:" . $data . "|**| command:";
						return false;
					}
				}
				else{
					$this->_errorMessage = "Error:" . socket_strerror(socket_last_error());
					return false;
				}
			}
			else{
				$this->_errorMessage = "Error:" . socket_strerror(socket_last_error());
				return false;
			}
		}catch(Exception $e) {
			$this->_errorMessage = "Error:" . $e->getMessage();
		}
	}

	/**
	* 建立到服务器的网络连接
	* @access private
	* @return boolean
	*/
	private function socket() {
		if(!function_exists("socket_create")) {
			$this->_errorMessage = "extension php-sockets must be enabled";
			return false;
		}
		//创建socket资源
		$this->_socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'));
		
		if(!$this->_socket) {
			$this->_errorMessage = socket_strerror(socket_last_error());
			return false;
		}

		//连接服务器
		if(!socket_connect($this->_socket, $this->_sendServer, $this->_port)) {
			$this->_errorMessage = socket_strerror(socket_last_error());
			return false;
		}
		socket_read($this->_socket, 1024);
		
		return true;
	}

	/**
	* 关闭socket
	* @access private
	* @return boolean
	*/
	private function close() {
		if(isset($this->_socket) && is_object($this->_socket)) {
			$this->_socket->close();
			return true;
		}
		$this->_errorMessage = "no resource can to be close";
		return false;
	}
}


/**************************** Test ***********************************/
$config = array(
		"from" => "XXXXX",
		"to" => "XXXXX",
		"subject" => "test",
		"body" => "<b>test</b>",
		"username" => "XXXXX",
		"password" => "******",
		//"isHTML" => true
	);

$mail = new MySendMail();

$mail->setServer("smtp.126.com");

$mail->setMailInfo($config);
if(!$mail->sendMail()) {
	echo $mail->error();
	return 1;
}
Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1252
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles