//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop

#include "qfspop.h"
#include "qfsrecv1.h"
#include "nMail.h"
#include "qfsdm.h"
#include "stdio.h"
#include "jis2001.h"
#include "Jconvert.hpp"
#include "base64.h"
#pragma package(smart_init)
#define HEADER_MAX 81920
#define BUF_SIZE 10240
const QLEN=800000;//SQL長さ
const MAXPOPCNT=500;//1回のPOPで受信できるﾒｰﾙ数
FILE *FI_HEAD;
AnsiString logstr;
#define AddLog(s) logstr=s;Synchronize(AddLog1)
#define Status(s) logstr=s;Synchronize(Status1)
#define AddList(st) li_list->Add(st)
//---------------------------------------------------------------------------

// 注意：異なるスレッドが所有する VCL のメソッド/関数/プロパティを
//       別のスレッドの中から扱う場合，排他処理の問題が発生します。
//
//       メインスレッドの所有するオブジェクトに対しては Synchronize
//       メソッドを使う事ができます。他のオブジェクトを参照するため
//       のメソッドをスレッドクラスに追加し，Synchronize メソッドの
//       引数として渡します。
//
//       たとえば UpdateCaption を以下のように定義し、
//
//      void __fastcall ThPop::UpdateCaption()
//      {
//        Form1->Caption = "スレッドから書き換えました";
//      }
//
//       Execute メソッドの中で Synchronize メソッドに渡すことでメイ
//       ンスレッドが所有する Form1 の Caption プロパティを安全に変
//       更できます。
//
//      Synchronize(UpdateCaption);
//
//---------------------------------------------------------------------------
__fastcall ThPop::ThPop(bool CreateSuspended)
        : TThread(CreateSuspended)
{
// AddLog("pop start");
}
//---------------------------------------------------------------------------
void __fastcall ThPop::Execute()
{
 int i,a;
 fi_head=INI("TempDir")+"\\header.log";
 fi_list=INI("TempDir")+"\\"+Now().FormatString("yymmddhhnnss")+".nMl";
// li_split=new TStringList();
 li_split2=new TStringList();
 li_sql=new TStringList();
 li_list=new TStringList();
 li_head=new TStringList();
 RecieveResult="";
 if(FrmRecv->serverNo==-1){a=0;
  for(i=0;i<FrmRecv->li_ini->Count;i++){
   if(FrmRecv->li_ini->Strings[i].Pos("Pop")==1){
    if(RecieveResult!=""){RecieveResult=RecieveResult+"/";}
     RecieveMail(a);++a;}}}
 else RecieveMail(FrmRecv->serverNo);

 AddList("status|0|"+RecieveResult);
 li_list->SaveToFile(fi_list);
 AddLog("complete");
 delete li_list;
 delete li_split2;
 delete li_sql;
 FrmRecv->DropToMailer(fi_list);
}
//---------------------------------------------------------------------------
bool __fastcall ThPop::delTab(AnsiString &st){
 int a;bool re=false;
 while((a=AnsiPos("\t",st))!=0){st[a]=' ';re=true;}
 while((a=AnsiPos("  ",st))!=0){st.Delete(a,1);re=true;}
 return re;
}

void __fastcall ThPop::DeleteEscape(AnsiString &st){
 int a;if((a=st.Pos("\x1b(J"))!=0)st.Delete(a,3);}

AnsiString __fastcall ThPop::HeadVal(AnsiString na,TStringList *li){
 int i,j,a;AnsiString st,rs;bool hd=false;
 rs="";na=na.LowerCase();
 for(i=0;i<li->Count;i++){
  st=li->Strings[i];
  if(hd){if(st==""||st[1]>32){//対象ﾍｯﾀﾞﾊﾟﾗﾒﾀ終わり?
   rs=ConvertJCode(rs,SJIS_OUT);DeleteEscape(rs);
   return rs;}
   a=0;j=1;st=st.Trim();//while(j<=st.Length()&&st[j]<33){++a;++j;}st.Delete(1,a);
   rs=rs+Bencode(st);}
  else if(st.LowerCase().Pos(na)==1){st.Delete(1,na.Length()+2);st=st.Trim();rs=Bencode(st);hd=true;}}
 rs=ConvertJCode(rs,SJIS_OUT);
// ToSjis(rs);
 DeleteEscape(rs);return rs;
 }

