이 글에서는 PHP에서 첨부 파일을 지원하는 이메일을 보내기 위해 smtp를 사용하는 예를 주로 소개합니다. 이 코드는 많은 실제 응용 프로그램에서 사용되었습니다.
경량 PHP 이메일 전송에는 smtp 서버 및 코드 많은 실제 사용을 거쳐 이제 모든 사람과 코드를 공유합니다
<?php /* 邮件发送smtp服务 联结smtp服务器,进行邮件发送,版权所有,不能复制 @author:jackbrown; @qq: 610269963 @time:2011-8-20; @version:1.0.3; */ class smtp{ /*邮件用户名*/ public $mailUser = MAIL_USER; /*邮件密码*/ public $mailPwd = MAIL_PWD; /*邮件服务器地址*/ public $server = MAIL_SMTP_HOST; /*邮件端口*/ public $port = MAIL_SMTP_PORT; public $timeout = MAIL_TIMEOUT; /*邮件编码*/ public $charset = MAIL_CHARSET; /*邮件发送者email,用于显示给接收者*/ public $senderMail = MAIL_SENDER; /*发用者名称*/ public $senderName = MAIL_SENDER_NAME; /*是否使用ssl安全操作*/ public $useSSL = IN_SSL; /*是否显示错误信息*/ public $showError = MAIL_SHOW_ERR; public $needLogin = MAIL_NEED_LOGIN; /*附件数组*/ public $attachMent = array(); public $failed = false; private static $smtpCon; private $stop ="\r\n"; private $status = 0; public function __construct(){ if(self::$smtpCon){ return; } if($this->mailUser==''){ $this->error('请配置好邮件登录用户名!'); return false; } if($this->mailPwd==''){ $this->error('请配置好邮件登录密码!'); return false; } if($this->server==''){ $this->error('请配置好邮服务器地址!'); return false; } if(!is_numeric($this->port)){ $this->error('请配置好邮服务器端口!'); return false; } /*ssl使用**/ $server = $this->server; if($this->useSSL == true){ $server = "ssl://".$this->server; } self::$smtpCon = @fsockopen($server, $this->port, $errno, $errstr,10);; if(!self::$smtpCon){ $this->error($errno.$errstr); return false; } socket_set_timeout(self::$smtpCon,0,250000); /*开始邮件指令*/ $this->getStatus(); $resp = true; $resp = $resp && $this->helo(); if($this->needLogin == '1'){ $resp = $resp && $this->login(); } if(!$resp){ $this->failed = true; } } /* 发送邮件 @param string $to 接收邮件地址 @param string $msg 邮件主要内容 @title string $title 邮件标题 */ public function sendMail($to,$msg,$title=''){ if($msg=='' ){ return false; } if(is_array($to)){ if($to!=null){ foreach($to as $k=>$e){ if(!preg_match('/^[a-z0-9A-Z_-]+@+([a-z0-9A-Z_-]+\.)+[a-z0-9A-Z]{2,3}$/',$e)){ unset($to[$k]); } } }else{ return false; } if($to == null){ return false; } }else{ if(!preg_match('/^[a-z0-9A-Z_-]+@+([a-z0-9A-Z_-]+\.)+[a-z0-9A-Z]{2,3}$/',$to)){ return false; } } if(!self::$smtpCon){ return false; } $this->sendSmtpMsg('MAIL FROM:<'.$this->senderMail.'>'); if(!is_array($to)){ $this->sendSmtpMsg('RCPT TO:<'.$to.'>'); }else{ foreach($to as $k=>$email){ $this->sendSmtpMsg('RCPT TO:<'.$email.'>'); } } $this->sendSmtpMsg("DATA"); if($this->status !='354'){ $this->error('请求发送邮件失败!'); $this->failed = true; return false; } $msg = base64_encode($msg); $msg = str_replace($this->stop . '.', $this->stop . '..', $msg); $msg = substr($msg, 0, 1) == '.' ? '.' . $msg : $msg; if($this->attachMent!=null){ $headers = $this->mimeHeader($msg,$to,$title); $this->sendSmtpMsg($headers,false); }else{ $headers = $this->mailHeader($to,$title); $this->sendSmtpMsg($headers,false); $this->sendSmtpMsg('',false); $this->sendSmtpMsg($msg,false); } $this->sendSmtpMsg('.');//发送结束标识符 if($this->status != '250'){ $this->failed = true; $this->error($this->readSmtpMsg()); return false; } return true; } /* 关闭邮件连接 */ public function close(){ $this->sendSmtpMsg('Quite'); @socket_close(self::$smtpCon); } /* 添加普通邮件头信息 */ protected function mailHeader($to,$title){ $headers = array(); $headers[] = 'Date: '.$this->gmtime('D j M Y H:i:s').' '.date('O'); if(!is_array($to)){ $headers[] = 'To: "'.'=?'.$this->charset.'?B?'.base64_encode($this->getMailUser($to)).'?="<'.$to.'>'; }else{ foreach($to as $k=>$e){ $headers[] = 'To: "'.'=?'.$this->charset.'?B?'.base64_encode($this->getMailUser($e)).'?="<'.$e.'>'; } } $headers[] = 'From: "=?'.$this->charset.'?B?'.base64_encode($this->senderName).'?="<'.$this->senderMail.'>'; $headers[] = 'Subject: =?'.$this->charset.'?B?'.base64_encode($title).'?='; $headers[] = 'Content-type: text/html; charset='.$this->charset.'; format=flowed'; $headers[] = 'Content-Transfer-Encoding: base64'; $headers = str_replace($this->stop . '.', $this->stop . '..', trim(implode($this->stop, $headers))); return $headers; } /* 带付件的头部信息 */ protected function mimeHeader($msg,$to,$title){ if($this->attachMent!=null){ $headers = array(); $boundary = '----='.uniqid(); $headers[] = 'Date: '.$this->gmtime('D j M Y H:i:s').' '.date('O'); if(!is_array($to)){ $headers[] = 'To: "'.'=?'.$this->charset.'?B?'.base64_encode($this->getMailUser($to)).'?="<'.$to.'>'; }else{ foreach($to as $k=>$e){ $headers[] = 'To: "'.'=?'.$this->charset.'?B?'.base64_encode($this->getMailUser($e)).'?="<'.$e.'>'; } } $headers[] = 'From: "=?'.$this->charset.'?B?'.base64_encode($this->senderName).'?="<'.$this->senderMail.'>'; $headers[] = 'Subject: =?'.$this->charset.'?B?'.base64_encode($title).'?='; $headers[] = 'Mime-Version: 1.0'; $headers[] = 'Content-Type: multipart/mixed;boundary="'.$boundary.'"'.$this->stop; $headers[]='--'.$boundary; $headers[]='Content-Type: text/html;charset="'.$this->charset.'"'; $headers[]='Content-Transfer-Encoding: base64'.$this->stop; $headers[] = ''; $headers[]= $msg.$this->stop; foreach($this->attachMent as $k=>$filename){ $f = @fopen($filename, 'r'); $mimetype = $this->getMimeType(realpath($filename)); $mimetype = $mimetype == '' ? 'application/octet-stream' : $mimetype; $attachment = @fread($f, filesize($filename)); $attachment = base64_encode($attachment); $attachment = chunk_split($attachment); $headers[] = "--" . $boundary; $headers[] = "Content-type: ".$mimetype.";name=\"=?".$this->charset."?B?". base64_encode(basename($filename)).'?="' ; $headers[] = "Content-disposition: attachment; name=\"=?".$this->charset."?B?". base64_encode(basename($filename)).'?="'; $headers[] = 'Content-Transfer-Encoding: base64'.$this->stop; $headers[] = $attachment.$this->stop; } $headers[] = "--" . $boundary . "--"; $headers = str_replace($this->stop . '.', $this->stop . '..', trim(implode($this->stop, $headers))); return $headers; } } /* 获取返回状态 */ protected function getStatus(){ $this->status = substr($this->readSmtpMsg(),0,3); } /* 获取邮件服务器返回的信息 @return string 信息字符串 */ protected function readSmtpMsg(){ if(!is_resource(self::$smtpCon)){ return false; } $return = ''; $line = ''; while (strpos($return, $this->stop)=== false OR $line{3}!== ' ') { $line = fgets(self::$smtpCon, 512); $return .= $line; } return trim($return); } /* 给邮件服务器发给指定命令消息 */ protected function sendSmtpMsg($cmd,$chStatus=true){ if (is_resource(self::$smtpCon)) { fwrite(self::$smtpCon, $cmd . $this->stop, strlen($cmd) + 2); } if($chStatus == true){ $this->getStatus(); } return true; } /* 邮件时间格式 */ protected function gmtime(){ return (time() - date('Z')); } /* 获取付件的mime类型 */ protected function getMimeType($file){ $mimes = array( 'chm'=>'application/octet-stream', 'ppt'=>'application/vnd.ms-powerpoint', 'xls'=>'application/vnd.ms-excel', 'doc'=>'application/msword', 'exe'=>'application/octet-stream', 'rar'=>'application/octet-stream', 'js'=>"javascrīpt/js", 'css'=>"text/css", 'hqx'=>"application/mac-binhex40", 'bin'=>"application/octet-stream", 'oda'=>"application/oda", 'pdf'=>"application/pdf", 'ai'=>"application/postsrcipt", 'eps'=>"application/postsrcipt", 'es'=>"application/postsrcipt", 'rtf'=>"application/rtf", 'mif'=>"application/x-mif", 'csh'=>"application/x-csh", 'dvi'=>"application/x-dvi", 'hdf'=>"application/x-hdf", 'nc'=>"application/x-netcdf", 'cdf'=>"application/x-netcdf", 'latex'=>"application/x-latex", 'ts'=>"application/x-troll-ts", 'src'=>"application/x-wais-source", 'zip'=>"application/zip", 'bcpio'=>"application/x-bcpio", 'cpio'=>"application/x-cpio", 'gtar'=>"application/x-gtar", 'shar'=>"application/x-shar", 'sv4cpio'=>"application/x-sv4cpio", 'sv4crc'=>"application/x-sv4crc", 'tar'=>"application/x-tar",'ustar'=>"application/x-ustar",'man'=>"application/x-troff-man", 'sh'=>"application/x-sh", 'tcl'=>"application/x-tcl", 'tex'=>"application/x-tex", 'texi'=>"application/x-texinfo",'texinfo'=>"application/x-texinfo", 't'=>"application/x-troff", 'tr'=>"application/x-troff", 'roff'=>"application/x-troff", 'shar'=>"application/x-shar", 'me'=>"application/x-troll-me", 'ts'=>"application/x-troll-ts", 'gif'=>"image/gif", 'jpeg'=>"image/pjpeg", 'jpg'=>"image/pjpeg", 'jpe'=>"image/pjpeg", 'ras'=>"image/x-cmu-raster", 'pbm'=>"image/x-portable-bitmap", 'ppm'=>"image/x-portable-pixmap", 'xbm'=>"image/x-xbitmap", 'xwd'=>"image/x-xwindowdump", 'ief'=>"image/ief", 'tif'=>"image/tiff", 'tiff'=>"image/tiff", 'pnm'=>"image/x-portable-anymap", 'pgm'=>"image/x-portable-graymap", 'rgb'=>"image/x-rgb", 'xpm'=>"image/x-xpixmap", 'txt'=>"text/plain", 'c'=>"text/plain", 'cc'=>"text/plain", 'h'=>"text/plain", 'html'=>"text/html", 'htm'=>"text/html", 'htl'=>"text/html", 'rtx'=>"text/richtext", 'etx'=>"text/x-setext", 'tsv'=>"text/tab-separated-values", 'mpeg'=>"video/mpeg", 'mpg'=>"video/mpeg", 'mpe'=>"video/mpeg", 'avi'=>"video/x-msvideo", 'qt'=>"video/quicktime", 'mov'=>"video/quicktime", 'moov'=>"video/quicktime", 'movie'=>"video/x-sgi-movie", 'au'=>"audio/basic", 'snd'=>"audio/basic", 'wav'=>"audio/x-wav", 'aif'=>"audio/x-aiff", 'aiff'=>"audio/x-aiff", 'aifc'=>"audio/x-aiff", 'swf'=>"application/x-shockwave-flash", 'myz'=>"application/myz" ); $ext = substr(strrchr($file,'.'),1); $type = $mimes[$ext]; unset($mimes); return $type; } /* 邮件helo命令 */ private function helo(){ if($this->status != '220'){ $this->error('连接服务器失败!'); return false; } return $this->sendSmtpMsg('HELO '.$this->server); } /* 登录 */ private function login(){ if($this->status!='250'){ $this->error('helo邮件指令失败!'); return false; } $this->sendSmtpMsg('AUTH LOGIN'); if($this->status!='334'){ $this->error('AUTH LOGIN 邮件指令失败!'); return false; } $this->sendSmtpMsg(base64_encode($this->mailUser)); if($this->status!='334'){ $this->error('邮件登录用户名可能不正确!'.$this->readSmtpMsg()); return false; } $this->sendSmtpMsg(base64_encode($this->mailPwd)); if($this->status !='235'){ $this->error('邮件登录密码可能不正确!'); return false; } return true; } private function getMailUser($to){ $temp = explode('@',$to); return $temp[0]; } /* 异常报告 */ private function error($exception){ if($this->showError == false){ file_put_contents('mail_log.txt',$exception,FILE_APPEND); return; } if(class_exists('error') && is_object($GLOBALS['error'])){ $GLOBALS['error']->showErrorStr($exception,'javascript:',false); }else{ throw new Exception($exception); } } } // 使用示例 ini_set('memory_limit','128M'); set_time_limit(120); define('MAIL_SENDER_NAME','楚贤'); define('MAIL_SMTP_HOST','smtp.ym.163.com'); define('MAIL_USER','admin@myxxxx.com'); define('MAIL_SENDER','admin@myxxxx.com'); define('MAIL_PWD','xxxx'); define('MAIL_SMTP_PORT',25); define('IN_SSL',false); define('MAIL_TIMEOUT',10); define('MAIL_CHARSET','utf-8'); date_default_timezone_set('PRC'); $m = new smtp(); $msg = "有用户登录服务器@".date('Y-m-d H:i:s'); 付件 //$m->attachMent = array('hehe.php','common.php'); if($m->sendMail(array('610269963@qq.com'),$msg,'88服务器登录提示')){ echo '发送成功!'; } $m->close(); ?>
위 내용은 모든 사람의 학습에 도움이 되기를 바랍니다. 중국사이트!
관련 권장 사항:
laravel sms를 사용하여 확인을 위한 SMS 확인 코드 전송 기능 구축
PHP의 치명적인 오류 session_start() 오류를 해결하는 방법
PHP의 autoLoad 자동 로딩 정보 메커니즘 분석
위 내용은 PHP에서 smtp를 사용하여 첨부 파일을 지원하는 이메일을 보내는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

여전히 인기있는 것은 사용 편의성, 유연성 및 강력한 생태계입니다. 1) 사용 편의성과 간단한 구문은 초보자에게 첫 번째 선택입니다. 2) 웹 개발, HTTP 요청 및 데이터베이스와의 우수한 상호 작용과 밀접하게 통합되었습니다. 3) 거대한 생태계는 풍부한 도구와 라이브러리를 제공합니다. 4) 활성 커뮤니티와 오픈 소스 자연은 새로운 요구와 기술 동향에 맞게 조정됩니다.

