用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 $server='';
var $username='';
var $password=''; var $marubox=''; var $email=''; function receiveMail($username,$password,$EmailAddress,$mailserver='localhost',$servertype='pop',$port='110',$ssl = false) //Constructure
{
if($servertype=='imap')
{
if($port=='') $port='143';
$strConnect='{'.$mailserver.':'.$port. '}INBOX';
}
else
{
$strConnect='{'.$mailserver.':'.$port. '/pop3'.($ssl ? "/ssl" : "").'}INBOX';
}
$this->server = $strConnect;
$this->username = $username;
$this->password = $password;
$this->email = $EmailAddress;
}
function connect() //Connect To the Mail Box
{
$this->marubox=@imap_open($this->server,$this->username,$this->password); if(!$this->marubox)
{
return false;
// echo "Error: Connecting to mail server";
// exit;
}
return true;
} function getHeaders($mid) // Get Header info
{
if(!$this->marubox)
return false; $mail_header=imap_header($this->marubox,$mid);
$sender=$mail_header->from[0];
$sender_replyto=$mail_header->reply_to[0];
if(strtolower($sender->mailbox)!='mailer-daemon' && strtolower($sender->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($sender->mailbox).'@'.$sender->host,
'fromName'=>$this->decode_mime($sender->personal),
'ccList'=>$ccList,//strtolower($sender_replyto->mailbox).'@'.$sender_replyto->host,
'toNameOth'=>$this->decode_mime($sender_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 Use
{
$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 = false, $part_number = false) //Get Part Of Message Internal Private Use
{ 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_base64($text);
// if ($structure->parameters[0]->value!="utf-8")
// {
// return imap_base64($text);
// }
// else
// {
// return imap_base64($text);
// }
}
else if($structure->encoding == 4)
{
return iconv('gb2312','utf8',imap_qprint($text));
}
else
{
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 false;
}
function getTotalMails() //Get Total Number off Unread Email In Mailbox
{
if(!$this->marubox)
return false; // return imap_headers($this->marubox);
return imap_num_recent($this->marubox);
} function GetAttach($mid,$path) // Get Atteced File from Mail
{
if(!$this->marubox)
return false; $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[count($extend)-1];
$file['pathname'] = $this->setPathName($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;
}
else
{
$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_base64 ($message);
if ($enc == 4)
$message = quoted_printable_decode($message);
if ($enc == 5)
$message = $message;
$fp=fopen($path.$file['pathname'],"w");
fwrite($fp,$message);
fclose($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]->ifdparameters)
{
//命名图片
$name=$this->decode_mime($struckture->parts[$key]->parts[$keyb]->dparameters[0]->value);
$extend =explode("." , $name);
$file['extension'] = $extend[count($extend)-1];
$file['pathname'] = $this->setPathName($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_base64 ($message);
if ($enc == 4)
$message = quoted_printable_decode($message);
if ($enc == 5)
$message = $message;
$fp=fopen($path.$file['pathname'],"w");
fwrite($fp,$message);
fclose($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 false; $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 (!isset($matches[0])) return; foreach ($matches[0] as $img)
{
// replace image web path with local path
preg_match('/src="(.*? )"/', $img, $m);
if (!isset($m[1])) continue;
$arr = parse_url($m[1]);
if (!isset($arr['scheme']) || !isset($arr['path']))continue; // if (!isset($arr['host']) || !isset($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 false; imap_delete($this->marubox,$mid);
}
function close_mailbox() //Close Mail Box
{
if(!$this->marubox)
return false; imap_close($this->marubox,CL_EXPUNGE);
} //移动邮件到指定分组
function move_mails($msglist,$mailbox)
{
if(!$this->marubox)
return false; imap_mail_move($this->marubox, $msglist, $mailbox);
} function creat_mailbox($mailbox)
{
if(!$this->marubox)
return false; //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]->charset!="default")
{echo "==".$str[0]->text;
return iconv($str[0]->charset,'utf8',$str[0]->text);
}
else
{
return $str[0]->text;
}
} /**
* Set path name of the uploaded file to be saved.
*
* @param int $fileID
* @param string $extension
* @access public
* @return string
*/
public function setPathName($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;charset=UTF-8');
error_reporting(0);
ignore_user_abort(); // run script in background
set_time_limit(0); // run script forever
date_default_timezone_set('Asia/Shanghai');
include("receivemail.class.php");
class mailControl
{
//定义系统常量
//username
public $mailAccount = "123456@qq.com";
public $mailPasswd = "12345";
public $mailAddress = "123456@qq.com";
public $mailServer = "pop.qq.com";
public $serverType = "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->setSavePath();
} /**
* 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->mailServer,$this->serverType,$this->port,false); //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 server");
}
// Get Total Number of Unread Email in mail box
$tot=$obj->getTotalMails(); //Total Mails in Inbox Return integer value
if($tot < 1) { //假设信件数为0,显示信息
return array("msg"=>"No Message for ".$this->mailAccount);
}
else
{
$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->close_mailbox(); //Close 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->mailServer,$this->serverType,$this->port,false);
$obj->creat_mailbox($boxName);
} /**
* Set save path.
*
* @access public
* @return void
*/
public function setSavePath()
{
$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 就可以

PHP收邮件receiveMail的更多相关文章

  1. Gmail邮件功能那么强大,GMail被封,在国内怎么用gmail收邮件?

    IT圈子里最热门的话题一定是:gmail被封,该怎么办?gmail由于强大的邮件功能,ITer一定是人手一个or多个,之前想要收发gmail使用imap或SMTP方式是可以在国内正常使用的,目前ima ...

  2. POP3是收邮件的协议,SMTP是发邮件的协议,IMAP是一种邮箱通信协议。

    我也是第一次接触这种服务,是因为我自己在做一个小小的自动推送天气情况到自己邮箱.所以才碰到这个的/ 看一下标题,我们可以先这样理解. POP3(Post Office Protocol - Versi ...

  3. 配置使用dwr完成收邮件提示

    DWR(Direct Web Remoting)是一个用于改善web页面与Java类交互的远程服务器端Ajax开源框架,可以帮助开发人员开发包含AJAX技术的网站.它可以允许在浏览器里的代码使用运行在 ...

  4. centos 邮件服务 腾讯企业邮箱(免费) 使用iRedmail 需要有公网的centos主机 发邮件协议:smtp 端口25 收邮件协议:pop3 端口110 iredmail安装配置 使用邮箱系统 第三十一节课

    centos   邮件服务  腾讯企业邮箱(免费) 使用iRedmail 需要有公网的centos主机 发邮件协议:smtp 端口25  收邮件协议:pop3 端口110  iredmail安装配置 ...

  5. FOXMAIL提示容量满无法收邮件,清除旧邮件后还是无法收取,请问如何解决?

    FOXMAIL提示容量满无法收邮件,清除旧邮件后还是无法收取,请问如何解决? 2009-03-23 11:21包子燕  分类:网站使用 我清除了FOXMAIL所在的磁盘空间,共有12G,也删除了部分旧 ...

  6. sonarqube 8.9版本配置收邮件提醒

    # admin登陆系统后,进入我的账户(每个用户的配置过程类似) sonarqube 8.9版本配置发信请参考我的另一篇博文: 链接如下: https://www.cnblogs.com/cndevo ...

  7. javamail 收邮件并解析附件

    package com.zz.mail; import java.io.*; import java.text.*; import java.util.*; import javax.mail.*; ...

  8. JavaMail接、收邮件

    我总算把这个研究出来啦.... 不要觉得 代码有点多哈. 我们先来说发送邮箱吧,首先建立一个属性文件*.properties sys.properties server=smtp.163.com ## ...

  9. MVC4/5+jquery+bootstrap样式+dataTables+linq+WCF+EF6后台和前台的框架集合!好蛋疼哦!数据库支持MYSQL 和MSSQL,oracle。集成腾讯企业邮箱收邮件同步用户SSO登陆等功能。

    花费了我好多心血,才做出来,下个项目准备用这个框架! 大家有没有做这方面的可以交流一下! 花费了我好多心血,才做出来,下个项目准备用这个框架! 大家有没有做这方面的可以交流一下! 花费了我好多心血,才 ...

随机推荐

  1. FOJ Problem 2256 迷宫

                                                                                                        ...

  2. 如何使用 OpenStack CLI

    本节首先讨论 image 删除操作,然后介绍 OpenStack CLI 的使用方法,最后讨如何 Troubleshoot. Web UI 删除 image admin 登录后,Project -&g ...

  3. POJ 2411Mondriaan's Dream

    题目: Squares and rectangles fascinated the famous Dutch painter Piet Mondriaan. One night, after prod ...

  4. Linux 设备驱动的固件加载【转】

    转自:http://blog.csdn.net/zqixiao_09/article/details/51106663 版权声明:本文为博主原创文章,未经博主允许不得转载. 作为一个驱动作者, 你可能 ...

  5. /sys/class/gpio 文件接口操作IO端口(s3c2440)

    http://blog.csdn.net/mirkerson/article/details/8464231 在嵌入式设备中对GPIO的操作是最基本的操作.一般的做法是写一个单独驱动程序,网上大多数的 ...

  6. 更新YUM源后的arning: rpmts_HdrFromFdno: Header V3 RSA/SHA1 Signature, key ID c105b9de: NOKEY错误

    yum源更新后需要导入key值,否则报错如下,无法安装相关的包. Totalsize:42M DownloadingPackages: warning:rpmts_HdrFromFdno:Header ...

  7. react-1 react需要的环境配置

    一.nodeJs简介和安装 1. 官网 https://nodejs.org/en/         NPM https://www.npmjs.com/ 2.检查安装成功的命令 node -v np ...

  8. 咦?Oracle归档文件存哪了?

    实验环境:RHEL 5.4 + Oracle 11.2.0.3 现象:日志切换后没找到归档日志目录. 1.查看归档日志路径 2.日志切换后并未找到归档目录 3.创建归档目录后再次观察 引申知识 1.查 ...

  9. Linux Root下的.gvfs出现异常解决办法(导致source失败,自启动失败)

    原文地址:   http://www.cnblogs.com/tdyizhen1314/p/4142991.html 在linux系统下安装软件或复制文件的时候,复制不成功,出现错误如下: error ...

  10. Codeforces Round #321 (Div. 2) Kefa and Dishes 状压+spfa

    原题链接:http://codeforces.com/contest/580/problem/D 题意: 给你一些一个有向图,求不超过m步的情况下,能获得的最大权值和是多少,点不能重复走. 题解: 令 ...