首页 > 作文

PHP receiveMail实现收邮件功能

更新时间:2023-04-06 17:47:30 阅读: 评论:0

用php来发邮件,相信大家都不陌生,但读取收件箱的话,接触就少了,这次总结下自己的经验,希望可以帮助大家.

注意:

1.php读取收件箱主要是利用imap扩展,所以在使用以下方法前,必须开启imap扩展模块的支持.

2.此方法支持中文,不会乱码,需要保持所有文件的编码的一致性

1.文件结构

2.邮件类 ./mailreceived/receivemail.class.php

./mailreceived/receivemail.class.php 文件内容如下:

<?php // main recivemail class file - version 1.0 (03-06-2015) /* * file: recivemail.class.php * description: reciving mail with attechment * version: 1.1 * created: 03-06-2015 * author: sara zhou */ class receivemail { var $rver=''; var $urname=''; var $password=''; var $marubox='';           var $email='';    function receivemail($urname,$password,$emailaddress,$mailrver='localhost',$rvertype='pop',$port='110',$ssl = fal) //constructure { if($rvertype=='imap') { if($port=='') $port='143';  $strconnect='{'.$mailrver.':'.$port. '}inbox';  } el { $strconnect='{'.$mailrver.':'.$port. '/pop3'.($ssl ? "/ssl" : "").'}inbox';  } $this->rver      =  $strconnect; $this->urname     =  $urname; $this->password     =  $password; $this->email     =  $emailaddress; } function connect() //connect to the mail box { $this->marubox=@imap_open($this->rver,$this->urname,$this->password); if(!$this->marubox) { return fal; //     echo "error: connecting to mail rver"; //     exit; } return true; } function getheaders($mid) // get header info { if(!$this->marubox) return fal; $mail_header=imap_header($this->marubox,$mid); $nder=$mail_header->from[0]; $nder_replyto=$mail_header->reply_to[0]; if(strtolower($nder->mailbox)!='mailer-daemon' && strtolower($nder->mailbox)!='postmaster') { $subject=$this->decode_mime($mail_header->subject); $cclist=array(); foreach ($mail_header->cc as $k => $v) { $cclist[]=$v->mailbox.'@'.$v->host; } $tolist=array(); foreach ($mail_header->to as $k => $v) { $tolist[]=$v->mailbox.'@'.$v->host; } $cclist=implode(",", $cclist); $tolist=implode(",", $tolist); $mail_details=array( 'fromby'=>strtolower($nder->mailbox).'@'.$nder->host, 'fromname'=>$this->decode_mime($nder->personal), 'cclist'=>$cclist,//strtolower($nder_replyto->mailbox).'@'.$nder_replyto->host, 'tonameoth'=>$this->decode_mime($nder_replyto->personal), 'subject'=>$subject, 'maildate'=>date("y-m-d h:i:s",$mail_header->udate), 'udate'=>$mail_header->udate, 'tolist'=>$tolist//strtolower($mail_header->to[0]->mailbox).'@'.$mail_header->to[0]->host //         'to'=>strtolower($mail_header->toaddress) ); } return $mail_details; } function get_mime_type(&$structure) //get mime type internal private u {  $primary_mime_type = array("text", "multipart", "message", "application", "audio", "image", "video", "other");  if($structure->subtype && $structure->subtype!="png") {  return $primary_mime_type[(int) $structure->type] . '/' . $structure->subtype;  }  return "text/plain";  }  function get_part($stream, $msg_number, $mime_type, $structure = fal, $part_number = fal) //get part of message internal private u {  if(!$structure) {  $structure = imap_fetchstructure($stream, $msg_number);  }  if($structure) {  if($mime_type == $this->get_mime_type($structure)) {  if(!$part_number)  {  $part_number = "1";  }  $text = imap_fetchbody($stream, $msg_number, $part_number); if($structure->encoding == 3) { return imap_ba64($text); //         if ($structure->parameters[0]->value!="utf-8") //         { //           return imap_ba64($text); //         } //         el //         { //           return imap_ba64($text); //         } } el if($structure->encoding == 4) { return iconv('gb2312','utf8',imap_qprint($text)); } el { return iconv('gb2312','utf8',$text); } }  if($structure->type == 1) /* multipart */  {  while(list($index, $sub_structure) = each($structure->parts)) {  if($part_number) {  $prefix = $part_number . '.';  }  $data = $this->get_part($stream, $msg_number, $mime_type, $sub_structure, $prefix . ($index + 1));  if($data) {  return $data;  }  }  }  } return fal;  }  function gettotalmails() //get total number off unread email in mailbox { if(!$this->marubox) return fal; //   return imap_headers($this->marubox); return imap_num_recent($this->marubox); } function getattach($mid,$path) // get atteced file from mail { if(!$this->marubox) return fal; $struckture = imap_fetchstructure($this->marubox,$mid); $files=array(); if($struckture->parts) { foreach($struckture->parts as $key => $value) { $enc=$struckture->parts[$key]->encoding; //取邮件附件 if($struckture->parts[$key]->ifdparameters) { //命名附件,转码 $name=$this->decode_mime($struckture->parts[$key]->dparameters[0]->value);          $extend =explode("." , $name); $file['extension'] = $extend[cou居里夫人传读后感nt($extend)-1]; $file['pathname'] = $this->tpathname($key, $file['extension']); $file['title']   = !empty($name) ? htmlspecialchars($name) : str_replace('.' . $file['extension'], '', $name); $file['size']   = $struckture->parts[$key]->dparameters[1]->value; //         $file['tmpname']  = $struckture->parts[$key]->dparameters[0]->value; if(@$struckture->parts[$key]->disposition=="attachment") { $file['type']   = 1;    } el { $file['type']   = 0; }       $files[] = $file;           $message = imap_fetchbody($this->marubox,$mid,$key+1); if ($enc == 0) $message = imap_8bit($message); if ($enc == 1) $message = imap_8bit ($message); if ($enc == 2) $message = imap_binary ($message); if ($enc == 3)//图片 $message = imap_ba64 ($message);  if ($enc == 4) $message = quoted_printable_decode($message); if ($enc == 5) $message = $message; $fp=fopen($path.$file['pathname'],"w"); fwrite($fp,$message); fclo($fp); } // 处理内容中包含图片的部分 if($struckture->parts[$key]->parts) { foreach($struckture->parts[$key]->parts as $keyb => $valueb) { $enc=$struckture->parts[$key]->parts[$keyb]->encoding; if($struckture->parts[$key]->parts[$keyb]->if中国感动dparameters) { //命名图片 $name=$this->decode_mime($struckture->parts[$key]->parts[$keyb]->dparameters[0]->value); $ex雨天歌词tend =explode("." , $name); $file['extension'] = $extend[count($extend)-1]; $file['pathname'] = $this->tpathname($key, $file['extension']); $file['title']   = !empty($name) ? htmlspecialchars($name) : str_replace('.' . $file['extension'], '', $name); $file['size']   = $struckture->parts[$key]->parts[$keyb]->dparameters[1]->value; //             $file['tmpname']  = $struckture->parts[$key]->dparameters[0]->value; $file['type']   = 0; $files[] = $file; $partnro = ($key+1).".".($keyb+1); $message = imap_fetchbody($this->marubox,$mid,$partnro); if ($enc == 0) $message = imap_8bit($message); if ($enc == 1) $message = imap_8bit ($message); if ($enc == 2) $message = imap_binary ($message); if ($enc == 3) $message = imap_ba64 ($message); if ($enc == 4) $message = quoted_printable_decode($message); if ($enc == 5) $message = $message; $fp=fopen($path.$file['pathname'],"w"); fwrite($fp,$message); fclo($fp); } } }         } } //move mail to taskmailbox $this->move_mails($mid, $this->marubox);    return $files; } function getbody($mid,&$path,$imagelist) // get message body { if(!$this->marubox) return fal; $body = $this->get_part($this->marubox, $mid, "text/html"); if ($body == "") $body = $this->get_part($this->marubox, $mid, "text/plain"); if ($body == "") {  return ""; } //处理图片 $body=$this->embed_images($body,$path,$imagelist); return $body; } function embed_images(&$body,&$path,$imagelist) { // get all img tags preg_match_all('/<img.*?>/', $body, $matches); if (!ist($matches[0])) return; foreach ($matches[0] as $img) { // replace image web path with local path preg_match('/src="(.*?)"/', $img, $m); if (!ist($m[1])) continue; $arr = par_url($m[1]); if (!ist($arr['scheme']) || !ist($arr['path']))continue; //     if (!ist($arr['host']) || !ist($arr['path']))continue; if ($arr['scheme']!="http") { $filename=explode("@", $arr['path']); $body = str_replace($img, '<img alt="" src="'.$path.$imagelist[$filename[0]].'" style="border: none;" />', $body); } } return $body; } function deletemails($mid) // delete that mail { if(!$this->marubox) return fal; imap_delete($this->marubox,$mid); } function clo_mailbox() //clo mail box { if(!$this->marubox) return fal; imap_clo($this->marubox,cl_expunge); } //移动邮件到指定分组 function move_mails($msglist,$mailbox) { if(!$this->marubox) return fal; imap_mail_move($this->marubox, $msglist, $mailbox); } function creat_mailbox($mailbox) { if(!$this->marubox) return fal; //imap_renamemailbox($imap_stream, $old_mbox, $new_mbox); imap_create($this->marubox, $mailbox); } /* * decode_mime()转换邮件标题的字符编码,处理乱码 */ function decode_mime($str){ $str=imap_mime_header_decode($str); return $str[0]->text; echo "str";print_r($str); if ($str[0]->chart!="default") {echo "==".$str[0]->text; return iconv($str[0]->chart,'utf8',$str[0]->text); } el { return $str[0]->text; } } /** * t path name of the uploaded file to be saved. * * @param int  $fileid * @param string $extension * @access public * @return string */ public function tpathname($fileid, $extension) { return date('ym/dhis', time()) . $fileid . mt_rand(0, 10000) . '.' . $extension; } } ?> 

