이 기사에서는 PHP에서 IMAP을 사용하여 이메일을 보내고 받고, 이메일을 삭제하고, 첨부 파일을 다운로드하는 방법을 소개합니다.
PHP에서 Imap 인스턴스의 전체 코드는 다음과 같습니다. 코드 복사 코드 예:* @version $$Id: Email.php 175 2011-03-26 09:52:16Z chen.qiao $$ * @copyright Copyright (c) 2011 jbxue Inc. 중국(http://bbs.it-home.org) */ /*** 이메일 수업
*
* 메일 총 개수 가져오기, 메일 목록 가져오기, 메일 내용 가져오기, 메일 첨부 가져오기
*
* 예를 들어, 지정된 이메일 목록을 얻으려는 경우.
* /*** __클래스의 구성*/ 공개 함수 __construct() { $this->_contentType = 배열( 'ez' => '응용 프로그램/andrew-inset','hqx' => '응용 프로그램/mac-binhex40', 'cpt' => '응용 프로그램/mac-compactpro','doc' => '응용 프로그램/msword', 'bin' => '응용 프로그램/옥텟 스트림','dms' => '응용 프로그램/옥텟 스트림', 'lha' => '응용 프로그램/옥텟 스트림','lzh' => '응용 프로그램/옥텟 스트림', 'exe' => '응용 프로그램/옥텟 스트림','클래스' => '응용 프로그램/옥텟 스트림', 'so' => '응용 프로그램/옥텟 스트림','dll' => '응용 프로그램/옥텟 스트림', 'oda' => '응용 프로그램/oda','pdf' => '응용 프로그램/pdf', 'ai' => '응용 프로그램/포스트스크립트','eps' => '응용 프로그램/포스트스크립트', 'ps' => '응용 프로그램/포스트스크립트','smi' => '응용 프로그램/smil', 'smil' => '응용 프로그램/smil','mif' => '응용 프로그램/vnd.mif', 'xls' => 'application/vnd.ms-excel','ppt' => 'application/vnd.ms-powerpoint', 'wbxml' => 'application/vnd.wap.wbxml','wmlc' => 'application/vnd.wap.wmlc', 'wmlsc' => 'application/vnd.wap.wmlscriptc','bcpio' => 'application/x-bcpio', 'vcd' => '응용 프로그램/x-cdlink','pgn' => '응용 프로그램/x-chess-pgn', 'cpio' => '응용 프로그램/x-cpio','csh' => '응용 프로그램/x-csh', 'dcr' => '응용 프로그램/x-디렉터','dir' => '응용 프로그램/x-디렉터', 'dxr' => '응용 프로그램/x-디렉터','dvi' => '응용 프로그램/x-dvi', 'spl' => '응용 프로그램/x-futuresplash','gtar' => '응용 프로그램/x-gtar', 'hdf' => '응용 프로그램/x-hdf','js' => '응용 프로그램/x-javascript', 'skp' => '응용 프로그램/x-koan','skd' => '응용 프로그램/x-koan', 'skt' => '응용 프로그램/x-koan','skm' => '응용 프로그램/x-koan', 'latex' => '응용 프로그램/x-latex','nc' => '응용 프로그램/x-netcdf', 'cdf' => '응용 프로그램/x-netcdf','sh' => '응용 프로그램/x-sh', 'shar' => '응용 프로그램/x-shar','swf' => '응용 프로그램/x-shockwave-flash', '앉아' => '응용 프로그램/x-stuffit','sv4cpio' => '응용 프로그램/x-sv4cpio', 'sv4crc' => '응용 프로그램/x-sv4crc','tar' => '응용 프로그램/x-tar', 'tcl' => '응용 프로그램/x-tcl','tex' => '응용 프로그램/x-tex', 'texinfo' => '응용 프로그램/x-texinfo','texi' => '응용 프로그램/x-texinfo', 't' => '응용 프로그램/x-troff','tr' => '응용 프로그램/x-troff', 'roff' => '응용 프로그램/x-troff','man' => '응용 프로그램/x-troff-man', '나' => '응용 프로그램/x-troff-me','ms' => '응용 프로그램/x-troff-ms', 'ustar' => '응용 프로그램/x-ustar','src' => '응용 프로그램/x-wais-소스', 'xhtml' => '응용 프로그램/xhtml xml','xht' => '응용 프로그램/xhtml xml', 'zip' => '응용 프로그램/zip','au' => '오디오/기본','snd' => '오디오/기본', 'mid' => '오디오/미디','midi' => '오디오/미디','kar' => '오디오/미디', 'mpga' => '오디오/mpeg','mp2' => '오디오/mpeg','mp3' => '오디오/mpeg', 'aif' => '오디오/x-aiff','aiff' => '오디오/x-aiff','aifc' => '오디오/x-aiff', 'm3u' => '오디오/x-mpegurl','ram' => '오디오/x-pn-realaudio','rm' => '오디오/x-pn-realaudio', 'rpm' => '오디오/x-pn-realaudio-플러그인','ra' => '오디오/x-realaudio', 'wav' => '오디오/x-wav','pdb' => '화학/x-pdb','xyz' => '화학/x-xyz', 'bmp' => '이미지/bmp','gif' => '이미지/gif','ief' => '이미지/ief', 'jpeg' => '이미지/jpeg','jpg' => '이미지/jpeg','jpe' => '이미지/jpeg', 'png' => '이미지/png','tiff' => '이미지/tiff','tif' => '이미지/tiff', 'djvu' => '이미지/vnd.djvu','djv' => '이미지/vnd.djvu','wbmp' => '이미지/vnd.wap.wbmp', 'ras' => '이미지/x-cmu-raster','pnm' => '이미지/x-portable-anymap', 'pbm' => '이미지/x-portable-비트맵','pgm' => '이미지/x-portable-회색맵', 'ppm' => '이미지/x-portable-pixmap','rgb' => '이미지/x-rgb','xbm' => '이미지/x-xbitmap', 'xpm' => '이미지/x-xpixmap','xwd' => '이미지/x-xwindowdump','igs' => '모델/iges', 'iges' => '모델/iges','msh' => '모델/메쉬','mesh' => '모델/메쉬', 'silo' => '모델/메시','wrl' => '모델/vrml','vrml' => '모델/vrml', 'css' => 'text/css','html' => 'text/html','htm' => 'text/html', 'asc' => '텍스트/일반','txt' => '텍스트/일반','rtx' => '텍스트/서식 있는 텍스트', 'rtf' => '텍스트/rtf','sgml' => '텍스트/sgml','sgm' => '텍스트/sgml', 'tsv' => '텍스트/탭으로 구분된 값','wml' => 'text/vnd.wap.wml', 'wmls' => 'text/vnd.wap.wmlscript','etx' => 'text/x-setext', 'xsl' => 'text/xml','xml' => 'text/xml','mpeg' => '비디오/mpeg', 'mpg' => '비디오/mpeg','mpe' => '비디오/mpeg','qt' => '비디오/퀵타임', 'mov' => '비디오/퀵타임','mxu' => '비디오/vnd.mpegurl','avi' => '비디오/x-msvideo', 'movie' => 'video/x-sgi-movie','ice' => 'x-conference/x-cooltalk', 'rar' => '응용 프로그램/x-rar-압축','zip' => '응용 프로그램/x-zip-압축', '*'=> '응용 프로그램/옥텟-스트림','docx' => '응용 프로그램/msword' ); }/*** 사서함에 대한 IMAP 스트림 열기 * * @param 문자열 $host * @param 문자열 $port * @param 문자열 $user * @param 문자열 $pass * @param 문자열 $폴더 * @param 문자열 $ssl * @param 문자열 $pop * @return 리소스|부울*/ 공용 함수 mailConnect($host,$port,$user,$pass,$folder="INBOX",$ssl,$pop=false) { if($팝){ $ssl = $pop.'/'.$ssl.'/novalidate-cert/notls'; } $this->_connect = imap_open("{"."$host:$port/$ssl"."}$folder",$user,$pass); if(!$this->_connect) { jbxue_Application::getSession()->addError('연결할 수 없습니다: ' . imap_last_error()); 거짓을 반환; } $this->_connect를 반환합니다. } /*** 현재 사서함에 대한 정보 얻기 * * @return 객체|부울*/ 공개 함수 mailInfo(){ $this->_mailInfo = imap_mailboxmsginfo($this->_connection); if(!$this->_mailInfo) { echo "mailInfo 가져오기 실패: " . imap_last_error(); 거짓을 반환; } $this->_mailInfo를 반환합니다. } /*** 해당 메시지 헤더의 정보 개요를 읽어보세요. * * @param 문자열 $msgRange * @return 배열*/ 공용 함수 mailList($msgRange='') { if ($msgRange) { $range=$msgRange; } 또 다른 { $this->mailTotalCount(); $range = "1:".$this->_totalCount; } $overview = imap_fetch_overview($this->_connect,$range); foreach($overview를 $val로) { $mailList[$val->msgno]=(배열)$val; } $mailList를 반환합니다. } /*** 현재 메일함의 총 개수를 가져옵니다. * * @return 정수*/ 공개 함수 mailTotalCount(){ $check = imap_check($this->_connect); $this->_totalCount = $check->Nmsgs; $this->_totalCount를 반환합니다. } /*** 메시지 헤더를 읽어보세요 * * @param 문자열 $msgCount * @return 배열*/ 공개 함수 mailHeader($msgCount) { $mailHeader = 배열(); $header=imap_header($this->_connect,$msgCount); $sender=$header->from[0]; $replyTo=$header->reply_to[0]; if(strtolower($sender->mailbox)!='mailer-daemon' && strtolower($sender->mailbox)!='postmaster') { $subject = $this->subjectDecode($header->subject); $mailHeader = 배열( 'from'=>strtolower($sender->mailbox).'@'.$sender->host, 'fromName'=>$sender->개인, 'toOther'=>strtolower($replyTo->mailbox).'@'.$replyTo->호스트, 'toOtherName'=>$replyTo->개인, '주제'=>$주제, 'to'=>strtolower($header->toaddress), '날짜'=>$헤더->날짜, 'id'=>$header->Msgno, '보임'=>$헤더->보이지 않음 ); } $mailHeader를 반환합니다. } /*** 중국어 주제를 해독하다 * * @param 문자열 $주제 * @return 찌르기*/ 공개 함수 subjectDecode($subject) { $beginStr = substr($subject, 0, 5); if($beginStr == '=?ISO') { $separator = '=?ISO-2022-JP'; $toEncoding = 'ISO-2022-JP'; } 또 다른 { $separator = '=?GB2312'; $toEncoding = 'GB2312'; } $encode = strstr($subject, $separator); if ($인코드) { $explodeArr = 폭발($separator, $subject); $length = 개수($explodeArr); $subjectArr = 배열(); for($i = 0; $i 0) { if ($begin > 0) { $beginStr = substr($subSubject, 0, $begin); } if ((strlen($subSubject) - $end) > 2) { $endStr = substr($subSubject, $end 2, strlen($subSubject) - $end - 2); } $str = substr($subSubject, 0, $end - strlen($subSubject)); $pos = strrpos($str, "?"); $str = substr($str, $pos 1, strlen($str) - $pos); $subSubject = $beginStr . imap_base64($str) . $endStr; $subSubjectArr[] = iconv ( $toEncoding, 'utf-8', $subSubject ); // mb_convert_encoding($subSubject, 'utf-8' ,'gb2312,ISO-2022-JP'); } } $subject = implode('', $subSubjectArr); } $주제를 반환합니다. } /*** 현재 메일함에서 삭제할 메시지를 표시하세요. * * @param 문자열 $msgCount*/ 공개 함수 mailDelete($msgCount) { imap_delete($this->_connect,$msgCount); } /*** 메시지 첨부 받기 * * @param 문자열 $msgCount * @param 문자열 $path * @return 배열*/ 공개 함수 getAttach($msgCount,$path) { $struckture = imap_fetchstructure($this->_connect,$msgCount); $첨부 = 배열(); if($구조->부품) { foreach($struckture->parts as $key => $value) { $encoding=$구조->부분[$key]->인코딩; if($struckture->parts[$key]->ifdparameters) { $name=$struckture->부분[$key]->d매개변수[0]->값; $message = imap_fetchbody($this->_connect,$msgCount,$key 1); if ($인코딩 == 0) { $메시지 = imap_8bit($메시지); }else if ($encoding == 1){ $메시지 = imap_8bit($메시지); } else if ($encoding == 2) { $메시지 = imap_binary($메시지); } else if ($encoding == 3) { $메시지 = imap_base64($메시지); } else if ($encoding == 4) { $message = quoted_printable_decode($message); } $this->downAttach($path,$name,$message);; $attach[] = $이름; } if($struckture->부분[$key]->부분) { foreach($struckture->parts[$key]->parts as $keyb => $valueb) { $encoding=$struckture->부분[$key]->부분[$keyb]->인코딩; if($구조->부분[$key]->부분[$keyb]->ifd매개변수){ $name=$struckture->부분[$key]->부분[$keyb]->d매개변수[0]->값; $partnro = ($key 1).".".($keyb 1); $message = imap_fetchbody($this->_connect,$msgCount,$partnro); if ($인코딩 == 0) { $메시지 = imap_8bit($메시지); } else if ($encoding == 1) { $메시지 = imap_8bit($메시지); } else if ($encoding == 2) { $메시지 = imap_binary($메시지); } else if ($encoding == 3) { $메시지 = imap_base64($메시지); } else if ($encoding == 4) { $message = quoted_printable_decode($message); } $this->downAttach($path,$name,$message); $attach[] = $이름; } } } } } $attach를 반환합니다. } /*** 메일 첨부 파일을 localhost로 다운로드 * * @param 문자열 $filePath * @param 문자열 $메시지 * @param 문자열 $name*/ 공용 함수 downAttach($filePath,$name,$message) { if(is_dir($filePath)) { $fileOpen = fopen($filePath.$name,"w"); } 또 다른 { mkdir($filePath); } fwrite($fileOpen,$message); fclose($fileOpen); } /*** 첨부링크를 클릭하시면 첨부파일을 다운로드 받으실 수 있습니다 * * @param 문자열 $id*/ 공용 함수 getAttachData($id,$filePath,$fileName) { $nameArr = 폭발('.',$fileName); $length = 개수($nameArr); $contentType = $this->_contentType[$nameArr[$length-1]]; if(!$contentType) { $contentType = $this->_contentType['*']; } $filePath = 잘라($filePath); if($filePath != ''){ if(substr($filePath,strlen($filePath)-1,strlen($filePath)) != '/') { $파일경로 .= '/'; } $파일경로 .= $파일이름; } 또 다른 { $filePath = $파일이름; } if(!file_exists($filePath)){ echo '파일이 존재하지 않습니다.'; 거짓을 반환; } $fileSize = 파일 크기($filePath); header("콘텐츠 유형: ".$contentType); header("Accept-Range : 바이트 "); header("수락 길이: $fileSize"); header("콘텐츠 처리: 첨부 파일; filename=".$fileName); $fileOpen= fopen($filePath,"r"); $bufferSize = 1024; $curPos = 0; while(!feof($fileOpen)&&$fileSize-$curPos>$bufferSize) { $buffer = fread($fileOpen,$bufferSize); 에코 $버퍼; $curPos = $bufferSize; } $buffer = fread($fileOpen,$fileSize-$curPos); 에코 $버퍼; fclose($fileOpen); 사실을 반환; } /*** 메시지 본문을 가져옵니다 * * @param 문자열 $msgCount * @return 문자열*/ 공개 함수 getBody($msgCount) { $body = $this->getPart($msgCount, "TEXT/HTML"); if ($body == '') { $body = $this->getPart($msgCount, "TEXT/PLAIN"); } if ($body == '') { 반품 ''; } $body를 반환합니다. } /*** 특정 메시지의 구조를 읽고 특정 메시지를 가져옵니다. * 메시지 본문 부분 * * @param 문자열 $msgCount * @param 문자열 $mimeType * @param 객체 $구조 * @param 문자열 $partNumber * @return 문자열|부울*/ 개인 함수 getPart($msgCount, $mimeType, $structure = false, $partNumber = false) { if(!$구조) { $구조 = imap_fetch구조($this->_connect, $msgCount); } if($구조) { if($mimeType == $this->getMimeType($structure)) { if(!$partNumber) { $partNumber = "1"; } $fromEncoding = $구조->매개변수[0]->값; $text = imap_fetchbody($this->_connect, $msgCount, $partNumber); if($구조->인코딩 == 3) { $text = imap_base64($text); } else if($구조->인코딩 == 4) { $text = imap_qprint($text); } $text = mb_convert_encoding($text,'utf-8',$fromEncoding); $text를 반환합니다. } if($구조->유형 == 1) { while(list($index, $subStructure) = 각각($structure->parts)) { if($partNumber) { $prefix = $partNumber . '.'; } $data = $this->getPart($msgCount, $mimeType, $subStructure, $prefix . ($index 1)); if($데이터){ $data를 반환합니다. } } } } 거짓을 반환; } /*** 메시지 구조의 하위 유형 및 유형을 가져옵니다. * * @param 객체 $구조*/ 개인 함수 getMimeType($structure) { $mimeType = array("TEXT", "MULTIPART", "MESSAGE", "APPLICATION", "AUDIO", "IMAGE", "VIDEO", "OTHER"); if($structure->하위 유형) { $mimeType[(int) $structure->type] 을 반환합니다. '/' . $구조->하위 유형; } "텍스트/일반"을 반환합니다. } /*** 읽지 않은 메시지를 읽음으로 넣습니다. * * @param 문자열 $msgCount * @return 부울*/ 공개 함수 mailRead($msgCount) { $status = imap_setflag_full($this->_connect, $msgCount , "//본"); $상태를 반환합니다. } /*** IMAP 스트림 닫기*/ 공개 함수 closeMail() { imap_close($this->_connect,CL_EXPUNGE); } } ?> 2, 调用示例及说明 1) 获得邮件列表 $mailList = array(); $mail = new jbxue_Email(); $connect = $mail->mailConnect($this->_imapServer,$this->_port,$this->_email,$this->_password,$this->_floder,$this->_ssl); if($connect) { $totalCount = $mail->mailTotalCount(); for ($i = $totalCount; $i > 0 ; $i --) { $mailList[] = $mail->mailHeader($i); } $mail->closeMail(); } 2) 获得邮件正文 $mailId = $this->getRequest()->getParam('id'); $mailHeader = array(); $mailAttach = array(); $mailBody = ''; $mail = new jbxue_Email(); $connect = $mail->mailConnect($this->_imapServer,$this->_port,$this->_email,$this->_password,$this->_floder,$this->_ssl); if($connect) { $mailHeader = $mail->mailHeader($mailId); if($mailHeader['seen'] == 'U') { $mail->mailRead($mailId); } $mailBody = $mail->getBody($mailId); $mailAttach = $mail->getAttach($mailId,$this->_attachPath); $mail->closeMail(); } 3) 下载附件 $id = $this->getRequest()->getParam('id'); $name = $this->getRequest()->getParam('name'); $email = new jbxue_Email(); $email->getAttachData($id,$this->_attachPath,$name); |

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를 무료로 생성하십시오.

인기 기사

뜨거운 도구

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

드림위버 CS6
시각적 웹 개발 도구

DVWA
DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는
