本文介绍下,一个用于email邮件发送的类,可以使用smtp与mail函数二种方式发送邮件,有需要的朋友参考下。
php实现的邮件发送类,二种方式: smtp方式与mail函数方式。 代码: <?php /** * 邮件发送类 * by bbs.it-home.org */ Class sendmail{ public $smtp_host; public $smtp_port = 25; public $smtp_user; public $smtp_password; public $from_name; public $SendFromMail; public $mail_to; public $subject; public $message; public $headers = ''; public $ContentType = 'html'; public $charset = 'windows-1251'; public $smtp_debug = true; public $socket; public $error; public $SendMailVia = 'smtp'; public function __construct() { if($this->SendFromMail == ''){ $this->SendFromMail = $this->smtp_user; } } public function Send($mail_to = '', $subject = '', $message = '') { if($mail_to!=''){$this->mail_to = stripslashes($mail_to);} if($subject!=''){$this->subject = stripslashes($subject);} if($message!=''){$this->message = $message;} $meilsArr = array_filter($this->GetMailAndNameArr()); if(trim($this->mail_to)==''){$this->error = 'Enter the recipient address'; } if($meilsArr == array()){$this->error = 'Please enter a valid recipient address'; } foreach ($meilsArr as $val) { $validEmail = $this->validEmail($val[2]); if($validEmail) { if($this->SendMailVia=='smtp'){ return $this->SMTPsend($mail_to = $val[2], $name_to = $val[1]); } else{ return $this->MAILsend($mail_to = $val[2], $name_to = $val[1]); } } } } public function MAILsend($mail_to, $name_to) { if($this->ContentType=="text"){ $header="Content-Type: text/plain; charset=".$this->charset.""; } else{ $header="Return-Path: ".$this->smtp_user."\n". "Reply-To: ".$this->SendFromMail."\n". "From: ".$this->from_name." <".$this->SendFromMail.">\n". "Subject: ".$this->subject."\n". "Content-Type: text/html; charset=".$this->charset."\n"; } if(mail("$name_to <$mail_to>",$this->subject,$this->message,$header)){ return true; }else{ return false; } } public function SMTPsend($mail_to, $name_to) { $SEND = "Date: ".date("D, d M Y H:i:s") . "\r\n"; $SEND .= 'Subject: =?'.$this->charset.'?B?'.base64_encode($this->subject)."=?=\r\n"; if ($this->headers!=''){ $SEND .= $this->headers."\r\n\r\n"; } else { $SEND .= "Reply-To: ".$this->SendFromMail."\r\n"; $SEND .= "MIME-Version: 1.0\r\n"; $SEND .= "Content-Type: text/".$this->ContentType."; charset=\"".$this->charset."\"\r\n"; $SEND .= "Content-Transfer-Encoding: 8bit\r\n"; $SEND .= "From: \"".$this->from_name."\" <".$this->SendFromMail.">\r\n"; $SEND .= "To: $name_to <$mail_to>\r\n"; $SEND .= "X-Priority: 3\r\n\r\n"; } $SEND .= $this->message."\r\n"; $socket = fsockopen($this->smtp_host, $this->smtp_port, $errno, $errstr, 30); if(!socket) { if($this->smtp_debug) $this->error = $errno." - ".$errstr; return false; } if (!$this->server_parse($socket, "220", __LINE__)){ return false; } fputs($socket, "HELO ".$this->smtp_host. "\r\n"); if (!$this->server_parse($socket, "250", __LINE__)) { if ($this->smtp_debug) $this->error = '<p>Can not send HELO!</p>'; fclose($socket); return false; } fputs($socket, "AUTH LOGIN\r\n"); if (!$this->server_parse($socket, "334", __LINE__)) { if ($this->smtp_debug) $this->error = '<p>Can not find an answer to a request authorization.</p>'; fclose($socket); return false; } fputs($socket, base64_encode($this->smtp_user) . "\r\n"); if (!$this->server_parse($socket, "334", __LINE__)) { if ($this->smtp_debug) $this->error = '<p>Login authorization was not accepted by server!</p>'; fclose($socket); return false; } fputs($socket, base64_encode($this->smtp_password) . "\r\n"); if (!$this->server_parse($socket, "235", __LINE__)) { if ($this->smtp_debug) $this->error = '<p>No password was not accepted as a true server! Authorization Error!</p>'; fclose($socket); return false; } fputs($socket, "MAIL FROM: <".$this->smtp_user.">\r\n"); if (!$this->server_parse($socket, "250", __LINE__)) { if ($this->smtp_debug) $this->error = '<p>Unable to send command MAIL FROM: </p>'; fclose($socket); return false; } fputs($socket, "RCPT TO: <" . $mail_to . ">\r\n"); if (!$this->server_parse($socket, "250", __LINE__)) { if ($this->smtp_debug) $this->error = '<p>Unable to send command RCPT TO: </p>'; fclose($socket); return false; } fputs($socket, "DATA\r\n"); if (!$this->server_parse($socket, "354", __LINE__)) { if ($this->smtp_debug) $this->error = '<p>Unable to send command DATA</p>'; fclose($socket); return false; } fputs($socket, $SEND."\r\n.\r\n"); if (!$this->server_parse($socket, "250", __LINE__)) { if ($this->smtp_debug) $this->error = '<p>Unable to send the message body. The letter was sent!</p>'; fclose($socket); return false; } fputs($socket, "QUIT\r\n"); fclose($socket); return TRUE; } private function GetMailAndNameArr(){ $mailingArr = array(); $tos = preg_split("/;|,/",$this->mail_to); $pregcode = '/(.*?)<(.*?)>/i'; foreach($tos as $to) { if(preg_match('/(.*?)<(.*?)>/i',$to,$matches)) { unset($matches[0]); $matches[1] = trim(str_replace('"','',$matches[1])); $matches[2] = trim($matches[2]); $mailingArr[] =$matches; } elseif(preg_match('/\b([A-Z0-9._%-]+)@([A-Z0-9.-]+\.[A-Z]{2,4})\b/i',$to,$matches2)) { unset($matches[0]); $matches[1] = trim(str_replace('"','',$matches2[1])); $matches[2] = trim($matches2[0]); $mailingArr[] =$matches; } } return $mailingArr; } private function server_parse($socket, $response, $line = __LINE__) { while (substr($server_response, 3, 1) != ' ') { if (!($server_response = fgets($socket, 256))) { if ($this->smtp_debug) $this->error = "<p>$line Problems sending mail! $response</p>"; return false; } } if (!(substr($server_response, 0, 3) == $response)) { if ($this->smtp_debug) $this->error = "<p>$line Problems sending mail! $response</p>"; return false; } return true; } function validEmail($email) { $isValid = true; $atIndex = strrpos($email, "@"); $msg = ''; if (is_bool($atIndex) && !$atIndex) { $isValid = false; } else { $domain = substr($email, $atIndex+1); $local = substr($email, 0, $atIndex); $localLen = strlen($local); $domainLen = strlen($domain); if ($localLen < 1 || $localLen > 64){ $msg = 'local part length exceeded'; $isValid = false; } else if ($domainLen < 1 || $domainLen > 255){ $msg = ' domain part length exceeded '; $isValid = false; } else if ($local[0] == '.' || $local[$localLen-1] == '.'){ $msg = ' local part starts or ends with .'; $isValid = false; } else if (preg_match('/\\.\\./', $local)){ $msg = 'local part has two consecutive dots'; $isValid = false; } else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)){ $msg = 'character not valid in domain part'; $isValid = false; } else if (preg_match('/\\.\\./', $domain)){ $msg = ' domain part has two consecutive dots'; $isValid = false; } else if(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local))){ $msg = ' character not valid in local part unless local part is quoted'; if (!preg_match('/^"(\\\\"|[^"])+"$/',str_replace("\\\\","",$local))){ $isValid = false; } } if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"))){ $msg = ' domain <b>'.$domain.'</b> not found in DNS'; $isValid = false; } } $this->error = $msg; return $isValid; } } ?> 调用示例: <?php include "sendmail.class.php"; $Mail = new sendmail(); // Set congif $Mail->SendMailVia = 'smtp'; // Send via smtp server or mail function $Mail->smtp_host = 'mail.myhost.com'; $Mail->smtp_port = 25; $Mail->smtp_user = 'user@myhost.com'; $Mail->smtp_password = 'mypassw'; // 例1 (mail from me) if($Mail->Send('mymail1@mydomain.com; recipient2 name <recipientmail2@mydomain.com>,"recipient name" <recipient@mail.com>', 'My subject','My message here.')) { echo '邮件已发送!'; } else { echo $Mail->error; } // 例2 (mail from me) $Mail->mail_to = 'mymail1@mydomain.com; recipient2 name <recipientmail2@mydomain.com>,"recipient name" <recipient@mail.com>'; $Mail->subject = 'My subject'; $Mail->message = 'My message here'; if($Mail->Send()) { echo '邮件已发送!'; } else { echo $Mail->error; } // 例3 (mail from another user: example user2@site2.com) $Mail->mail_to = 'Recipient Name <recipientmail@domain.com>'; $Mail->subject = 'My subject'; $Mail->message = 'My message here'; $Mail->from_name = 'User2 Name'; $Mail->SendFromMail = 'user2@site2.com'; if($Mail->Send()) { echo 'message Mail send!'; } else { echo $Mail->error; } ?> |