char HexToInt(char a,char b){
 if(a>='a'&&a<='f')a-='a'-10;else if(a>='A'&&a<='F')a-='A'-10;else a-='0';
 if(b>='a'&&b<='f')b-='a'-10;else if(b>='A'&&b<='F')b-='A'-10;else b-='0';
 return (a<<4)|b;}

AnsiString __fastcall ThPop::Bencode(AnsiString st){
 AnsiString st2;unsigned char *buf,*buf2,*q,*p;
 AnsiString b_pat[]={"=?ISO-2022-JP?B?","=?EUC-JP?B?","=?UTF-8?B?","=?SHIFT_JIS?B?"};
 AnsiString q_pat[]={"=?ISO-2022-JP?Q?","=?EUC-JP?Q?","=?UTF-8?Q?","=?SHIFT_JIS?Q?"};
 unsigned short cod[]={JIS2K_JIS,JIS2K_EUC,JIS2K_UTF8,JIS2K_SJIS};
 int a,a2,len=st.Length(),i,j,len2=len*2;
 buf=new unsigned char[len2];
 buf2=new unsigned char[len2];
// StrPCopy(buf2,st);p=buf2;q=buf;
// while(*p){if(*p!=' '){*q=*p;++q;}++p;}*q=0;st=StrPas(buf);
 for(i=0;i<4;i++){
 do{
  a=st.UpperCase().AnsiPos(b_pat[i]);
  if(a!=0){
   st.Delete(a,b_pat[i].Length());
   a2=st.AnsiPos("?=");
   st2=st.SubString(a,a2-a);
   StrPCopy(buf2,st2);
   if(!decode(buf2,buf)){buf[mime_len]=0;
    st.Delete(a2,2);st.Delete(a,a2-a);
    StrCopy(buf2,buf);ToSjisChar(buf,buf2,cod[i],len2);
    st.Insert(StrPas(buf),a);}}
 }while(a!=0);}

 int q_len;unsigned char h1,h2;
 for(i=0;i<4;i++){
 do{
  a=st.UpperCase().Pos(q_pat[i]);
  if(a!=0){
   st.Delete(a,q_pat[i].Length());
   a2=st.Pos("?=");
   st2=st.SubString(a,a2-a);
   StrPCopy(buf2,st2);p=buf2;q=buf;q_len=0;len=st2.Length();
   for(j=0;j<len;j++){
    if(*p=='='){h1=*(p+1);h2=*(p+2);
     if( ((h1>='0'&&h1<='9')||(h1>='A'&&h1<='F')||(h1>='a'&&h1<='f'))
       &&((h2>='0'&&h2<='9')||(h2>='A'&&h2<='F')||(h2>='a'&&h2<='f'))){
     *(q++)=HexToInt(h1,h2);
     p+=3;j+=2;}else{++p;--q_len;while(j<len&&*p<32){++p;++j;} }//if(*p=='='){++p;++i;}
   }else{*(q++)=*(p++);}++q_len;}*q=0;
   st.Delete(a2,2);st.Delete(a,a2-a);
   StrCopy(buf2,buf);ToSjisChar(buf,buf2,cod[i],len2);
   st.Insert(StrPas(buf),a);
}
  }while(a!=0);}

// ToSjis(st);
 delete buf;delete buf2;
 return st;
}
//---
void __fastcall ThPop::ToSjisChar(char *buf,char *buf2,unsigned short cod,int len){
 #define cod(X) /*Application->MessageBox(X,"knj",MB_OK)*/
 #define AMM 4
 switch(cod){
  case JIS2K_JIS:Iso2022jpToSjis(buf2,buf,len);StrCopy(buf,buf2);break;
  case JIS2K_EUC:EucToSjis(buf2,buf,len);StrCopy(buf,buf2);break;
  case JIS2K_UTF8:UTF8ToUnicode((wchar_t*)buf2,buf,len);
   StrCopy(buf,buf2);UnicodeToSjis(buf,(wchar_t*)buf2,len);break;
  case JIS2K_SJIS:break;}}

