package afu.mymail;

import java.io.*;
import javax.mail.internet.*;
import javax.mail.*;
import java.util.*;

public class RecieveMail


{
public RecieveMail()

{
}

public void getMails(final String targetFolder) throws Exception

{
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("pop3");
store.connect("pop.126.com","username","password");
Folder folder = store.getFolder("INBOX");
if(folder==null)

{
System.out.println("Sorry,can not find the inbox folder");
return;
}
folder.open(Folder.READ_WRITE);
Message[] messages = folder.getMessages();
if(messages.length==0) //邮箱里没有邮件

{
System.out.println("Sorry,there are no email for you");
folder.close(true);
return;
}
System.out.println("Congratulate,you have " + messages.length + " new emails");
for(int i=0;i < messages.length;i++)

{
String mailSubject = getSubject(messages[i]);
String emailfile = targetFolder + mailSubject + ".html";
System.out.println(emailfile);

PrintWriter outFile = null;
try

{
outFile = new PrintWriter(new FileOutputStream(new File(emailfile)));
outFile.println("邮件来源:" + getSourceEmailAddress(messages[i]) + "<br>");
outFile.println(parseMailContent(messages[i]));
messages[i].setFlag(Flags.Flag.DELETED,true); //delete email on server
}
catch(Exception e)

{
System.out.println("wrote mail " + mailSubject + " failed.");
//e.printStackTrace();
}
finally

{
outFile.close();
}
}
folder.close(true);
store.close();
}


/** *//**
* get email's subject
*/
private String getSubject(final Message msg) throws MessagingException

{
String[] subjects = msg.getHeader("Subject");
if(subjects==null) return getCurrentLongTime();

/** *//**
* may be more one subjects,but they have the same content
*/
if(subjects[0]==null||subjects[0].equals(""))
return getCurrentLongTime();
String subject = decodeText(subjects[0]);
int loc = subject.indexOf(" ");
if(loc==-1)
return subject;
else

{
loc = subject.indexOf(" ",loc + 1);
return subject.substring(loc + 1);
}
}

/** *//**
* get current time
*/
private String getCurrentLongTime()

{
return String.valueOf((new java.util.Date()).getTime());
}

/** *//**
* email body is very complex,
* this method parse email body to a string
*/
private String parseMailContent(final Message msg) throws Exception

{
if(msg.getContent() instanceof String)
return (String)msg.getContent();
StringBuffer mailContent = new StringBuffer(1000);
Multipart multiPart = (Multipart)msg.getContent();
String multiPartType = multiPart.getContentType();
BodyPart bodyPart = multiPart.getBodyPart(0);
if(bodyPart.getContent() instanceof String)
mailContent.append((String)bodyPart.getContent());
else if(bodyPart.getContent() instanceof MimeMultipart)
mailContent.append(((MimeMultipart)bodyPart.getContent()).getBodyPart(0).getContent());

/** *//**
* deal with attachment
*/
if(multiPartType.startsWith("multipart/mixed"))

{
mailContent.append("<br>-----------附件:-----------<br>");
for(int c = 1;c < multiPart.getCount(); c++)

{
String fn = extractAttachmentFileName(multiPart.getBodyPart(c).getContentType());
mailContent.append(fn).append("<br>");
}
}
return mailContent.toString();
}

/** *//**
* get source email address
*/
private String getSourceEmailAddress(final Message msg) throws MessagingException

{
String address = InternetAddress.toString(msg.getFrom());
int foreindex = address.indexOf("<");
int backindex = address.indexOf(">");
if(foreindex == -1 || backindex == -1)
return address;
return address.substring(foreindex + 1,backindex);
}

/** *//**
* contentType contains attachment file name
* this method extract the file name from contentType string.
*/
private String extractAttachmentFileName(final String contentType)

{
int loc = contentType.indexOf("name=");
String fileName = contentType.substring(loc + 6,contentType.length()-1);
return decodeText(fileName);
}

private String decodeText(final String contentText)

{
String dt = null;
try

{
dt = MimeUtility.decodeText(contentText);
}
catch (UnsupportedEncodingException E)

{
dt = "";
}
return dt;
}
public static void main(String[] args)

{
try

{
RecieveMail rm = new RecieveMail();
rm.getMails("D:\\resume\\0826\\");
}
catch(Exception e)

{
e.printStackTrace();
}
}
}

自动收取email,每个email生成一个html文件。不处理附件。