PHP는 동적 웹 사이트를 구축하는 데 사용되며 해당 핵심 기능에는 다음이 포함됩니다. 1. 데이터베이스와 연결하여 동적 컨텐츠를 생성하고 웹 페이지를 실시간으로 생성합니다. 2. 사용자 상호 작용 및 양식 제출을 처리하고 입력을 확인하고 작업에 응답합니다. 3. 개인화 된 경험을 제공하기 위해 세션 및 사용자 인증을 관리합니다. 4. 성능을 최적화하고 모범 사례를 따라 웹 사이트 효율성 및 보안을 개선하십시오.

PHP는 MySQLI 및 PDO 확장 기능을 사용하여 데이터베이스 작업 및 서버 측 로직 프로세싱에서 상호 작용하고 세션 관리와 같은 기능을 통해 서버 측로 로직을 처리합니다. 1) MySQLI 또는 PDO를 사용하여 데이터베이스에 연결하고 SQL 쿼리를 실행하십시오. 2) 세션 관리 및 기타 기능을 통해 HTTP 요청 및 사용자 상태를 처리합니다. 3) 트랜잭션을 사용하여 데이터베이스 작업의 원자력을 보장하십시오. 4) SQL 주입 방지, 디버깅을 위해 예외 처리 및 폐쇄 연결을 사용하십시오. 5) 인덱싱 및 캐시를 통해 성능을 최적화하고, 읽을 수있는 코드를 작성하고, 오류 처리를 수행하십시오.