void __fastcall ThPop::ToSjis(AnsiString &st){
 #define cod(X) /*Application->MessageBox(X,"knj",MB_OK)*/
 #define AMM 4
 bool err=false;
 int han,len,len2;
 char *buf,*buf2;wchar_t *buf3;
try{len=st.Length();
 buf=new char[st.Length()+AMM];StrPCopy(buf,st);
 buf[len]=0;
 switch(GetKanjiCodeType(buf,len-1)){
  case JIS2K_JIS:SKIP_JIS:cod("JIS");
   len2=Iso2022jpToSjis(NULL,buf,0);buf2=new char[len2+AMM];
        Iso2022jpToSjis(buf2,buf,len2+AMM);break;
  case JIS2K_EUC:SKIP_EUC:cod("EUC");
   len2=EucToSjis(NULL,buf,0);buf2=new char[len2+AMM];
        EucToSjis(buf2,buf,len2+AMM);buf2[len2]=0;break;
  case JIS2K_UTF8:SKIP_UTF8:cod("UTF8");
   len2=UTF8ToUnicode(NULL,buf,0);buf3=new wchar_t[len2+AMM];
        UTF8ToUnicode(buf3,buf,len2+AMM);
   len2=UnicodeToSjis(NULL,buf3,0);buf2=new char[len2+AMM];
        UnicodeToSjis(buf2,buf3,len2*AMM);delete buf3;break;
  case JIS2K_UNICODE:SKIP_UNICODE:cod("Unicode");
   len2=UnicodeToSjis(NULL,(wchar_t *)buf,0);buf2=new char[len2+AMM];
        UnicodeToSjis(buf2,(wchar_t *)buf,len2+AMM);break;
  case JIS2K_SJIS:SKIP_SJIS:cod("SJIS");goto POKO;
  default:POKO:st=StrPas(buf);delete buf;return;}
 st=StrPas(buf2);
}catch(...){err=true;}
 SKIP_READ:
 if(err){st="Failed get text";}
 delete buf;delete buf2;}

void __fastcall ThPop::AddLog1(void){
 FrmRecv->Memo1->Lines->Add(logstr);}

void __fastcall ThPop::Status1(void){
 FrmRecv->StatusBar1->SimpleText=logstr;}

void __fastcall ThPop::WriteHeader(int m_id,char *st){//return;
// if(st.Length()>256)st=st.SubString(1,255);
 fputs(("**"+IntToStr(m_id)+"**\n").c_str(),FI_HEAD);
 fputs(st,FI_HEAD);
 fputs("\n",FI_HEAD);}

 int __fastcall ThPop::sql(AnsiString q){//if(!dbok)return 0;
// WriteLog(q);
 DM1->SQLQuery2->SQL->Text=q;/*Clear();
 DM1->SQLQuery2->SQL->Add(q);*/
 DM1->SQLQuery2->ExecSQL(true);
 return DM1->SQLQuery2->RowsAffected;
}

void __fastcall ThPop::sql2(AnsiString q){//if(!dbok)return;
// if(isRecieve)return;
// WriteLog(q);
// DM1->SQLQuery2->Close();
 DM1->SQLQuery2->SQL->Clear();
 DM1->SQLQuery2->SQL->Add(q);
 DM1->SQLQuery2->Open();
}

int __fastcall ThPop::sqm(AnsiString q){
// WriteLog(q);
 DM1->SQLQuery3->SQL->Clear();
 DM1->SQLQuery3->SQL->Add(q);
 DM1->SQLQuery3->ExecSQL(true);
 return DM1->SQLQuery3->RowsAffected;
}

void __fastcall ThPop::sqm2(AnsiString q){
// WriteLog(q);
 DM1->SQLQuery3->SQL->Clear();
 DM1->SQLQuery3->SQL->Add(q);
 DM1->SQLQuery3->Open();}

