package email_;

im
port java.io.BufferedReader;
im
port java.io.BufferedWriter;
im
port java.io.ByteArrayOutputStream;
im
port java.io.File;
im
port java.io.FileWriter;
im
port java.io.IOException;
im
port java.io.InputStreamReader;
im
port java.io.Reader;
im
port java.io.StringReader;
im
port java.io.UnsupportedEncodingException;
im
port java.util.Date;
im
port javax.mail.BodyPart;
im
port javax.mail.Flags;
im
port javax.mail.Folder;
im
port javax.mail.Message;
im
port javax.mail.MessagingException;
im
port javax.mail.Multipart;
im
port javax.mail.NoSuchProviderException;
im
port javax.mail.Part;
im
port javax.mail.Session;
im
port javax.mail.Store;
im
port javax.mail.internet.InternetAddress;
im
port javax.mail.internet.MimeMessage;
im
port javax.mail.internet.MimeUtility;
public class MailReceiver {
//收邮件的参数配置
private MailReceiverInfo receiverInfo ;
//与邮件服务器连接后得到的邮箱
private Store store;
//收件箱
private Folder folder;
//收件箱中的邮件信息
private Message[] messages;
//当前正在处理的邮件信息
private Message currentMessage;
private String currentEmailFileName;
public MailReceiver(MailReceiverInfo receiverInfo){
this.receiverInfo = receiverInfo;
}
public void receiveAllMail()throws Exception{
if(this.receiverInfo == null){
throw new Exception("必须提供接收邮件的参数");
}
//链接到服务器
if(this.co
nnectToServer()){
//
if(this.openInBoxFolder()){
//获取邮件
this.getAllMail();
this.closeCo
nnection();
}else{
throw new Exception("收件箱打开失败");
}
}else{
throw new Exception("邮箱链接失败");
}
}
//登录邮件服务器
private boolean co
nnectToServer() {
//判断是否需要身份认证
MyAuthenticator authenticator = null;
if(this.receiverInfo.isValidate()){
//需要身份认证,创建一个密码验证器
authenticator= new MyAuthenticator(
this.receiverInfo.getUserName(), this.receiverInfo.getPasswor
d());
}
//创建session
Session session = Session.getInstance(this.receiverInfo.getProperties(),authenticator);
//创建store,建立连接
try {
this.store = session.getStore(this.receiverInfo.getProtocal());
} catch (NoSuchProviderException e) {
// TODO Auto-generated catch block
System.out.println("连接服务器失败");
return false;
}
System.out.println("连接中...");
try {
this.store.co
nnect();
} catch (MessagingException e) {
System.out.println("连接服务器失败");
return false;
}
System.out.println("连接服务器成功");
return true;
}
//打开收件箱
private boolean openInBoxFolder() {
try {
this.folder = store.getFolder("INBOX");
//reado
nly
folder.open(Folder.READ_ONLY);
return true ;
} catch (MessagingException e) {
// TODO Auto-generated catch block
System.out.println("打开收件箱失败");
}
return false;
}
//断开与邮件服务器的链接
private boolean closeCo
nnection() {
try {
if(this.folder.isOpen()){
this.folder.close(true);
}
this.store.close();
System.out.println("成功关闭与服务器的链接");
return true;
} catch (MessagingException e) {
System.out.println("关闭与服务器的链接出错");
}
return false;
}
//获取所有邮件
private void getAllMail() throws MessagingException{
this.messages = this.folder.getMessages();
System.out.println("总的邮件数目:"+messages.length);
System.out.println("新邮件数目:"+this.getNewMessageCount());
System.out.println("未读邮件数目:"+this.getUnreadMessageCount());
//将要下载的邮件的数量。
int mailArrayLength = this.getMessageCount();
System.out.println("一共有邮件" + mailArrayLength + "封");
int errorCounter = 0; //邮件下载出错计数器
int successCounter = 0;
for (int index = 0; index < mailArrayLength; index++) {
try {
this.currentMessage = (messages[index]); //设置当前message
System.out.println("正在获取第" + index + "封邮件");
this.showMailBasicInfo();
getMail(); //获取当前message
System.out.println("成功获取第" + index + "封邮件");
successCounter++;
} catch (Throwable e) {
errorCounter++;
System.err.println("下载第" + index + "封邮件时出错");
}
}
System.out.println("------------------");
System.out.println("成功下载了" + successCounter + "封邮件");
System.out.println("失败下载了" + errorCounter + "封邮件");
System.out.println("------------------");
}
private void showMailBasicInfo() throws Exception{
showMailBasicInfo(this.currentMessage);
}
private void showMailBasicInfo(Message message) throws Exception {
System.out.println("-------- 邮件ID:" + this.getMessageId() + " ---------");
System.out.println("From:" + this.getFrom());
System.out.println("To:" + this.getTOAddress());
System.out.println("CC:" + this.getCCAddress());
System.out.println("BCC:" + this.getBCCAddress());
System.out.println("Subject:" + this.getSubject());
System.out.println("发送时间::" + this.getSentDate());
System.out.println("是新邮件?" + this.isNew());
System.out.println("要求回执?" + this.getReplySign());
System.out.println("包含附件?" + this.isCo
ntainAttach());
System.out.println("------------------------------");
}
private String getTOAddress() throws Exception {
return getMailAddress("TO", this.currentMessage);
}
private String getCCAddress() throws Exception {
return getMailAddress("CC", this.currentMessage);
}
private String getBCCAddress() throws Exception {
return getMailAddress("BCC", this.currentMessage);
}
private String getMailAddress(String type, Message mimeMessage)
throws Exception {
String mailaddr = "";
String addtype = type.toUpperCase();
InternetAddress[] address = null;
if (addtype.equals("TO") || addtype.equals("CC")
|| addtype.equals("BCC")) {
if (addtype.equals("TO")) {
address = (InternetAddress[]) mimeMessage
.getRecipients(Message.RecipientType.TO);
} else if (addtype.equals("CC")) {
address = (InternetAddress[]) mimeMessage
.getRecipients(Message.RecipientType.CC);
} else {
address = (InternetAddress[]) mimeMessage
.getRecipients(Message.RecipientType.BCC);
}
if (address != null) {
for (int i = 0; i < address.length; i++) {
// 先获取邮件地址
String email = address[i].getAddress();
if (email == null){
email = "";
}else {
email = MimeUtility.decodeText(email);
}
// 再取得个人描述信息
String perso
nal = address[i].getPerso
nal();
if (perso
nal == null){
perso
nal = "";