PHP에서 전처리 문과 PDO를 사용하면 SQL 주입 공격을 효과적으로 방지 할 수 있습니다. 1) PDO를 사용하여 데이터베이스에 연결하고 오류 모드를 설정하십시오. 2) 준비 방법을 통해 전처리 명세서를 작성하고 자리 표시자를 사용하여 데이터를 전달하고 방법을 실행하십시오. 3) 쿼리 결과를 처리하고 코드의 보안 및 성능을 보장합니다.

PHP와 Python은 고유 한 장점과 단점이 있으며 선택은 프로젝트 요구와 개인 선호도에 달려 있습니다. 1.PHP는 대규모 웹 애플리케이션의 빠른 개발 및 유지 보수에 적합합니다. 2. Python은 데이터 과학 및 기계 학습 분야를 지배합니다.

PHP는 전자 상거래, 컨텐츠 관리 시스템 및 API 개발에 널리 사용됩니다. 1) 전자 상거래 : 쇼핑 카트 기능 및 지불 처리에 사용됩니다. 2) 컨텐츠 관리 시스템 : 동적 컨텐츠 생성 및 사용자 관리에 사용됩니다. 3) API 개발 : 편안한 API 개발 및 API 보안에 사용됩니다. 성능 최적화 및 모범 사례를 통해 PHP 애플리케이션의 효율성과 유지 보수 성이 향상됩니다.

PHP를 사용하면 대화식 웹 컨텐츠를 쉽게 만들 수 있습니다. 1) HTML을 포함하여 컨텐츠를 동적으로 생성하고 사용자 입력 또는 데이터베이스 데이터를 기반으로 실시간으로 표시합니다. 2) 프로세스 양식 제출 및 동적 출력을 생성하여 htmlspecialchars를 사용하여 XSS를 방지합니다. 3) MySQL을 사용하여 사용자 등록 시스템을 작성하고 Password_Hash 및 전처리 명세서를 사용하여 보안을 향상시킵니다. 이러한 기술을 마스터하면 웹 개발의 효율성이 향상됩니다.

PHP와 Python은 각각 고유 한 장점이 있으며 프로젝트 요구 사항에 따라 선택합니다. 1.PHP는 웹 개발, 특히 웹 사이트의 빠른 개발 및 유지 보수에 적합합니다. 2. Python은 간결한 구문을 가진 데이터 과학, 기계 학습 및 인공 지능에 적합하며 초보자에게 적합합니다.

PHP는 여전히 역동적이며 현대 프로그래밍 분야에서 여전히 중요한 위치를 차지하고 있습니다. 1) PHP의 단순성과 강력한 커뮤니티 지원으로 인해 웹 개발에 널리 사용됩니다. 2) 유연성과 안정성은 웹 양식, 데이터베이스 작업 및 파일 처리를 처리하는 데 탁월합니다. 3) PHP는 지속적으로 발전하고 최적화하며 초보자 및 숙련 된 개발자에게 적합합니다.


핫 AI 도구

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

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

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

SecList
SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

Dreamweaver Mac版
시각적 웹 개발 도구

PhpStorm 맥 버전
최신(2018.2.1) 전문 PHP 통합 개발 도구