//--- Split
/*void __fastcall ThPop::Split(AnsiString txt,char c){
 int a;li_split->Clear();
 while((a=txt.AnsiPos(c))!=0){
  li_split->Add(txt.SubString(1,a-1));
  txt.Delete(1,a);}
 li_split->Add(txt);}*/

void __fastcall ThPop::Split2(AnsiString txt,char c){
 int a;li_split2->Clear();
 while((a=txt.AnsiPos(c))!=0){
  li_split2->Add(txt.SubString(1,a-1));
  txt.Delete(1,a);}
 li_split2->Add(txt);}

bool isNoDelete,isReci;int DayDiff;
//受信したものをInsert
int __fastcall ThPop::InsertMail(int m_id,int d_id,char flag,char state,
AnsiString mailfrom,AnsiString recipients,AnsiString cc,AnsiString replyto,
AnsiString sdate,AnsiString subject,char priority,
AnsiString header,AnsiString body,int size,AnsiString MessageId){
 int i;unsigned short a;
// AnsiString sdate=date.FormatString("yyyy-mm-dd hh:nn:ss");
 ToSjis(body);//=ConvertJCode(body,SJIS_OUT);
 delTab(subject);
 delTab(recipients);
 delTab(cc);
 delTab(replyto);
 delTab(mailfrom);

 if(sdate.Length()!=19)sdate="1899/12/30 12:00:00";
 else{for(i=1;i<sdate.Length();i++){if(sdate[i]=='/')sdate[i]='-';}}
 subject=GenChar(subject);
 if(isNoDelete){
  sqm2("select m_id,regdate from mail where date='"+sdate+"' and subject="+subject);
  if(ROWSM){
//   (Now()-reDatem(1)).DecodeDate(&a,&a,&DayDiff);//ShowMessage(IntToStr(DayDiff));
   DayDiff=Now()-reDatem(1);
   isReci=false;return 0;}}

 GenCharStore(body,li_sql);
 bool errflg=false;int chance=5;
 RETRY_IM:
 try{
 sqm("insert into mail (m_id,d_id,flag,s_id,mailfrom,recipients,cc,replyto,date,subject,priority,"
 "size,regdate) values ("+str(m_id)+","
 +str(d_id)+","+str(flag)+","+str(state)+","
 +GenChar(mailfrom)+","+GenChar(recipients)+","+GenChar(cc)+","+GenChar(replyto)+",'"+sdate+"',"
 +subject+",'"+str(priority)+"',"+str(size)+",'"/*+MessageId+"','"*/+Now().FormatString("yyyy-mm-dd hh:nn:ss")+"')");
 }catch(...){++m_id;--chance;errflg=true;}
 if(errflg&&chance>0){Sleep(500+rand()%1000);goto RETRY_IM;}
//,"+li_sql->Strings[0]+"
 sqm("insert into mailbody (m_id,body) values ("+str(m_id)+","+li_sql->Strings[0]+")");
 for(i=1;i<li_sql->Count;i++){sqm("update mailbody set body=concat(body,"+li_sql->Strings[i]+") where m_id="+str(m_id));/*WriteLog("LONG m_id="+str(m_id)+","+str(i));*/}

// WriteLog("OK");sql(q3);
//return m_id; //Divide
// CLOSEM;
// if(state==0){
//振り分け処理
 AnsiString q,q2;
 for(i=0;i<FrmRecv->li_ini->Count;i++){
  q=FrmRecv->li_ini->Strings[i];if(q.AnsiPos("Div")==1){q.Delete(1,q.AnsiPos("="));
   int a=q.AnsiPos(">>");
/*   st=q.SubString(1,a);
   gbr->Split("m/>>/",q,2);*///gbr->Split("m/>>/",q,2);
//   if(gbr->Count==2){d_id=StrToInt(gbr->Strings[1]);q2=gbr->Strings[0].Trim();
   if(a){q2=q.SubString(1,a-1).Trim();q.Delete(1,a+2);
    if(q.Pos("pop")){//ポップアップ
     q="select subject from mail where m_id="+str(m_id);
     if(q2!="")q=q+" and ("+q2+")";
     sqm2(q);if(ROWSM==1){AddList("pop|"+IntToStr(m_id)+"|"+reStrm(0));}}
    else{d_id=StrToInt(q);
     q="update mail set d_id="+str(d_id)+" where m_id="+str(m_id)/*+" and d_id=0"*/;
     if(q2!="")q=q+" and ("+q2+")";
   // WriteLog(q);
     if(sqm(q)>0){break;}}}
   }//}
 }return m_id;}