PHP와 Python은 웹 개발, 데이터 처리 및 자동화 작업에 널리 사용되는 고급 프로그래밍 언어입니다. 1.PHP는 종종 동적 웹 사이트 및 컨텐츠 관리 시스템을 구축하는 데 사용되며 Python은 종종 웹 프레임 워크 및 데이터 과학을 구축하는 데 사용됩니다. 2.PHP는 Echo를 사용하여 콘텐츠를 출력하고 Python은 인쇄를 사용합니다. 3. 객체 지향 프로그래밍을 지원하지만 구문과 키워드는 다릅니다. 4. PHP는 약한 유형 변환을 지원하는 반면, 파이썬은 더 엄격합니다. 5. PHP 성능 최적화에는 Opcache 및 비동기 프로그래밍 사용이 포함되며 Python은 Cprofile 및 비동기 프로그래밍을 사용합니다.

PHP는 주로 절차 적 프로그래밍이지만 객체 지향 프로그래밍 (OOP)도 지원합니다. Python은 OOP, 기능 및 절차 프로그래밍을 포함한 다양한 패러다임을 지원합니다. PHP는 웹 개발에 적합하며 Python은 데이터 분석 및 기계 학습과 같은 다양한 응용 프로그램에 적합합니다.

PHP는 1994 년에 시작되었으며 Rasmuslerdorf에 의해 개발되었습니다. 원래 웹 사이트 방문자를 추적하는 데 사용되었으며 점차 서버 측 스크립팅 언어로 진화했으며 웹 개발에 널리 사용되었습니다. Python은 1980 년대 후반 Guidovan Rossum에 의해 개발되었으며 1991 년에 처음 출시되었습니다. 코드 가독성과 단순성을 강조하며 과학 컴퓨팅, 데이터 분석 및 기타 분야에 적합합니다.

