찾다
백엔드 개발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 01, 2025 am 12:23 AM

phpidifiesauser의 sssessionusessessioncookiesandssessionids.1) whensession_start () iscalled, phpgeneratesauniquessessionStoredInacookienamedPhpsSessIdonSeuser 'sbrowser.2) thisidallowsphptoretrievessessionDataTromServer.

PHP 세션을 확보하기위한 모범 사례는 무엇입니까?PHP 세션을 확보하기위한 모범 사례는 무엇입니까?May 01, 2025 am 12:22 AM

PHP 세션의 보안은 다음 측정을 통해 달성 할 수 있습니다. 1. Session_REGENEREAT_ID ()를 사용하여 사용자가 로그인하거나 중요한 작업 일 때 세션 ID를 재생합니다. 2. HTTPS 프로토콜을 통해 전송 세션 ID를 암호화합니다. 3. 세션 _save_path ()를 사용하여 세션 데이터를 저장하고 권한을 올바르게 설정할 보안 디렉토리를 지정하십시오.

PHP 세션 파일은 기본적으로 어디에 저장됩니까?PHP 세션 파일은 기본적으로 어디에 저장됩니까?May 01, 2025 am 12:15 AM

phpsessionfilesarestoredInTheRectorySpecifiedBysession.save_path, 일반적으로/tmponunix-likesystemsorc : \ windows \ temponwindows.tocustomizethis : 1) austession_save_path () toSetacustomDirectory, verlyTeCustory-swritation;

PHP 세션에서 데이터를 어떻게 검색합니까?PHP 세션에서 데이터를 어떻게 검색합니까?May 01, 2025 am 12:11 AM

toretrievedatafromAphPsession, startSessionstart_start () andaccessvariblesinthe $ _sessionArray.forexample : 1) startthessession : session_start (). 2) retrievedata : $ _ session [ 'username']; echo "Welcome,". $ username;

세션을 사용하여 쇼핑 카트를 구현할 수있는 방법은 무엇입니까?세션을 사용하여 쇼핑 카트를 구현할 수있는 방법은 무엇입니까?May 01, 2025 am 12:10 AM

세션을 사용하여 효율적인 쇼핑 카트 시스템을 구축하는 단계에는 다음이 포함됩니다. 1) 세션의 정의와 기능을 이해합니다. 세션은 요청에 따라 사용자 상태를 유지하는 데 사용되는 서버 측 스토리지 메커니즘입니다. 2) 쇼핑 카트에 제품 추가와 같은 기본 세션 관리를 구현합니다. 3) 제품 수량 관리 및 삭제 지원 고급 사용으로 확장; 4) 세션 데이터를 지속하고 보안 세션 식별자를 사용하여 성능 및 보안을 최적화합니다.

PHP에서 인터페이스를 어떻게 생성하고 사용합니까?PHP에서 인터페이스를 어떻게 생성하고 사용합니까?Apr 30, 2025 pm 03:40 PM

이 기사는 PHP의 인터페이스를 생성, 구현 및 사용하는 방법을 설명하여 코드 구성 및 유지 관리에 대한 이점에 중점을 둡니다.

crypt ()와 password_hash ()의 차이점은 무엇입니까?crypt ()와 password_hash ()의 차이점은 무엇입니까?Apr 30, 2025 pm 03:39 PM

이 기사에서는 PHP의 암호 해싱에 대한 Crypt ()와 Password_hash ()의 차이점에 대해 논의하여 최신 웹 애플리케이션에 대한 구현, 보안 및 적합성에 중점을 둡니다.

PHP의 크로스 사이트 스크립팅 (XSS)을 어떻게 방지 할 수 있습니까?PHP의 크로스 사이트 스크립팅 (XSS)을 어떻게 방지 할 수 있습니까?Apr 30, 2025 pm 03:38 PM

기사는 입력 유효성 검사, 출력 인코딩 및 OWASP ESAPI 및 HTML 청정기와 같은 도구를 통해 PHP의 크로스 사이트 스크립팅 (XSS) 방지에 대해 논의합니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

안전한 시험 브라우저

안전한 시험 브라우저

안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.