Chinaunix首页 | 论坛 | 博客
  • 博客访问: 100555
  • 博文数量: 19
  • 博客积分: 1550
  • 博客等级: 上尉
  • 技术积分: 246
  • 用 户 组: 普通用户
  • 注册时间: 2009-09-15 19:50
文章分类

全部博文(19)

文章存档

2013年(1)

2012年(4)

2010年(8)

2009年(6)

我的朋友

分类: Java

2012-07-14 15:36:12

//最终版?设置线程数为10,从栈里面取当前邮件序号,由多个线程共享


//多线程里用Message看来不行,Message可能上了锁
// 只好建立三个连接

import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.Message;
import javax.mail.Flags.Flag;
import javax.mail.internet.*;
import javax.mail.search.*;
import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPMessage;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.PrintWriter;
import java.io.FileWriter;
import java.io.IOException;

class myStack{
int len;
int cur;
myStack(int len) {
this.len = len;
cur = 0;
}
synchronized int pop() {
if(cur>= len)
return -1;
return cur++;
}
};

class Savemail implements Runnable {
public String username;
public String password;
public StringBuffer filename = null;
public StringBuffer head = null;
public StringBuffer body = null;
public StringBuffer attachment = null;
public String path = null;
public String date = null;
IMAPFolder folder = null;
Store store = null;
Flag flag = null;
static myStack stack = null;
final String[] versions = { "", "1.0", "1.1", "1.2", "1.3", "1.4",
"1.5" };
public Savemail() {}
public boolean fileExist(String path, String filename) {
File textFile, attachFile;
for (String ver : versions) {
attachFile = new File(path + "/" + ver + "/" + filename
+ ".attach.txt");
textFile = new File(path + "/" + ver + "/" + filename + ".text.txt");
if (attachFile.exists() || textFile.exists()) {
return true;
}
}
return false;
}
public void init() {
// init...
try {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getDefaultInstance(props, null);
store = session.getStore("imaps");
store.connect("imap.googlemail.com", username, password);
folder = (IMAPFolder) store.getFolder("inbox");
if (!folder.isOpen())
folder.open(Folder.READ_ONLY);
} catch (Exception e) {
e.printStackTrace();
return;
}
}
public Savemail(String username, String password, String date, String path) {
this.username = username;
this.date = date;
this.path = path;
this.password = password;
}

public String ripHtml(String html) {
StringBuffer sb = new StringBuffer();
String tag = "";
int a = 0, s = 1, t = 1;
while (s >= 0) {
s = html.indexOf("<", a);
t = html.indexOf(">", s);
if (s < 0 || t < 0) {
if (a < html.length())
sb.append(html.substring(a, html.length()));
break;
}
tag = html.substring(s + 1, t);
sb.append(html.substring(a, s));
if (tag.indexOf("br") != -1) {
sb.append("\n");
}
a = t + 1;
}
return sb.toString();
}

public boolean isAttachment(Part part) {
try {
String contenttype = part.getContentType();
String disposition = part.getDisposition();
String filename = part.getFileName();

contenttype = contenttype == null ? "" : contenttype.toLowerCase();
disposition = disposition == null ? "" : disposition.toLowerCase();
filename = filename == null ? "" : filename.toLowerCase();

if (contenttype.indexOf("name") != -1
|| ((disposition.indexOf("attachment") != -1) && (filename
.length() > 0)))
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}

public void getMailContent(Part part, StringBuffer bodytext,
StringBuffer attachment) throws Exception {
boolean conname = isAttachment(part);

if ((part.isMimeType("text/plain")) && !conname) {
if (bodytext.length() > 0)
bodytext.delete(0, bodytext.length());
bodytext.append((String) part.getContent());
} else if (part.isMimeType("text/html") && !conname) {
if (bodytext.length() == 0)
bodytext.append(ripHtml((String) part.getContent()));
} else if (part.isMimeType("multipart/*")) {
Multipart multipart = (Multipart) part.getContent();
int counts = multipart.getCount();
for (int i = 0; i < counts; i++) {
getMailContent(multipart.getBodyPart(i), bodytext, attachment);
}
} else if (part.isMimeType("message/rfc822")) {
getMailContent((Part) part.getContent(), bodytext, attachment);
} else if (conname && part.isMimeType("text/plain")) {
String contentType = part.getContentType();
String charset = "";
Pattern p = Pattern.compile("charset=([0-9a-zA-Z]*);");
Matcher m = p.matcher(contentType);
if (m.find()) {
charset = m.group(1);
}

if (charset.equalsIgnoreCase("cp932")) {
InputStream is = part.getInputStream();
// filename
char[] temp = new char[1000];
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));

int status = reader.read(temp);
while (status != -1) {
attachment.append(temp);
status = reader.read(temp);
}

} else
attachment.append((String) part.getContent());
}
}

