Home Backend Development PHP Tutorial php socket通过smtp发送邮件(可带附件)

php socket通过smtp发送邮件(可带附件)

Jun 20, 2016 pm 01:02 PM
socket

php socket通过smtp发送邮件(可带附件)

//define("SOL", "\n");
define("EOL", "\r\n");
define("SMTP_HOST", "smtp.163.com");//SMTP服务器
define("SMTP_PORT", "25");//SMTP服务器端口
define("SMTP_USER", "");//SMTP服务器的用户帐号
define("SMTP_PASS", "");//SMTP服务器的用户密码


$from = "";//SMTP服务器的用户邮箱
$to = "";//发送给谁 可用逗号隔开多个邮箱
$cc = "";
$bcc = "";

$subject="这是一个由PHP发送的带附件的邮件";//邮件主题 很多客户端会有乱码,所以转一下码
$body = "这个是一个带附件的邮件发送程序<hr>看到没,这里显示了HTM标签哦;<a href="'http://www.google.com/'">请点开链接</a><input type="'button'" id="'aaa'" name='\"aaa\"'> ".date('Y-m-d H:i:s');//邮件内容
$smtp = new smtp(SMTP_HOST,SMTP_PORT,SMTP_USER,SMTP_PASS, true);//这里面的一个true是表示使用身份验证,否则不使用身份验证.
$smtp->addAttachment("mail.zip");
$smtp->sendmail($to, $from, $subject, $body, $cc, $bcc);


class smtp {

	/* Public Variables */
	public $attachments = array();
	/* Private Variables */
	private $smtp_host;
	private $smtp_port;
	private $time_out;
	private $host_name;
	private $auth;
	private $user;
	private $pass;
	private $sock;

	/* Constractor */
	public function smtp($smtp_host = null, $smtp_port = null, $user = null, $pass = null, $auth = true) {
		$this->smtp_host = (!empty($smtp_host)) ? $smtp_host : SMTP_HOST;
		$this->smtp_port = (!empty($smtp_port)) ? $smtp_port : SMTP_PORT;
		$this->user = (!empty($user)) ? $user : SMTP_PORT;
		$this->pass = (!empty($pass)) ? $pass : SMTP_PORT;
		$this->auth = $auth;
		$this->time_out = 15;
		#
		$this->host_name = "localhost";
		$this->sock = FALSE;
	}

	/* Main Function */
	public function sendmail($to, $from, $subject = "", $body = "", $cc = "", $bcc = "") {
		$bndp = md5(uniqid("")) . rand(1000, 9999);
		$bnd  = md5(uniqid("")) . rand(1000, 9999);
		list ($msec, $sec) = explode(" ", microtime());

		$mail_from = $this->strip_line_breaks($from);
		$mail_to = explode(",", $to);
		$body = preg_replace("/(^|(\r\n))(\\.)/", "", $body);
		if ($cc != "") $mail_to = array_merge($mail_to, explode(",", $cc));
		if ($bcc != "") $mail_to = array_merge($mail_to, explode(",", $bcc));

		$headers  = "MIME-Version:1.0" . EOL;
		$headers .= "To: " . $to . EOL;
		if ($cc != "") {
		$headers .= "Cc: " . $cc . EOL;
		}
		$headers .= "From: $from" . EOL;
		$headers .= "Subject: " . $subject . EOL;
		$headers .= "Date: " . date("r") . EOL;
		$headers .= "X-Mailer: Webmail ver 1.0 (PHP Version/" . phpversion() . ")" . EOL;
		$headers .= "Message-ID: " . EOL;
		if (count($this->attachments) > 0) {
			$headers .= "Content-Type: multipart/mixed;" . EOL . chr(9) . " boundary=\"" . $bndp . "\"" . EOL . EOL;
			$headers .= '--'.$bndp . EOL;
			$headers .= 'Content-Type : multipart/alternative; boundary="' . $bnd . '"' . EOL . EOL;
			$headers .= '--' . $bnd . EOL;
			$headers .= 'Content-Type: text/plain; charset=utf-8' . EOL;
			$headers .= "Content-Transfer-Encoding: 8bit" . EOL . EOL;
			$headers .= $body . EOL;
			$headers .= '--' . $bnd . EOL;
			$headers .= 'Content-type: text/html; charset=utf-8' . EOL;
			$headers .= "Content-Transfer-Encoding: 8bit" . EOL . EOL;
			$headers .= $body . EOL;
			$headers .= '--' . $bnd . '--' . EOL;

			foreach ($this->attachments as $att) {
				$headers .= "--" . $bndp . EOL . $att;
			}
			$headers .= '--' . $bndp . '--' . EOL;
			$this->clear_attachments();
		} else {
			$headers .= 'Content-Type : multipart/alternative;boundary="'.$bnd.'"' . EOL . EOL;
			$headers .= '--'.$bnd . EOL;
			$headers .= 'Content-Type: text/plain; charset=utf-8' . EOL;
			$headers .= "Content-Transfer-Encoding: 8bit" . EOL . EOL;
			$headers .= $body . EOL;
			$headers .= '--'.$bnd . EOL;
			$headers .= 'Content-type: text/html; charset=utf-8' . EOL;
			$headers .= "Content-Transfer-Encoding: 8bit" . EOL . EOL;
			$headers .= $body . EOL;
			$headers .= '--'.$bnd.'--' . EOL;
		}

		$sent = TRUE;
		foreach ($mail_to as $rcpt_to) {
			$rcpt_to = $this->strip_line_breaks($rcpt_to);
			if (!$this->smtp_sockopen($rcpt_to)) {
				$this->log_write("Error: Cannot send email to " . $rcpt_to);
				$sent = FALSE;
				continue;
			}
			if ($this->smtp_send($this->host_name, $mail_from, $rcpt_to, $headers, $body)) {
				$this->log_write("E-mail has been sent to ");
			} else {
				$this->log_write("Error: Cannot send email to ");
				$sent = FALSE;
			}
			fclose($this->sock);
		}
		$this->log_write("{$mail_to} send over;");
		return $sent;
	}

