如何使用PHP IMAP将包含附件的所有邮件下载到服务器? [英] How to Download all mail with attachments to server using PHP IMAP?

查看:199
本文介绍了如何使用PHP IMAP将包含附件的所有邮件下载到服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用PHP IMAP功能我可以阅读电子邮件,但是我需要自动运行或手动运行以下载邮件,我如何下载带有或不带附件的所有电子邮件并将其保存到主要网络的邮件文件夹名称中的本地驱动器或服务器(gmail,yahoo,hotmail,AOL)。 解决方案

请尝试使用此代码将电子邮件和商店附件提取到目录中。



您也可以使用imap_delete和imap_expunge从邮箱中取出邮件。



在下面的代码中设置您的网站名称,邮箱用户名,密码以及用于存储附件的路径。

  if($ mbox = imap_open( {yoursitename.com:110/pop3/notls}INBOX,邮箱用户名,邮箱密码)){
$ path =在这里设置附件存储位置的路径;
$ check = imap_mailboxmsginfo($ mbox);
函数getmsg($ mbox,$ mid){
全局$ charset,$ htmlmsg,$ plainmsg,$附件,$ from,$ to,$ subj,$ timages,$ path;
$ htmlmsg = $ plainmsg = $ charset ='';
$ attachments = array();
// HEADER
$ h = imap_headerinfo($ mbox,$ mid);
//在这里添加代码以获取日期,从,到,cc,主题...
$ date = $ h-> date;
$ from = $ h-> fromaddress;
$ to = $ h-> toaddress;
$ subj = htmlspecialchars($ h-> Subject);
// BODY
$ s = imap_fetchstructure($ mbox,$ mid);
if(!$ s-> parts)//简单
getpart($ mbox,$ mid,$ s,0); //将0作为零件号
else {//多部分:循环遍历每个零件
foreach($ s->零件作为$ partno0 => $ p)
getpart($ MBOX,$中旬,$ p,$ partno0 + 1);



函数getpart($ mbox,$ mid,$ p,$ partno){
// $ partno ='1','2' ,'2.1','2.1.3'等多部分,0如果简单
全局$ htmlmsg,$ plainmsg,$ charset,$附件,$ partid,$ last_mail_id,$ patterns,$ pic,$ newstr, $ C,$确定,$ timages,$ SUBJ,$路径;
$ patterns = array();
$ pic = array();
$ image = array();
$ data =($ partno)? imap_fetchbody($ mbox,$ mid,$ partno):imap_body($ mbox,$ mid); // $ simple
if($ p-> encoding == 4)
$ data = quoted_printable_decode($ data);
else if($ p-> encoding == 3)
$ data = base64_decode($ data);
// PARAMETERS //获取所有参数,例如字符集,附件的文件名等。
$ params = array();
if($ p-> parameters)
foreach($ p->参数为$ x)
$ params [strtolower($ x->属性)] = $ x- >值; ($ p-> dparameters)
foreach($ p-> dparameters as $ x)
$ params [strtolower($ x->属性)] = $ x- >值;

//附件//任何带有文件名的零件都是附件,
//所以附加的文本文件(类型0)不会被误认为是消息。
if($ params ['filename'] || $ params ['name']){
$ partid = htmlentities($ p-> id,ENT_QUOTES);

//文件名可能会以'文件名'或'名称'或两者同时给出
$ filename =($ params ['filename'])? $ params ['filename']:$ params ['name'];
// filename可能会被编码,所以请参阅imap_mime_header_decode()
$ attachments [$ filename] = $ data; //这是一个问题,如果两个文件具有相同的名称
//在阵列中存储id和文件名
$ image [$ key] = $ filename;

$ b $ //将附件保存在目录
foreach($ attachments as $ key => $ val){
$ fname = $ key;
$ fp = fopen($ path / $ fname,w);
fwrite($ fp,$ val);
fclose($ fp);
}
// TEXT
if($ p-> type == 0&& $ data){
//消息可能在不同的部分被分割,因为内联附件,//将空白行附加在一起。
if(strtolower($ p-> subtype)=='plain')
$ plainmsg。= trim($ data)。\\\
\\\
;
else
// preg_match_all('/< img [^>] +> / i',$ data,$ result);
$ htmlmsg。= $ data。< br>< br>;
$ charset = $ params ['charset']; //假设所有部分都是相同的字符集
}

//没有PHP函数可以解析嵌入的消息,所以这只是将原始源添加到主消息。
else if($ p-> type == 2&& $ data){
$ plainmsg。= $ data。\\\
\\\
;
}
// SUBPART RECURSION
if($ p-> parts){
foreach($ p-> parts as $ partno0 => $ p2)
getpart($ mbox,$ mid,$ p2,$ partno。'。'。($ partno0 + 1)); // 1.2,1.2.1等
}
}

$ attachments = array();
$ num_msg = imap_num_msg($ mbox);
if($ num_msg> 0){
getmsg($ mbox,1);
} else {
echoSorry!...邮箱中没有邮件...< br>;
}

// imap_delete和imap_expunge用于在取回后删除邮件....如果要从邮箱中删除邮件,请取消注释
// imap_delete($ MBOX,1);
// imap_expunge($ mbox);
imap_close($ mbox);
$ b $} else {exit(Can not connect:。imap_last_error()。\\\
);回声失败!\\\
; };


Using PHP IMAP function i can read email, but i need to run autoamtically or manually to download messages , how can i download all email messages with or without attachments and saved it to local drive or server in mailid folder name for major networks (gmail,yahoo,hotmail,AOL).

解决方案

Please try this code to fetch the email and store attachments in a directory.

You can also delete the mail using imap_delete and imap_expunge, after you have fetched it from the mailbox.

In the below code set your website name, mailbox username, password and path for storing attachments.

if( $mbox = imap_open("{yoursitename.com:110/pop3/notls}INBOX", "username of mailbox", "password of mailbox")){
    $path = "set path here for where the attachments are store";
    $check = imap_mailboxmsginfo($mbox);     
    function getmsg($mbox,$mid) {   
        global $charset,$htmlmsg,$plainmsg,$attachments,$from,$to,$subj,$timages,$path;
        $htmlmsg = $plainmsg = $charset = '';
        $attachments = array();
        // HEADER
        $h = imap_headerinfo($mbox,$mid);
        // add code here to get date, from, to, cc, subject...
        $date = $h->date;
        $from = $h->fromaddress;
        $to = $h->toaddress;
          $subj = htmlspecialchars($h->Subject);
        // BODY
        $s = imap_fetchstructure($mbox,$mid);
        if (!$s->parts)  // simple
        getpart($mbox,$mid,$s,0);  // pass 0 as part-number
        else {  // multipart: cycle through each part
        foreach ($s->parts as $partno0=>$p)
          getpart($mbox,$mid,$p,$partno0+1);
        }
    }

    function getpart($mbox,$mid,$p,$partno) {
        // $partno = '1', '2', '2.1', '2.1.3', etc for multipart, 0 if simple
        global $htmlmsg,$plainmsg,$charset,$attachments,$partid,$last_mail_id,$patterns,$pic,$newstr,$c,$ok,$timages,$subj,$path;
        $patterns = array();
        $pic =  array();
        $image=array();
        $data = ($partno) ? imap_fetchbody($mbox,$mid,$partno) : imap_body($mbox,$mid);  // simple
        if ($p->encoding==4)
        $data = quoted_printable_decode($data);
        else if ($p->encoding==3)
        $data = base64_decode($data);
        // PARAMETERS    // get all parameters, like charset, filenames of attachments, etc.
        $params = array();
        if ($p->parameters)
        foreach ($p->parameters as $x)
            $params[strtolower($x->attribute)] = $x->value;
        if ($p->dparameters)
        foreach ($p->dparameters as $x)
            $params[strtolower($x->attribute)] = $x->value;

        // ATTACHMENT    // Any part with a filename is an attachment,
        // so an attached text file (type 0) is not mistaken as the message.
        if ($params['filename'] || $params['name']) {
        $partid = htmlentities($p->id,ENT_QUOTES);

           // filename may be given as 'Filename' or 'Name' or both
        $filename = ($params['filename'])? $params['filename'] : $params['name'];
        // filename may be encoded, so see imap_mime_header_decode()
         $attachments[$filename] = $data;  // this is a problem if two files have same name
        //store id and filename in array
        $image[$key] = $filename;

        }
        //save the attachments in the directory
        foreach( $attachments as $key => $val){
          $fname = $key;
          $fp = fopen("$path/$fname","w");
          fwrite($fp, $val);
          fclose($fp);
        }
            // TEXT
            if ($p->type==0 && $data) {
            // Messages may be split in different parts because of inline attachments,   // so append parts together with blank row.
            if (strtolower($p->subtype)=='plain')
                $plainmsg .= trim($data)."\n\n";
            else
                //preg_match_all('/<img[^>]+>/i',$data, $result);
                $htmlmsg .= $data."<br><br>";
                $charset = $params['charset'];  // assume all parts are same charset
            }

        // There are no PHP functions to parse embedded messages, so this just appends the raw source to the main message.
        else if ($p->type==2 && $data) {
        $plainmsg .= $data."\n\n";
        }
        // SUBPART RECURSION
        if ($p->parts) {
        foreach ($p->parts as $partno0=>$p2)
            getpart($mbox,$mid,$p2,$partno.'.'.($partno0+1));  // 1.2, 1.2.1, etc.
        }
    }

    $attachments = array();
    $num_msg = imap_num_msg($mbox);
    if($num_msg>0) {
        getmsg($mbox,1);
    }else {
         echo "Sorry!...No Messages in MailBox...<br>";
    }

    //imap_delete and imap_expunge are used to delete the mail after fetching....Uncomment it if you want to delete the mail from mailbox
    //imap_delete($mbox,1); 
    //imap_expunge($mbox);
    imap_close($mbox);

}else { exit ("Can't connect: " . imap_last_error() ."\n");  echo "FAIL!\n";  };

这篇关于如何使用PHP IMAP将包含附件的所有邮件下载到服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