int __fastcall ThPop::InsertAttachment(int m_id,AnsiString filename,AnsiString encode){
 int rowfile;
 sqm2("select max(rowfile) from attachment");rowfile=reIntm(0)+1;
// if(encode.LowerCase()=="base64")BinStore(body,li_sql);else GenCharStore(body,li_sql);
 bool errflg=false;int chance=5;
 RETRY_IA:
 try{
 sqm("insert into attachment (m_id,filename,encode,rowfile) values ("+str(m_id)+","+GenChar(filename)+",'"+encode+"',"+str(rowfile)+")");
 }catch(...){++rowfile;--chance;errflg=true;}
 if(errflg&&chance>0){Sleep(500+rand()%1000);goto RETRY_IA;}
 AddLog("添付:"+IntToStr(rowfile)+":"+filename);
 //WriteLog("TOPA m_id="+str(m_id)+","+li_sql->Strings[0]);
// for(i=1;i<li_sql->Count;i++){sqm("update attachment set body=concat(body,"+li_sql->Strings[i]+") where m_id="+str(m_id));}
////  WriteLog("LONGA m_id="+str(m_id)+","+str(i)+","+li_sql->Strings[i].SubString(1,16));
 return rowfile;}

AnsiString __fastcall ThPop::GenChar(AnsiString st){
 int len;
 if((len=st.Length())==0)return "''";
 int i;/*AnsiString st2="CHAR(";*/unsigned char j,l;
// FrmQfs->WriteLog("GENstart"+str(st.Length()));
 char *buf,s[8],*p,*q,*sp;
 buf=new char[len*4+4];
 q=st.c_str();p=buf;
 for(i=0;i<len;i++){
  sprintf(s,"%d,",(unsigned char)*(q++));l=strlen(s);
  sp=s;for(j=0;j<l;j++){*(p++)=*(sp++);}}
 *(p-1)=0;
 st="CHAR("+StrPas(buf)+")";delete buf;
 return st;}

void __fastcall ThPop::GenCharStore(AnsiString st,TStringList *li_sql){
 int len,blen;
 li_sql->Clear();
 if((len=st.Length())==0){li_sql->Add("''");return;}

 int i;unsigned char j,l;
 char *buf,s[8],*p,*q,*sp;
 buf=new char[len*4+4];
 q=st.c_str();p=buf;blen=0;
 for(i=0;i<len;i++){
  sprintf(s,"%d,",(unsigned char)*(q++));l=strlen(s);
  sp=s;for(j=0;j<l;j++){*(p++)=*(sp++);++blen;}
  if(blen>QLEN){blen=0;*(p-1)=0;li_sql->Add("CHAR("+StrPas(buf)+")");p=buf;}
  }
 if(blen>0){*(p-1)=0;li_sql->Add("CHAR("+StrPas(buf)+")");}
 delete buf;}

//void deltab(char *p){ while(*p){if(*p==9)*p=32;++p;}}