private Date getSearchDate(String date) {
String[] ymd = date.split("-");
int year, month, day;
Date srchdate = null;
try {
year = Integer.parseInt(ymd[0]);
month = Integer.parseInt(ymd[1]) - 1;
day = Integer.parseInt(ymd[2]);
Calendar cal = Calendar.getInstance();
cal.set(year, month, day);
srchdate = cal.getTime();
} catch (Exception ex) {
ex.printStackTrace();
}
return srchdate;
}

public Message[] getMsgAfterDate(String date) {
try {
SearchTerm st = new SentDateTerm(SentDateTerm.GT,
getSearchDate(date));
return folder.search(st);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String getVersionName(String body) {
Pattern p = Pattern.compile("VersionName=([0-9\\.]*)");
Matcher m = p.matcher(body);
if (m.find()) {
return m.group(1);
}
return new String("");
}

public void writeToFile(StringBuffer filename, StringBuffer body,
StringBuffer attach, String path) throws Exception {
String versionName = getVersionName(body.toString());

PrintWriter pw1 = null;
PrintWriter pw2 = null;
try {
File file = new File(path + "/" + versionName);
file.mkdirs();

pw1 = new PrintWriter(new FileWriter(path + "/" + versionName + "/"
+ filename.toString() + ".attach.txt"));
pw2 = new PrintWriter(new FileWriter(path + "/" + versionName + "/"
+ filename.toString() + ".text.txt"));

pw1.println(attach.toString());
pw2.println(body.toString());
} catch (IOException e) {
throw e;
} finally {
if (pw1 != null)
pw1.close();
if (pw2 != null)
pw2.close();
}
}

public void run() {
init();
try{
Message[] messages = getMsgAfterDate(date);

synchronized(this){
if(stack==null) {
stack=new myStack(messages.length);
}
}
int i=-1;
while((i=stack.pop())!=-1) {
Message msg = messages[i];
int number = msg.getMessageNumber();
System.out.println("# Message: "+(i+1)+"/"+stack.len+" , "+number);
head = new StringBuffer();
filename = new StringBuffer();
body = new StringBuffer();
attachment = new StringBuffer();
Date d = msg.getReceivedDate();
filename.append("" + (d.getMonth() + 1) + "-" + d.getDate()
+ "-");
filename.append(number);
if (fileExist(path, filename.toString())) {
System.out.println("warning[ "+(i+1) + " already exist! ]");
continue;
}
head.append("Subject: " + msg.getSubject());
head.append("\nFrom: " + msg.getFrom()[0]);
head.append("\nTo: " + msg.getAllRecipients()[0]);
head.append("\nDate: " + msg.getReceivedDate());
   
try {
getMailContent(msg, body, attachment);
   writeToFile(filename, head.append(body), attachment, path);
} catch (Exception e) {
e.printStackTrace();
continue;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try{
if (folder != null && folder.isOpen()) {
folder.close(true);
}
if (store != null) {
store.close();
}
}catch(Exception e){}
}
}
}

public class FetchMailM {
static final int threadNumber = 10;
private void fetchMail(String username, String password, String date,
String path) throws MessagingException, IOException {
try {
for(int t = 0; t
Savemail h = new Savemail(username, password, date, path);
Thread th = new Thread(h);
th.start();
}

} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String[] args) throws MessagingException,
IOException {
long s = System.currentTimeMillis();
FetchMailM mail = new FetchMailM();
if (args.length >= 3) {
String path = "";
if (args.length == 4)
path = args[3];
mail.fetchMail(args[0], args[1], args[2], path);
}

while(Thread.activeCount()>1)
;
long t = System.currentTimeMillis();
System.out.println(t-s);
}
}


阅读(2506) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~