	public function addAttachment($file, $dispo = "attachment") {
		$file_data = (file_exists($file)) ? file_get_contents($file) : "";
		if ($file_data != "") {
			$filename = basename($file);
			$ext = pathinfo($filename, PATHINFO_EXTENSION);
			$chunks = chunk_split(base64_encode($file_data));
			$parts  = "Content-Type: application/$ext; name=\"" . $filename . "\"" . EOL;
			$parts .= "Content-Transfer-Encoding: base64" . EOL;
			$parts .= "Content-Disposition: " . $dispo . "; filename=\"" . $filename . "\"" . EOL . EOL;
			$parts .= $chunks . EOL . EOL;
			$this->attachments[] = $parts;
		}
	}

	private function clear_attachments() {
		unset($this->attachments);
		$this->attachments = array();
	}

	/* Private Functions */
	private function smtp_send($helo, $from, $to, $header, $body = "") {
		if (!$this->smtp_putcmd("HELO", $helo)) {
			//$this->log_write("Error: Error occurred while sending HELO command.");
			return FALSE;
		}
		#auth
		if ($this->auth) {
			if (!$this->smtp_putcmd("AUTH LOGIN", base64_encode($this->user))) {
				//$this->log_write("Error: Error occurred while sending HELO command.");
				return FALSE;
			}
			if (!$this->smtp_putcmd("", base64_encode($this->pass))) {
				//$this->log_write("Error: Error occurred while sending HELO command.");
				return FALSE;
			}
		}
		if (!$this->smtp_putcmd("MAIL", "FROM:")) {
			//$this->log_write("Error: Error occurred while sending MAIL FROM command.");
			return FALSE;
		}
		if (!$this->smtp_putcmd("RCPT", "TO:")) {
			//$this->log_write("Error: Error occurred while sending RCPT TO command.");
			return FALSE;
		}
		if (!$this->smtp_putcmd("DATA")) {
			//$this->log_write("Error: Error occurred while sending DATA command.");
			return FALSE;
		}
		if (!$this->smtp_message($header, $body)) {
			//$this->log_write("Error: Error occurred while sending message.");
			return FALSE;
		}
		if (!$this->smtp_eom()) {
			//$this->log_write("Error: Error occurred while sending <cr><lf>.<cr><lf> [EOM].");
			return FALSE;
		}
		if (!$this->smtp_putcmd("QUIT")) {
			//$this->log_write("Error: Error occurred while sending QUIT command.");
			return FALSE;
		}
		return TRUE;
	}
	private function smtp_sockopen($address) {
		if ($this->smtp_host == "") {
			return $this->smtp_sockopen_mx($address);
		} else {
			return $this->smtp_sockopen_relay();
		}
	}
	private function smtp_sockopen_relay() {
		$this->log_write("Trying to Connect " . $this->smtp_host . ":" . $this->smtp_port . "...");
		$this->sock = @fsockopen($this->smtp_host, $this->smtp_port, $errno, $errstr, $this->time_out);
		if (!($this->sock && $this->smtp_ok())) {
			$this->log_write("Error: connenct error" . $errstr . " (" . $errno . ")");
			return FALSE;
		}
		$this->log_write("Connected Ok");
		return TRUE;
	}
	private function smtp_sockopen_mx($address) {
		$domain = preg_replace("/^.+@([^@]+)$/", "\1", $address);
		if (!@getmxrr($domain, $MXHOSTS)) {
			$this->log_write("Error: Cannot resolve MX \"" . $domain . "\"");
			return FALSE;
		}
		foreach ($MXHOSTS as $host) {
			$this->log_write("Trying to " . $host . ":" . $this->smtp_port);
			$this->sock = @fsockopen($host, $this->smtp_port, $errno, $errstr, $this->time_out);
			if (!($this->sock && $this->smtp_ok())) {
				$this->log_write("Connect Error ," . $errstr . " (" . $errno . ")");
				continue;
			}
			$this->log_write("Connected to mx host " . $host);
			return TRUE;
		}
		$this->log_write("Error: Cannot connect to any mx hosts (" . implode(", ", $MXHOSTS) . ")");
		return FALSE;
	}
	private function smtp_message($header, $body) {
		fputs($this->sock, $header . "\r\n" . $body);
		return TRUE;
	}
	private function smtp_eom() {
		fputs($this->sock, "\r\n.\r\n");
		return $this->smtp_ok();
	}
	private function smtp_ok() {
		$response = str_replace("\r\n", "", fgets($this->sock, 512));
		if (!preg_match("/^[23]/", $response)) {
			fputs($this->sock, "QUIT\r\n");
			fgets($this->sock, 512);
			$this->log_write("Error: Remote host returned \"" . $response . "\"");
			return FALSE;
		}
		return TRUE;
	}
	private function smtp_putcmd($cmd, $arg = "") {
		if ($arg != "") $cmd = ($cmd == "") ? $arg : ($cmd . " " . $arg);
		fputs($this->sock, $cmd . "\r\n");
		return $this->smtp_ok();
	}
	private function strip_line_breaks($address) {
		$address = preg_replace("/([\t\r\n])+/", "", $address);
		$address = preg_replace("/^.*.*$/", "", $address);
		return $address;
	}
	public function log_write($message) {
		$message = date("M d H:i:s ") . get_current_user() . "[" . getmypid() . "]: " . $message;
		file_put_contents(dirname(__FILE__) . '/mail.log', $message . PHP_EOL, FILE_APPEND | LOCK_EX);
	}
}</lf></cr></lf></cr>
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 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)

