POP3获取文件的内容
浏览量:740
首先先封装一个类文件用于获取文件类型
<?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 $debug = false;
var $email='';
private $server2 = "";
public $DC;
/**
* 参数初始化
* @param $username 用户名
* @param $password 用户密码
* @param $EmailAddress
* @param string $mailserver 邮件服务器
* @param string $servertype 邮件协议
* @param string $port 端口
* @param bool|false $ssl
* author : lianghuiju
* function_name : receiveMail
* description :
*/
function receiveMail($username,$password,$EmailAddress,$mailserver='localhost',$servertype='pop',$port='110',$ssl = false){
global $debug;
if ($servertype == 'imap') {
if ($port == '') $port = '143';
$strConnect = '{' . $mailserver . ':' . $port . '}';
}else{
$strConnect = '{' . $mailserver . ':' . $port . '/pop3' . ($ssl ? "/ssl" : "") . '}';
$strConnect_2 = '{' . $mailserver . ':' . $port . '/pop3/notls' . ($ssl ? "/ssl" : "") . '}';
$this->server2 = $strConnect_2;
}
$this->server = $strConnect;
$this->username = $username;
$this->password = $password;
$this->email = $EmailAddress;
$this->DC = new datacenter();
$this->debug = $debug ? $debug : false;
}
/**
* 连接邮件服务器
* @return bool
* author : lianghuiju
* function_name : connect
* description :
*/
function connect() {
$this->marubox = @imap_open($this->server."INBOX", $this->username, $this->password);
if (!$this->marubox) {
$this->server = $this->server2;
$this->marubox = @imap_open($this->server."INBOX", $this->username, $this->password);
}
if (!$this->marubox) {
return false;
// echo "Error: Connecting to mail server";
// exit;
}
return true;
}
/**
* 获取邮件头信息,返回数组
* @param $mid
* @return array|bool
* author : lianghuiju
* function_name : getHeaders
* description :
* return array(
* subject,//主题
* ccList,//抄送给
* fromBy,//发信人邮箱
* fromName,//发信人名字
* toNameOth,//收信人名字
* mailDate,//发信日期(格式化)
* udate,//发信时间戳
* toList,//收信人
* )
*/
function getHeaders($mid) {
if(!$this->marubox){
return false;
}
$mail_header=imap_header($this->marubox,$mid);
$message_id = $mail_header->message_id;
$cache_message = $this->DC->get_cache_4("shensuMail$message_id");
//将获取到的信件message_id存入缓存,乳沟缓存中有此信件返回false
if($cache_message === false){
if(!$this->debug) {
$this->DC->set_cache_4("shensuMail$message_id",1,strtotime(date("Y-m-d",strtotime("+2 days"))));
}
}else{
if(!$this->debug) {
return false;
}
}
$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();
if (is_array($mail_header->cc)) {
foreach ($mail_header->cc as $k => $v) {
$ccList[] = $v->mailbox . '@' . $v->host;
}
}
$toList = array();
if($mail_header->to) {
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,//抄送人
'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,
);
return $mail_details;
}else{
return false;
}
}
/**
* 获取邮件内容
* @param $mid
* @param $path
* @param $imageList
* @return bool|mixed|string|void
* author : lianghuiju
* function_name : getBody
* description :
*/
function getBody($mid,&$path,$imageList)
{
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 get_mime_type(&$structure) {
$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";
}
/**
* 获取信件的结构信息
* @param $stream
* @param $msg_number
* @param $mime_type
* @param bool|false $structure
* @param bool|false $part_number
* @return bool|string
* author : lianghuiju
* function_name : get_part
* description :
*
*/
function get_part($stream, $msg_number, $mime_type, $structure = false, $part_number = false) {
if(!$structure) {
/**
* imap_fetchstructure()获取信件的结构信息
* 返回数组,其中数组的type 元素的值代表的意义如下
* 值代表意义: 0 文字 text 1 复合 multipart 2 信息 message 3 程序 application 4 声音 audio 5 图形 image 6 影像 video 7 其它 other
* 数组的 encoding 元素的值代表的意义如下
* 值代表意义: 0 七位 (7 bit) 1 八位 (8 bit) 2 二进位 (binary) 3 BASE64 编码 4 QP 编码 (QuotedPrintable) 5 其它
*/
$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 $this->safeEncoding(imap_base64($text));
} else if ($structure->encoding == 4) {
return $this->safeEncoding(imap_qprint($text));
} else {
return $this->safeEncoding($text);
}
}
/* multipart */
if($structure->type == 1){
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;
}
/**
* 获取未读邮件总数
* @return bool|int
* author : lianghuiju
* function_name : getTotalMails
* description :
*/
function getTotalMails() {
if (!$this->marubox)
return false;
// var_dump(imap_search($this->marubox, "UNSEEN"));
// return imap_headers($this->marubox);
return imap_num_recent($this->marubox);
}
//获取一天内的邮件
function search_mail(){
if (!$this->marubox)
return false;
$date = date ( "d M Y", strtotime ( "-1 days" ) );
return $uids = imap_search ($this->marubox, "SINCE \"$date\"", SE_UID );
}
/**
* 获取邮件附件,返回的邮件附件信息数组
* @param $mid
* @param $path
* @return array|bool
* author : lianghuiju
* function_name : GetAttach
* description :
*/
function GetAttach($mid,$path) {
if (!$this->marubox) {
return false;
}
$struckture = imap_fetchstructure($this->marubox,$mid);
$files=array();
if($struckture->parts){
// var_dump($this->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;
$local_path = $path.$file['pathname'];
$fp=fopen($local_path,"w");
if($fp) {
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);
}
}
}
}
}
return $files;
}
/**
* 处理图片
* @param $body
* @param $path
* @param $imageList
* @return mixed|void
* author : lianghuiju
* function_name : embed_images
* description :
*/
function embed_images(&$body,&$path,$imageList) {
// get all img tags
preg_match_all('/<img.*?>/', $body, $matches);
if (!isset($matches[0])) return;
// var_dump($matches);
foreach ($matches[0] as $img) {
// replace image web path with local path
preg_match('/src="(.*?)"/', $img, $m);
preg_match('/alt="(.*?)"/', $img, $t);
// var_dump($m);
// var_dump($t);
if (!isset($m[1])) continue;
if (!isset($t[1])) continue;
$arr = parse_url($m[1]);
// var_dump($arr);
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[$t[1]]['pathname'] . '" style="border: none;" />', $body);
}
}
return $body;
}
/**
* 删除邮件
* @param $mid
* @return bool
* author :lianghuiju
* function_name : deleteMails
* description :
*/
function deleteMails($mid) {
if (!$this->marubox) {
return false;
}
imap_delete($this->marubox, $mid);
}
/**
* 关闭连接
* @return bool
* author : lianghuiju
* function_name : close_mailbox
* description :
*/
function close_mailbox() {
if (!$this->marubox)
return false;
imap_close($this->marubox, CL_EXPUNGE);
}
/**
* 移动邮件到指定分组
* @param $msglist
* @param $mailbox
* @return bool
* author : lianghuiju
* function_name : move_mails
* description :
*/
function move_mails($msglist,$mailbox) {
if (!$this->marubox) {
return false;
}
imap_mail_move($this->marubox, $msglist, $mailbox);
}
/**
* 创建一个信箱分组
* @param $mailbox
* @return bool
* author : lianghuiju
* function_name : creat_mailbox
* description :
*/
function creat_mailbox($mailbox) {
if (!$this->marubox) {
return false;
}
//imap_renamemailbox($imap_stream, $old_mbox, $new_mbox);
imap_create($this->marubox, $mailbox);
}
function _imap_listmailbox(){
$res = imap_listmailbox($this->marubox,$this->server,"*");
if($res){
return $res;
}else{
var_dump(imap_last_error());
}
}
/**
* 转换邮件标题的字符编码,处理乱码
* @param $str
* @return string
* author : lianghuiju
* function_name : decode_mime
* description :
*/
function decode_mime($str){
$str=imap_mime_header_decode($str);
$text = $str[0]->text;
return $this->safeEncoding($text);
}
/**
* 自动获取字符串编码并转换为$outEncoding所指定的编码
* @param $string
* @param string $outEncoding
* @return string
* author : lianghuiju
* function_name : safeEncoding
* description :
*/
public function safeEncoding($string,$outEncoding ='UTF-8') {
$encode_arr = array('UTF-8','ASCII','GBK','GB2312',"BIG5");
$encoded = mb_detect_encoding($string, $encode_arr);//自动判断编码
// var_dump($encoded);
// $encode = mb_detect_encoding($string, array("ASCII","UTF-8","GB2312","GBK","BIG5"));
if($encoded) {
if(in_array(strtolower($encoded),array("cp936","gb18030"))){
$return_str = mb_convert_encoding($string, $outEncoding, "GBK");
}else {
$return_str = mb_convert_encoding($string, $outEncoding, $encoded);
}
}else{
$return_str = mb_convert_encoding($string, $outEncoding, "GBK");
}
return $return_str;
}
/**
* 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('dHis', time()) . $fileID . mt_rand(0, 10000) . '.' . $extension;
}
}下面就来说一下使用方式
<?php
/**
* author : lianghuiju
* description : 获取申诉邮箱邮件
* createby : PhpStorm
*/
header("Content-Type: text/html;charset=utf-8");
date_default_timezone_set("Asia/Shanghai");
set_time_limit(0);
$debug = false;
$start_time = microtime(true);
require_once ('receivemail.class.php');
require_once ('Request.php');
$host = 'pop3.jiayuan'.'.com';
$user = 'shensu@jiayuan'.'.com';
$pass = 'love@21.'.'cn';
//本机保存附件的路径
$savePath = setSavePath();
//文件服务器中保存文件的子路径
$server_path = "shensu_files/".date("Ym");
//删除本地下载的附件
$f = glob($savePath."*"); //glob() 函数返回匹配指定模式的文件名或目录。
if($f){
foreach($f as $v){
unlink($v);//删除文件。
}
}
$obj= new receivemail($user,$pass,$user,$host,"pop3","110",false);
$obj->connect();//链接服务器
//获取1天以内的邮件
$search = $obj->search_mail();
if($search && is_array($search)){
$res = array();
// var_dump($search);
foreach($search as $i){
//获取邮件头信息,并将获取过的邮件的messag_id存入缓存
$head=$obj->getHeaders($i);
if($head === false){
continue;
}
$head['i']=$i;
//处理邮件附件
$files=$obj->GetAttach($i,$savePath); // 获取邮件附件,返回的邮件附件信息数组
$imageList=array();
if(!is_array($files)){$files = array();}
foreach($files as $k => &$file) {
//type=1为附件,0为邮件内容图片
if ($file['type'] == 0) {
$imageList[$file['title']] = $file;
}
//本机所下载的附件全路径
$loca_file = $savePath . $file['pathname'];
if (!$debug) {
compress_images($loca_file, $loca_file);//对大的图片附件进行压缩处理
upload_photo_http($loca_file, $file['pathname']);//上传到文件服务器
} else {
//调试压缩上传
if (filesize($loca_file) > 2000000) {
$fp = pathinfo($loca_file, PATHINFO_BASENAME);
compress_images($savePath . $fp, $savePath . "test_" . $fp);
upload_photo_http($savePath . "test_" . $fp, $fp);
echo "http://help.jyimg.com/" . $server_path . "/test_" . $fp . PHP_EOL;
var_dump($head["fromBy"]);
var_dump($head["subject"]);
echo PHP_EOL;
}
}
//文件服务器端附件访问路径
$file['server_url'] = "http://help.jyimg.com/" . $server_path . "/" . $file['pathname'];
}
$web_path = "http://help.jyimg.com/" . $server_path . "/";
//获取邮件内容
$body = $obj->getBody($i,$web_path,$imageList);
if($body === false){$body = "";}
$res[]=array(
'head'=>$head,
'body'=>$body,
"attachList"=>$files
);
}
$obj->close_mailbox();
if(!$res){
echo_log( "No access to mail ");
exit();
}
if($debug) {
var_dump($res);
die;
}
/*******将获取的邮件存入数据库**********/
$sql_str = "";
$num = 1;
$update_time = time();
foreach($res as $mail){
$send_time = $mail['head']['udate'];
$from_user = htmlspecialchars(addslashes($mail['head']['fromBy']));
$subject = htmlspecialchars(addslashes($mail['head']['subject']));
$content = htmlspecialchars(addslashes($mail['body']));
$status = 1;
$attachment = "";
if($mail['attachList']){
foreach($mail['attachList'] as $attach){
$attach['server_url'] =
$attachment .= $attach['server_url'] ? $attach['server_url']."###" : "";
}
$attachment = trim($attachment,"###");
}
$num++;
$sql_str .= "('{$send_time}','{$from_user}','{$subject}','{$content}','{$attachment}',$status,$update_time),";
}
//测试数据库 $NEW_MDB = new Database(MDB_HOST_TEST,MDB_PORT_TEST,MDB_USER_TEST,MDB_PASSWORD_TEST,MDB_DATABASE_TEST);
$NEW_MDB = new Database(MDB_HOST_NEW,MDB_PORT_NEW,MDB_USER_NEW,MDB_PASSWORD_NEW,MDB_DATABASE_NEW);
//$NEW_SDB = new Database(SDB_HOST_NEW,SDB_PORT_NEW,SDB_USER_NEW,SDB_PASSWORD_NEW,SDB_DATABASE_NEW);
if($sql_str != "") {
$sql = "INSERT INTO `shensu_mail_inboxs` (`send_time`,`from_user`,`subject`,`content`,`attachment`,`status`,`update_time`) VALUES " . trim($sql_str, ',');
if($NEW_MDB->query($sql)){
echo_log("Get {$num} mails to database success");
}
}else{
echo_log("Not sql insert");
}
}
$end_time = microtime(true);
$total_time = $end_time - $start_time;
echo_log("This php script total runtime {$total_time}s");
/**
* 创建本机保存附件的路径
* @return string
* author : lianghuiju
* function_name : setSavePath
* description :
*/
function setSavePath() {
$savePath = DATA_ROOT_PATH."check/shensu/";
if (!file_exists($savePath)) {
@mkdir($savePath, 0755, true);
}
$savePath = rtrim($savePath,"/") . '/';
return $savePath;
}
/**
* 上传附件到文件服务器
* @param $local_filename 本机保存的附件全路径
* @param $server_filename 文件服务器端将保存的文件名
* @return bool
* author : lianghuiju
* function_name : upload_photo_http
* description :
*/
function upload_photo_http($local_filename, $server_filename){
if(!SendQuery($server_filename,$local_filename, 0))
{
// unlink($local_filename);
echo_log("upload attachment fail {$local_filename}");
return false;
}
// unlink($local_filename);
echo_log("upload attachment success");
return true;
}
/**
* 调用接口上传附件
* @param $server_filename文件服务器端保存的文件名
* @param $local_filename本机的附件全路径
* @param $action_type 0:上传 1;删除
* @return bool
* author : lianghuiju
* function_name : SendQuery
* description :
*/
function SendQuery($server_filename,$local_filename,$action_type){
global $server_path;
$http_url = "http://10.0.1.236:8000/check_upload_new.php";
$req = &new HTTP_Request($http_url);
$req->addQueryString("type","photo");
if($action_type==0) {
$req->setMethod(HTTP_REQUEST_METHOD_POST);
$req->addQueryString("path", $server_path);
$req->addQueryString("act", "upload");
// $req->addQueryString("debug", "1");
$result = $req->addFile($server_filename, $local_filename);
if (PEAR::isError($result)) {
$result->getMessage();
return false;
}
}else if($action_type == 1){
$req->setMethod(HTTP_REQUEST_METHOD_GET);
$req->addQueryString("act","delete");
$req->addQueryString("deletepath", $server_path.'/');
$req->addQueryString("deletefile", $server_filename);
}
$response = $req->sendRequest();
// var_dump($req->getUrl('')).PHP_EOL;
// var_dump($req).PHP_EOL;
if (PEAR::isError($response))
{
//$response->getMessage().PHP_EOL;
return false;
}
else
{
$return = json_decode($req->getResponseBody(),true);
$ResponseCode = $req->getResponseCode();
echo $ResponseCode.PHP_EOL;
var_dump($return);
var_dump($req->getResponseBody());
if ($ResponseCode >= 400 ) return false;
if(!$return) return false;
if ($return['flag'] == false) return false;
else return true;
}
}
/**
* 输出格式化日志
* @param $str
* author : lianghuiju
* function_name : echo_log
* description :
*/
function echo_log($str){
echo date("Y-m-d H:i:s")." ".$str.PHP_EOL;
}
/**
* desription 压缩图片
* @param sting $imgsrc 图片路径
* @param string $imgdst 压缩后保存路径
*/
function compress_images($imgsrc,$imgdst){
if(!file_exists($imgsrc)){
return false;
}
$file_type = strtolower(pathinfo($imgsrc,PATHINFO_EXTENSION));
$file_size = filesize($imgsrc);
if(!in_array($file_type,array("jpg","gif","png"))){
return false;
}
//换算为M,超过2M则压缩
if(($file_size/1024/1024) < 2){
return false;
}
list($w,$h,$type)=getimagesize($imgsrc);
$width = 5000;//最大宽高
$height = 5000;
//计算图片缩放后的大小
if($width/$w<$height/$h){
$dw=$width;
$dh=$h*($width/$w);
}else{
$dw=$w*($height/$h);
$dh=$height;
}
switch($type){
case 1:
//创建模板图片画布
$giftype=check_gifcartoon($imgsrc);
if($giftype){
$image_wp=imagecreatetruecolor($dw, $dh);
$image = imagecreatefromgif($imgsrc);
imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $dw, $dh, $w, $h);
imagegif($image_wp, $imgdst);
imagedestroy($image_wp);
}
break;
case 2:
$image_wp=imagecreatetruecolor($dw, $dh);
$image = imagecreatefromjpeg($imgsrc);
imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $dw, $dh, $w, $h);
imagejpeg($image_wp, $imgdst);
imagedestroy($image_wp);
break;
case 3:
$image_wp=imagecreatetruecolor($dw, $dh);
$image = imagecreatefrompng($imgsrc);
imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $dw, $dh, $w, $h);
imagepng($image_wp, $imgdst);
imagedestroy($image_wp);
break;
default:
break;
}
}
/**
* desription 判断是否gif动画
* @param sting $image_file图片路径
* @return boolean t 是 f 否
*/
function check_gifcartoon($image_file){
$fp = fopen($image_file,'rb');
$image_head = fread($fp,1024);
fclose($fp);
return preg_match("/".chr(0x21).chr(0xff).chr(0x0b).'NETSCAPE2.0'."/",$image_head)?false:true;
}
神回复
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。