//----- 受信ﾙｰﾌﾟ
void __fastcall ThPop::RecieveMail(int sv){
// if(!dbok)return;
 int i,j,k,cnt,cntHtml,m_id,MaxSize,a1,rowfile;
 //TStringList *li,*li_head,*li_body,*li_boundary;
// AnsiString Head,Body,From,To,Cc,ReplyTo,Subject,ContentType,ContentDisposition,st,filename,RDate,Encode;
 AnsiString st,Subject,ReplyTo;
 SOCKET S;
 char *pBody;int size,errcd;
 char pSubject[HEADER_MAX],pDate[BUF_SIZE],pFrom[HEADER_MAX],
 pTo[BUF_SIZE],pCc[BUF_SIZE],pReplyTo[BUF_SIZE],pXPrioryty[32],pAttachement[BUF_SIZE];
 char pHeader[HEADER_MAX];
 TDateTime dtRDate;
 AnsiString Name;int err=0,DeleteDay;
 char mo,mo2,*buf,Priority;bool isBody;
 if((FI_HEAD=fopen(fi_head.c_str(),"a"))==NULL){
  AddLog("Cannot open "+fi_head);return;}

// li=new TStringList();li_head=new TStringList();li_body=new TStringList();li_boundary=new TStringList();
 st=INI("Pop"+IntToStr(sv));
 Split2(st,'|');
 isNoDelete=(li_split2->Strings[PopNoDelete]==1)?true:false;
 if(li_split2->Strings[PopDeleteDay]!=""){DeleteDay=StrToInt(li_split2->Strings[PopDeleteDay]);}else DeleteDay=-1;

 Name=li_split2->Strings[PopName];
 AddLog("Connect "+li_split2->Strings[PopHost]);

 if((S=NMailPop3ConnectPortNo(li_split2->Strings[PopHost].c_str(),StrToInt(li_split2->Strings[PopPort])))==INVALID_SOCKET){err=-1;AddLog("失敗");goto CON_ERR_SKIP;}

// ShowMessage(li_split2->Text);
 if((cnt=NMailPop3Authenticate(S,li_split2->Strings[PopUser].c_str(),FrmRecv->strDecrypt(li_split2->Strings[PopPassword],Name[1]&127).c_str(),(li_split2->Strings[PopApop]=="1")?true:false))<0){err=-2;goto CON_ERR_SKIP;}
 if(cnt>MAXPOPCNT)cnt=MAXPOPCNT;
 MaxSize=StrToInt(INI("MaxMailSize"))*1024;
 //AddLog("接続");//+IdPOP31->Host;
//x FrmPopup->Init();
 if(cnt){AddLog("recieving "+IntToStr(cnt)+"mails..");}else{AddLog("no mails");}

// IdPOP31->Connect();
// cnt=IdPOP31->CheckMessages();if(cnt>MAXPOPCNT)cnt=MAXPOPCNT;

//x if(cnt&&FrmNew->li_m_id->Count){FrmNew->Add(-1,"");}
// int tick=GetTickCount();
 for(i=1;i<=cnt;i++){isReci=true;/*受信済ﾒｰﾙﾁｪｯｸ用*/
  Status(Name+":"+IntToStr(i)+"/"+IntToStr(cnt));
//  if(GetTickCount()-tick>TI_INTERVAL){Application->ProcessMessages();tick=GetTickCount();}
  size=NMailPop3GetMailSize(S,i);
  if(size>MaxSize){++err;continue;}

  try{
   pBody=new char[size*2+2];
   if((errcd=NMailPop3GetMail(S,i,pSubject,pDate,pFrom,pHeader,pBody,INI("TenpDir").c_str(),pAttachement))
    !=NMAIL_SUCCESS){
    isReci=false;
    AddLog(IntToStr(i)+":recv Error code:"+IntToStr(errcd));++err;goto ERRSKIP;}
   //deltab(pSubject);
   Subject=StrPas(pSubject);
   li_head->Text=StrPas(pHeader);
//   delTab(Subject);
   //--- DELFILTER---
   j=1;while(INI("DelFilter"+IntToStr(j))!=""){
   if(Subject.AnsiPos( INI("DelFilter"+IntToStr(j)))!=0){Subject="★"+Subject;goto DELSKIP;}++j;}

//  ShowMessage(pSubject);
//  IdPOP31->RetrieveRaw(i,li);
   sqm2("select max(m_id) from mail");m_id=reIntm(0)+1;

   //--- ﾍｯﾀﾞ取得
   NMailGetHeaderField(pTo,pHeader,"To:",BUF_SIZE);//deltab(pTo);
   NMailGetHeaderField(pCc,pHeader,"Cc:",BUF_SIZE);//deltab(pCc);
//   NMailGetHeaderField(pReplyTo,pHeader,"Reply-To:",BUF_SIZE);
   ReplyTo=HeadVal("Reply-To",li_head);
   NMailGetHeaderField(pXPrioryty,pHeader,"X-Priority:",BUF_SIZE);
   if(pXPrioryty[0])Priority=pXPrioryty[0]-'0';else Priority=3;
   //st=HeadVal("X-Priority",li_head);if(st.Length())Priority=st[1]-'0';else Priority=3;
//   AddLog("prio:"+StrPas(pXPrioryty));
//   AddLog(Subject);
//   AddLog("prio:"+st);
//   AddLog("REPLY:"+ReplyTo);
   if(pHeader[0])WriteHeader(m_id,pHeader);

  //--- Insert
   m_id=InsertMail(m_id,1,(pAttachement[0])?1:0,1,pFrom,pTo,pCc,ReplyTo,pDate,Subject,Priority,pHeader,pBody,size,"");
   if(pAttachement[0]){
    Split2(pAttachement,',');
    for(j=0;j<li_split2->Count;j++){
     st=li_split2->Strings[j];
     rowfile=InsertAttachment(m_id,st,"copy");
//   ShowMessage(st+","+INI("TenpDir")+"\\"+IntToStr(rowfile));
    RenameFile(INI("TenpDir")+"\\"+st,INI("TenpDir")+"\\"+IntToStr(rowfile));}}
   else{if(li_head->Text.AnsiPos("multipart/mixed"))/*&&size>10000&&Subject.AnsiPos("#")!=1&&Subject.AnsiPos("*")!=1)*/{++err;isReci=false;AddLog("添付ｴﾗｰ:"+Subject);goto ERRSKIP;}}



   if(!isNoDelete||(!isReci&&DayDiff>DeleteDay&&DeleteDay!=-1)){//ShowMessage("Diff="+IntToStr(DayDiff)+"\nDeleteDay="+IntToStr(DeleteDay));
    DELSKIP:
    NMailPop3DeleteMail(S,i);}
  ERRSKIP:
  delete pBody;
  }catch(...){
/*   if(Application->MessageBox(("件名:"+StrPas(pSubject)+"\nをﾒｰﾙｻｰﾊﾞｰから削除しますか?").c_str(),"受信失敗",MB_ICONERROR|MB_YESNO)==ID_YES){
    NMailPop3DeleteMail(S,i);}*/
   isReci=false;
   AddLog("Error Recv:"+StrPas(pDate)+"\n"+StrPas(pBody));++err;}
  CLOSEM;
  if(isReci){AddList("new|"+IntToStr(m_id)+"|"+Subject);}
  }
  NMailPop3Close(S);
  AddLog("Disconnected");
 CON_ERR_SKIP:
 S=INVALID_SOCKET;
// IdPOP31->Disconnect();
// }catch(...){WriteLog("Error Connect:"+Name);err=-1;}
// delete li;delete li_head;delete li_body;delete li_boundary;
 fclose(FI_HEAD);
// DM1->ClientDataSet1->CancelUpdates();
// DM1->ClientDataSet1->Refresh();
 if(err==-1){RecieveResult=RecieveResult+Name+":接続ｴﾗｰ";}
 else if(err==-2){RecieveResult=RecieveResult+Name+":認証ｴﾗｰ";}
//  FrmNew->StatusBar1->SimpleText=Name+":接続ｴﾗｰ";}
 else if(err){RecieveResult=RecieveResult+Name+":ｴﾗｰ "+IntToStr(err)+"通/"+IntToStr(cnt);}
//  FrmNew->StatusBar1->SimpleText="ｴﾗｰ:"+IntToStr(err)+"通";}
 else RecieveResult=RecieveResult+Name+":Ok "+IntToStr(cnt)+"通";
 errcnt=err;
// AddLog(RecieveResult);
}