3.控制层./mailreceived/mailcontrol.php

./mailreceived/mailcontrol.php 内容如下:

<? /* * file: mailcontrol.php * description: received mail example * created: 03-06-2015 * author: sara zhou */ @header('content-type: text/html;chart=utf-8'); error_reporting(0); ignore_ur_abort(); // run script in background t_time_limit(0); // run script forever date_default_timezone_t('asia/shanghai'); include("receivemail.class.php"); class mailcontrol { //定义系统常量 //用户名 public $mailaccount = "123456@qq.com"; public $mailpasswd = "12345"; public $mailaddress = "123456@qq.com"; public $mailrver = "pop.qq.com"; pub在家做什么挣钱lic $rvertype = "pop3"; public $port = "110"; public $now    = 0; public $savepath = ''; public $webpath  = "../upload/"; public function __construct() { $this->now = date("y-m-d h:i:s",time()); $this->tsavepath(); } /** * mail received()读取收件箱邮件 * * @param * @access public * @return result */ public function mailreceived() { // creating a object of recivemail class $obj= new receivemail($this->mailaccount,$this->mailpasswd,$this->mailaddress,$this->mailrver,$this->rvertype,$this->port,fal); //connect to the mail box $res=$obj->connect();     //if connection fails give error message and exit if (!$res) { return array("msg"=>"error: connecting to mail rver"); } // get total number of unread email in mail box $tot=$obj->gettotalmails(); //total想双飞xx mails in inbox return integer value if($tot < 1) { //如果信件数为0,显示信息 return array("msg"=>"no message for ".$this->mailaccount); } el { $res=array("msg"=>"total mails:: $tot<br>"); for($i=$tot;$i>0;$i--) { $head=$obj->getheaders($i); // get header info return array of headers **array keys are (subject,to,tooth,tonameoth,from,fromname) //处理邮件附件 $files=$obj->getattach($i,$this->savepath); // 获取邮件附件,返回的邮件附件信息数组 $imagelist=array(); foreach($files as $k => $file) {       //type=1为附件,0为邮件内容图片 if($file['type'] == 0) { $imagelist[$file['title']]=$file['pathname']; } } $body = $obj->getbody($i,$this->webpath,$imagelist); $res['mail'][]=array('head'=>$head,'body'=>$body,"attachlist"=>$files);        //       $obj->deletemails($i); // delete mail from mail box //       $obj->move_mails($i,"taskmail"); } $obj->clo_mailbox();  //clo mail box return $res; } } /** * creatbox * * @access public * @return void */ public function creatbox($boxname) { // creating a object of recivemail class $obj= new receivemail($this->mailaccount,$this->mailpasswd,$this->mailaddress,$this->mailrver,$this->rvertype,$this->port,fal); $obj->creat_mailbox($boxname); } /** * t save path. * * @access public * @return void */ public function tsavepath() { $savepath = "../upload/" . date('ym/', $this->now); if(!file_exists($savepath)) { @mkdir($savepath, 0777, true); touch($savepath . 'index.html'); } $this->savepath = dirname($savepath) . '/'; } } $obj=new mailcontrol(); //收取邮件 $res=$obj->mailreceived(); echo "<pre>";print_r($res); //创建邮箱 // $obj->creatbox("readybox"); ?> 

4.访问地址:http://localhost/test.cn/mailreceived/mailcontrol.php 即可

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持www.887551.com。

本文发布于:2023-04-06 17:47:24,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/zuowen/4e9214798cb81126f2b11f734ac8a96d.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

本文word下载地址:PHP receiveMail实现收邮件功能.doc

本文 PDF 下载地址:PHP receiveMail实现收邮件功能.pdf

标签:收件箱   邮件   图片   邮件附件
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图