import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import javax.activation.*;
import java.io.*;
public class getmailbean
{
private String host;
private String protocol;
private int count;
private int per;
private Message[] allmails;
private Message[] mails;

public getmailbean()
{
this.init();
}
public void init()
{
Properties p=readprop.getInitprop();
host=p.getProperty("Mailhost");
protocol=p.getProperty("protocol");
per=(new Integer(p.getProperty("perpage"))).intValue();
mails=null;
allmails=null;
count=0;
}
public void connect(String user,String password,String folder)
{
Properties p=new Properties();
javax.mail.Authenticator a=null;
try {
Session s=Session.getDefaultInstance(p,a);
Store store=s.getStore(protocol);
store.connect(host,user,password);
Folder box=store.getFolder(folder);
box.open(Folder.READ_WRITE);
allmails=box.getMessages();
this.sortmail(allmails);
count=allmails.length;
  }
  catch (Exception e) {
  System.out.println (e);
  }
}
private void sortmail(Message[] a)
{
Message temp;
for (int i=0;i<(a.length/2);i++) 
{
temp=a[a.length-i-1];
a[a.length-i-1]=a[i];
a[i]=temp;
}
}
public int getmailcount()
{
return count;
}
public int getpagenum()
{
int p;
if ((count/per)>0) {
if ((count%per)>0) {
p=count/per+1;
}
else p=count/per;
}
else p=1;
return p;
}
public Message[] getMails(int page)
{
int p=(page-1)*per;
if (count<(page*per)) {
int j=count-p;
mails=new Message[j];
System.arraycopy(allmails,p,mails,0,j);
return mails;
}
else {
mails=new Message[per];
System.arraycopy(allmails,p,mails,0,per);
return mails;
}
}
public String getmailfrom(int i)
{
String s=null;
try {
 s=mails[i].getFrom()[0].toString();
    }
    catch (Exception ex) {
     s="未知地址";
    }
return s;
}
public String getmailsubject(int i)
{
String s=null;
try {
 s=mails[i].getSubject();
    }
    catch (Exception ex) {
     s="未知主题";
    }
return s;
}
public String getmailcontext(int i)
{
String s=null;
try {
 s=mails[i].getContent().toString();
    }
    catch (Exception ex) {
     s="读取失败";
    }
return s;
}
public String getmaildate(int i)
{
String s=null;
Date trialTime=null;
Calendar calendar = Calendar.getInstance();
try {
 trialTime = mails[i].getSentDate();
 calendar.setTime(trialTime);
 s=calendar.get(Calendar.YEAR)+"年"+(calendar.get(Calendar.MONTH)+1)+"月"+calendar.get(Calendar.DAY_OF_MONTH)+"日 "+calendar.get(Calendar.HOUR_OF_DAY)+":"+calendar.get(Calendar.SECOND);
    }
    catch (Exception ex) {
     s="未知日期";
    }
return s;
}
}