JavaMail接收指定账号邮件

JavaMail接收指定邮箱账号的邮件

/**
*
*
@author archie
* 接收指定账号的邮件
*/
public class ReceiveMail {

/**
* Message实现了Part接口,它表示一个邮件消息,包含一系列的属性和一个消息内容。
* 消息属性包括了消息址址消息,定义了消息内容的结构(包括内容类型),
* 消息内容使用DataHandler对象包装实际数据。当邮件消息位于目录(folder)中时,
* 系统还使用了一个标志位集合来描述它的状态。
*/
private MimeMessage msg = null;

private String saveAttchPath = "";//保存附件路径
private StringBuffer bodytext = new StringBuffer();//邮件内容
private String dateformate = "yy-MM-dd HH:mm";//日期格式化

public ReceiveMail(MimeMessage msg){
this.msg = msg;
}
public void setMsg(MimeMessage msg) {
this.msg = msg;
}

/**
* 获取发送邮件者信息
*
@return
*
@throws MessagingException
*/
public String getFrom() throws MessagingException{
InternetAddress[] address
= (InternetAddress[]) msg.getFrom();
String from
= address[0].getAddress();
if(from == null){
from
= "";
}
String personal
= address[0].getPersonal();
if(personal == null){
personal
= "";
}
String fromaddr
= personal +"<"+from+">";
return fromaddr;
}

/**
* 获取邮件收件人,抄送,密送的地址和信息。根据所传递的参数不同
* "to"-->收件人,"cc"-->抄送人地址,"bcc"-->密送地址
*
@param type
*
@return
*
@throws MessagingException
*
@throws UnsupportedEncodingException
*/
public String getMailAddress(String type) throws MessagingException, UnsupportedEncodingException{
String mailaddr
= "";
String addrType
= type.toUpperCase();
InternetAddress[] address
= null;

if(addrType.equals("TO")||addrType.equals("CC")||addrType.equals("BCC")){
if(addrType.equals("TO")){
address
= (InternetAddress[]) msg.getRecipients(Message.RecipientType.TO);
}
if(addrType.equals("CC")){
address
= (InternetAddress[]) msg.getRecipients(Message.RecipientType.CC);
}
if(addrType.equals("BCC")){
address
= (InternetAddress[]) msg.getRecipients(Message.RecipientType.BCC);
}

if(address != null){
for(int i=0;i<address.length;i++){
String mail
= address[i].getAddress();
if(mail == null){
mail
= "";
}
else{
mail
= MimeUtility.decodeText(mail);
}
String personal
= address[i].getPersonal();
if(personal == null){
personal
= "";
}
else{
personal
= MimeUtility.decodeText(personal);
}
String compositeto
= personal +"<"+mail+">";
mailaddr
+= ","+compositeto;
}
mailaddr
= mailaddr.substring(1);
}
}
else{
throw new RuntimeException("Error email Type!");
}
return mailaddr;
}

/**
* 获取邮件主题
*
@return
*
@throws UnsupportedEncodingException
*
@throws MessagingException
*/
public String getSubject() throws UnsupportedEncodingException, MessagingException{
String subject
= "";
/**
* 指定subject编码为javamail方式编码
* 编码内容的字符集是系统字符集
*/
subject
= MimeUtility.decodeText(msg.getSubject());
if(subject == null){
subject
= "";
}
return subject;
}

/**
* 获取邮件发送日期
*
@return
*
@throws MessagingException
*/
public String getSendDate() throws MessagingException{
Date sendDate
= msg.getSentDate();//邮件发送日期
SimpleDateFormat smd = new SimpleDateFormat(dateformate);
return smd.format(sendDate);
}

/**
* 获取邮件正文内容
*
@return
*/
public String getBodyText(){

return bodytext.toString();
}

/**
* 解析邮件,将得到的邮件内容保存到一个stringBuffer对象中,解析邮件 主要根据MimeType的不同执行不同的操作,一步一步的解析
*
@param part
*
@throws MessagingException
*
@throws IOException
*/
public void getMailContent(Part part) throws MessagingException, IOException{

String contentType
= part.getContentType();
int nameindex = contentType.indexOf("name");
boolean conname = false;
if(nameindex != -1){
conname
= true;
}
System.out.println(
"CONTENTTYPE:"+contentType);
if(part.isMimeType("text/plain")&&!conname){
bodytext.append((String)part.getContent());
}
else if(part.isMimeType("text/html")&&!conname){
bodytext.append((String)part.getContent());
}
else if(part.isMimeType("multipart/*")){
Multipart multipart
= (Multipart) part.getContent();
int count = multipart.getCount();
for(int i=0;i<count;i++){
getMailContent(multipart.getBodyPart(i));
}
}
else if(part.isMimeType("message/rfc822")){
getMailContent((Part) part.getContent());
}

}

/**
* 判断邮件是否需要回执,如需回执返回true,否则返回false
*
@return
*
@throws MessagingException
*/
public boolean getReplySign() throws MessagingException{
boolean replySign = false;
String needreply[]
= msg.getHeader("Disposition-Notification-TO");//回执
if(needreply != null){
replySign
= true;
}
return replySign;
}

/**
* 获取此邮件的message-id
*
@return
*
@throws MessagingException
*/
public String getMessageId() throws MessagingException{
return msg.getMessageID();
}

/**
* 判断此邮件是否已读,如果未读则返回false,已读返回true
*
@return
*
@throws MessagingException
*/
public boolean isNew() throws MessagingException{
boolean isnew = false;
Flags flags
= ((Message)msg).getFlags();
Flags.Flag[] flag
= flags.getSystemFlags();
System.out.println(
"flags''s length:"+flag.length);
for(int i=0;i<flag.length;i++){
if(flag[i]==Flags.Flag.SEEN){
isnew
= true;
System.out.println(
"seen message .......");
break;
}
}

return isnew;
}

/**
* 判断是是否包含附件
*
@param part
*
@return
*
@throws MessagingException
*
@throws IOException
*/
public boolean isContainAttch(Part part) throws MessagingException, IOException{
boolean flag = false;

if(part.isMimeType("multipart/*")){
Multipart multipart
= (Multipart) part.getContent();
int count = multipart.getCount();
for(int i=0;i<count;i++){
BodyPart bodypart
= multipart.getBodyPart(i);
String dispostion
= bodypart.getDisposition();
if((dispostion != null)&&(dispostion.equals(Part.ATTACHMENT)||dispostion.equals(Part.INLINE))){
flag
= true;
}
else if(bodypart.isMimeType("multipart/*")){
flag
= isContainAttch(bodypart);
}
else{
String conType
= bodypart.getContentType();
if(conType.toLowerCase().indexOf("appliaction")!=-1){
flag
= true;
}
if(conType.toLowerCase().indexOf("name")!=-1){
flag
= true;
}
}
}
}
else if(part.isMimeType("message/rfc822")){
flag
= isContainAttch((Part) part.getContent());
}

return flag;
}

/**
* 保存附件
*
@param part
*
@throws MessagingException
*
@throws IOException
*/
public void saveAttchMent(Part part) throws MessagingException, IOException{
String filename
= "";
if(part.isMimeType("multipart/*")){
Multipart mp
= (Multipart) part.getContent();
for(int i=0;i<mp.getCount();i++){
BodyPart mpart
= mp.getBodyPart(i);
String dispostion
= mpart.getDisposition();
if((dispostion != null)&&(dispostion.equals(Part.ATTACHMENT)||dispostion.equals(Part.INLINE))){
filename
= mpart.getFileName();
if(filename.toLowerCase().indexOf("gb2312")!=-1){
filename
= MimeUtility.decodeText(filename);
}
saveFile(filename,mpart.getInputStream());
}
else if(mpart.isMimeType("multipart/*")){
saveAttchMent(mpart);
}
else{
filename
= mpart.getFileName();
if(filename != null&&(filename.toLowerCase().indexOf("gb2312")!=-1)){
filename
= MimeUtility.decodeText(filename);
}
saveFile(filename,mpart.getInputStream());
}
}

}
else if(part.isMimeType("message/rfc822")){
saveAttchMent((Part) part.getContent());
}
}
/**
* 获得保存附件的地址
*
@return
*/
public String getSaveAttchPath() {
return saveAttchPath;
}
/**
* 设置保存附件地址
*
@param saveAttchPath
*/
public void setSaveAttchPath(String saveAttchPath) {
this.saveAttchPath = saveAttchPath;
}
/**
* 设置日期格式
*
@param dateformate
*/
public void setDateformate(String dateformate) {
this.dateformate = dateformate;
}
/**
* 保存文件内容
*
@param filename
*
@param inputStream
*
@throws IOException
*/
private void saveFile(String filename, InputStream inputStream) throws IOException {
String osname
= System.getProperty("os.name");
String storedir
= getSaveAttchPath();
String sepatror
= "";
if(osname == null){
osname
= "";
}

if(osname.toLowerCase().indexOf("win")!=-1){
sepatror
= "//";
if(storedir==null||"".equals(storedir)){
storedir
= "d://temp";
}
}
else{
sepatror
= "/";
storedir
= "/temp";
}

File storefile
= new File(storedir+sepatror+filename);
System.out.println(
"storefile''s path:"+storefile.toString());

BufferedOutputStream bos
= null;
BufferedInputStream bis
= null;

try {
bos
= new BufferedOutputStream(new FileOutputStream(storefile));
bis
= new BufferedInputStream(inputStream);
int c;
while((c= bis.read())!=-1){
bos.write(c);
bos.flush();
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally{
bos.close();
bis.close();
}

}
/**
* 接收邮件
*
@param part
*
@param i
*
@throws MessagingException
*
@throws IOException
*/
public void recive(Part part,int i) throws MessagingException, IOException{
System.out.println(
"------------------START-----------------------");
System.out.println(
"Message"+i+" 主题subject:" + getSubject());
System.out.println(
"Message"+i+" 发件人from:" + getFrom());
System.out.println(
"Message"+i+" 是否阅读isNew:" + isNew());
boolean flag = isContainAttch(part);
System.out.println(
"Message"+i+" 是否包含附件isContainAttch:" +flag);
System.out.println(
"Message"+i+" 是否需要回执replySign:" + getReplySign());
getMailContent(part);
System.out.println(
"Message"+i+" 邮件内容content:" + getBodyText());


//附件目录不存在则创建该目录
try {
if (!(new File("f://temp//"+i).isDirectory())) {
new File("f://temp//"+i).mkdir();
}
}
catch (SecurityException e) {
//e.printStackTrace();
}
//设置保存附件路径
setSaveAttchPath("f://temp//"+i);

if(flag){
saveAttchMent(part);
}
System.out.println(
"------------------END-----------------------"+i);
}


/**
* 测试主方法
*
@param args
*
@throws MessagingException
*
@throws IOException
*/
public static void main(String[] args) throws MessagingException, IOException {

/**
* 初始化服务器环境
* session类定义了与远程邮件系统通信的邮件会话
* 它只是用于存储与服务器建立连接会话相关信息和逻辑。
*/
Properties props
= new Properties();
props.setProperty(
"mail.smtp.host", "smtp.163.com");
props.setProperty(
"mail.smtp.auth", "true");
Session session
= Session.getDefaultInstance(props,null);
/**
* 第1个参数为接受协议,第2个参数为邮件接收服务器的地址,
* 第三个参数为pop3协议的端口,最后两个为用户名和密码
*/
URLName urlname
= new URLName("pop3","pop.163.com",110,null,"zhangjie7275019@163.com*******","13938");

/**
* java.mail.Store 该类实际特定邮件协议上的读,写,监视,查找等操作
*/
Store store
= session.getStore(urlname);
store.connect();
//连接邮件服务器
Folder folder = store.getFolder("INBOX");//收件箱
folder.open(Folder.READ_ONLY);//以只读方式打开收件箱
Message msgs[] = folder.getMessages();//得到文件夹信息,获取邮件列表
int count = msgs.length;
System.out.println(
"Message Count:"+count);
ReceiveMail rm
= null;

System.out.println(
"该账号邮件数目:"+count);

for(int i=0;i<count;i++){
rm
= new ReceiveMail((MimeMessage) msgs[i]);
rm.recive(msgs[i],i);;
System.out.println(
"=============================邮件分隔线========================");
}
// 释放资源
try {
if (folder != null)
folder.close(
false);
if (store != null)
store.close();
}
catch (Exception ex) {
ex.printStackTrace();
}

}

}

posted on 2011-07-05 12:34  archie2010  阅读(976)  评论(0编辑  收藏  举报