PHP는 웹 개발 및 빠른 프로토 타이핑에 적합하며 Python은 데이터 과학 및 기계 학습에 적합합니다. 1.PHP는 간단한 구문과 함께 동적 웹 개발에 사용되며 빠른 개발에 적합합니다. 2. Python은 간결한 구문을 가지고 있으며 여러 분야에 적합하며 강력한 라이브러리 생태계가 있습니다.

PHP는 현대화 프로세스에서 많은 웹 사이트 및 응용 프로그램을 지원하고 프레임 워크를 통해 개발 요구에 적응하기 때문에 여전히 중요합니다. 1.PHP7은 성능을 향상시키고 새로운 기능을 소개합니다. 2. Laravel, Symfony 및 Codeigniter와 같은 현대 프레임 워크는 개발을 단순화하고 코드 품질을 향상시킵니다. 3. 성능 최적화 및 모범 사례는 응용 프로그램 효율성을 더욱 향상시킵니다.

phphassignificallyimpactedwebdevelopmentandextendsbeyondit

PHP 유형은 코드 품질과 가독성을 향상시키기위한 프롬프트입니다. 1) 스칼라 유형 팁 : PHP7.0이므로 int, float 등과 같은 기능 매개 변수에 기본 데이터 유형을 지정할 수 있습니다. 2) 반환 유형 프롬프트 : 기능 반환 값 유형의 일관성을 확인하십시오. 3) Union 유형 프롬프트 : PHP8.0이므로 기능 매개 변수 또는 반환 값에 여러 유형을 지정할 수 있습니다. 4) Nullable 유형 프롬프트 : NULL 값을 포함하고 널 값을 반환 할 수있는 기능을 포함 할 수 있습니다.


핫 AI 도구

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

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

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

Clothoff.io
AI 옷 제거제

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

인기 기사

뜨거운 도구

Dreamweaver Mac版
시각적 웹 개발 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

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

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

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