搜尋
首頁後端開發php教程php socket通过smtp发送邮件(可带附件)

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>

 


陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
可以在PHP會話中存儲哪些數據?可以在PHP會話中存儲哪些數據?May 02, 2025 am 12:17 AM

phpsessionscanStorestrings,數字,數組和原始物。

您如何開始PHP會話?您如何開始PHP會話?May 02, 2025 am 12:16 AM

tostartaphpsession,usesesses_start()attheScript'Sbeginning.1)placeitbeforeanyOutputtosetThesessionCookie.2)useSessionsforuserDatalikeloginstatusorshoppingcarts.3)regenerateSessiveIdStopreventFentfixationAttacks.s.4)考慮使用AttActAcks.s.s.4)

什麼是會話再生,如何提高安全性?什麼是會話再生,如何提高安全性?May 02, 2025 am 12:15 AM

會話再生是指在用戶進行敏感操作時生成新會話ID並使舊ID失效,以防會話固定攻擊。實現步驟包括:1.檢測敏感操作,2.生成新會話ID,3.銷毀舊會話ID,4.更新用戶端會話信息。

使用PHP會話時有哪些性能考慮?使用PHP會話時有哪些性能考慮?May 02, 2025 am 12:11 AM

PHP会话对应用性能有显著影响。优化方法包括:1.使用数据库存储会话数据,提升响应速度;2.减少会话数据使用,只存储必要信息;3.采用非阻塞会话处理器,提高并发能力;4.调整会话过期时间,平衡用户体验和服务器负担;5.使用持久会话,减少数据读写次数。

PHP會話與Cookie有何不同?PHP會話與Cookie有何不同?May 02, 2025 am 12:03 AM

PHPsessionsareserver-side,whilecookiesareclient-side.1)Sessionsstoredataontheserver,aremoresecure,andhandlelargerdata.2)Cookiesstoredataontheclient,arelesssecure,andlimitedinsize.Usesessionsforsensitivedataandcookiesfornon-sensitive,client-sidedata.

PHP如何識別用戶的會話?PHP如何識別用戶的會話?May 01, 2025 am 12:23 AM

phpIdentifiesauser'ssessionSessionSessionCookiesAndSessionId.1)whiwsession_start()被稱為,phpgeneratesainiquesesesessionIdStoredInacookInAcookInAcienamedInAcienamedphpsessIdontheuser'sbrowser'sbrowser.2)thisIdallowSphptpptpptpptpptpptpptpptoretoreteretrieetrieetrieetrieetrieetrieetreetrieetrieetrieetrieetremthafromtheserver。

確保PHP會議的一些最佳實踐是什麼?確保PHP會議的一些最佳實踐是什麼?May 01, 2025 am 12:22 AM

PHP會話的安全可以通過以下措施實現:1.使用session_regenerate_id()在用戶登錄或重要操作時重新生成會話ID。 2.通過HTTPS協議加密傳輸會話ID。 3.使用session_save_path()指定安全目錄存儲會話數據,並正確設置權限。

PHP會話文件默認存儲在哪裡?PHP會話文件默認存儲在哪裡?May 01, 2025 am 12:15 AM

phpsessionFilesArestoredIntheDirectorySpecifiedBysession.save_path,通常是/tmponunix-likesystemsorc:\ windows \ windows \ temponwindows.tocustomizethis:tocustomizEthis:1)useession_save_save_save_path_path()

See all articles

熱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

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用