package com.msss.util;
import javax.mail.*;
import java.util.*;
import java.io.*;
/**
* @author Bromon
*/
public class Receiver {
Folder inbox;
Store store;
// 连接邮件服务器,获得所有邮件的列表
public Message[] getMail(String host, String name, String password)
throws Exception {
Properties prop = new Properties();
prop.put("mail.pop3.host", host);
Session session = Session.getDefaultInstance(prop);
store = session.getStore("pop3");
store.connect(host, name, password);
inbox = store.getDefaultFolder().getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message[] msg = inbox.getMessages();
FetchProfile profile = new FetchProfile();
profile.add(FetchProfile.Item.ENVELOPE);
inbox.fetch(msg, profile);
return (msg);
}
// 处理任何一种邮件都需要的方法
private void handle(Message msg) throws Exception {
System.out.println("邮件主题:" + msg.getSubject());
System.out.println("邮件作者:" + msg.getFrom()[0].toString());
System.out.println("发送日期:" + msg.getSentDate());
}
// 处理文本邮件
public void handleText(Message msg) throws Exception {
this.handle(msg);
System.out.println("邮件内容:" + msg.getContent());
}
// 处理Multipart邮件,包括了保存附件的功能
public void handleMultipart(Message msg) throws Exception {
String disposition;
BodyPart part;
Multipart mp = (Multipart) msg.getContent();
int mpCount = mp.getCount();// Miltipart的数量,用于除了多个part,比如多个附件
for (int m = 0; m < mpCount; m++) {
this.handle(msg);
part = mp.getBodyPart(m);
disposition = part.getDisposition();
if (disposition != null && disposition.equals(Part.ATTACHMENT))// 判断是否有附件
{
// this.saveAttach(part);//这个方法负责保存附件,注释掉是因为附件可能有病毒,请清理信箱之后再取掉注释
} else {
System.out.println(part.getContent());
}
}
}
private void saveAttach(BodyPart part) throws Exception {
String temp = part.getFileName();// 得到未经处理的附件名字
String s = temp.substring(11, temp.indexOf("?=") - 1);// 去到header和footer
// 文件名一般都经过了base64编码,下面是解码
String fileName = this.base64Decoder(s);
System.out.println("有附件:" + fileName);
InputStream in = part.getInputStream();
FileOutputStream writer = new FileOutputStream(new File(fileName));
byte[] content = new byte[255];
int read = 0;
while ((read = in.read(content)) != -1) {
writer.write(content);
}
writer.close();
in.close();
}
// base64解码
private String base64Decoder(String s) throws Exception {
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
byte[] b = decoder.decodeBuffer(s);
return (new String(b));
}
// 关闭连接
public void close() throws Exception {
if (inbox != null) {
inbox.close(false);
}
if (store != null) {
store.close();
}
}
public static void main(String args[]) {
String host = "pop.126.com";
String name = "bingling8421";
String password = "bbb888888";
Receiver receiver = new Receiver();
try {
Message[] msg = receiver.getMail(host, name, password);
for (int i = 0; i < msg.length; i++) {
if (msg[i].isMimeType("text/*"))// 判断邮件类型
{
receiver.handleText(msg[i]);
} else {
receiver.handleMultipart(msg[i]);
}
}
receiver.close();
} catch (Exception e) {
System.out.println(e);
}
}
}