IO multiplexing of PHP+Socket series and implementation of web server IO multiplexing of PHP+Socket series and implementation of web server Feb 02, 2023 pm 01:43 PM

This article brings you relevant knowledge about php+socket, which mainly introduces IO multiplexing and how php+socket implements web server? Friends who are interested can take a look below. I hope it will be helpful to everyone.

How to use Python's socket and socketserver How to use Python's socket and socketserver May 28, 2023 pm 08:10 PM

1. Socket programming based on TCP protocol 1. The socket workflow starts with the server side. The server first initializes the Socket, then binds to the port, listens to the port, calls accept to block, and waits for the client to connect. At this time, if a client initializes a Socket and then connects to the server (connect), if the connection is successful, the connection between the client and the server is established. The client sends a data request, the server receives the request and processes the request, then sends the response data to the client, the client reads the data, and finally closes the connection. An interaction ends. Use the following Python code to implement it: importso

How to use Spring Boot+Vue to implement Socket notification push How to use Spring Boot+Vue to implement Socket notification push May 27, 2023 am 08:47 AM

The first step on the SpringBoot side is to introduce dependencies. First we need to introduce the dependencies required for WebSocket, as well as the dependencies for processing the output format com.alibabafastjson1.2.73org.springframework.bootspring-boot-starter-websocket. The second step is to create the WebSocket configuration class importorg. springframework.context.annotation.Bean;importorg.springframework.context.annotation.Config

What to do if php socket cannot connect What to do if php socket cannot connect Nov 09, 2022 am 10:34 AM

Solution to the problem that the php socket cannot be connected: 1. Check whether the socket extension is enabled in php; 2. Open the php.ini file and check whether "php_sockets.dll" is loaded; 3. Uncomment "php_sockets.dll".

Common network communication and security problems and solutions in C# Common network communication and security problems and solutions in C# Oct 09, 2023 pm 09:21 PM

Common network communication and security problems and solutions in C# In today's Internet era, network communication has become an indispensable part of software development. In C#, we usually encounter some network communication problems, such as data transmission security, network connection stability, etc. This article will discuss in detail common network communication and security issues in C# and provide corresponding solutions and code examples. 1. Network communication problems Network connection interruption: During the network communication process, the network connection may be interrupted, which may cause

Methods and techniques for implementing Socket communication in PHP Methods and techniques for implementing Socket communication in PHP Mar 07, 2024 pm 02:06 PM

PHP is a commonly used development language that can be used to develop various web applications. In addition to common HTTP requests and responses, PHP also supports network communication through Sockets to achieve more flexible and efficient data interaction. This article will introduce the methods and techniques of how to implement Socket communication in PHP, and attach specific code examples. What is Socket Communication Socket is a method of communication in a network that can transfer data between different computers. by S

PHP+Socket series realizes data transmission between client and server PHP+Socket series realizes data transmission between client and server Feb 02, 2023 am 11:35 AM

This article brings you relevant knowledge about php+socket. It mainly introduces what is socket? How does php+socket realize client-server data transmission? Friends who are interested can take a look below. I hope it will be helpful to everyone.

Research on real-time file transfer technology using PHP and Socket Research on real-time file transfer technology using PHP and Socket Jun 28, 2023 am 09:11 AM

With the development of the Internet, file transfer has become an indispensable part of people's daily work and entertainment. However, traditional file transfer methods such as email attachments or file sharing websites have certain limitations and cannot meet the needs of real-time and security. Therefore, using PHP and Socket technology to achieve real-time file transfer has become a new solution. This article will introduce the technical principles, advantages and application scenarios of using PHP and Socket technology to achieve real-time file transfer, and demonstrate the implementation method of this technology through specific cases. technology

See all articles