服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

用javamail写的邮件接收程序

前段时间一直忙于学校里面的事情,没有时间静下心来写接收邮件的程序,现在学校里的事情终于忙完了,可以静下心里做自己喜欢做的事情了,这种感觉真的很好!
  对我自己而言,刚开始在用javamail来编写收邮件的程序时最重要和最难的要数解析附件和邮件正文的部分,因为mime类型实在是太多了!下面的这段代码是我自己学习javamail的一段体会,供大家来参考(请高手指教,有什么更好的办法,请回复此文章),具体代码如下:

package coffeecatwebmail;

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

public class prasemimemessage{
 private mimemessage mimemessage = null;
 private string saveattachpath = "";          //附件下载后的存放目录
 private stringbuffer bodytext = new stringbuffer();
 //存放邮件内容的stringbuffer对象
 private string dateformat = "yy-mm-dd hh:mm";    //默认的日前显示格式
    
/**
 * 构造函数,初始化一个mimemessage对象
 */

 public prasemimemessage(){}
 public prasemimemessage(mimemessage mimemessage){
  this.mimemessage = mimemessage;
  system.out.println("create a prasemimemessage object........");
 }

 public void setmimemessage(mimemessage mimemessage){
  this.mimemessage = mimemessage;
 }
  
/**
 * 获得发件人的地址和姓名
 */

 public string getfrom()throws exception{
  internetaddress address[] = (internetaddress[])mimemessage.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"---密送人地址
 */


 public string getmailaddress(string type)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 personal=address[i].getpersonal();
      if(personal==null) personal="";
      else{
       personal=mimeutility.decodetext(personal);
      }
      string compositeto=personal+"<"+email+">";
      mailaddr+=","+compositeto;
     }
     mailaddr=mailaddr.substring(1);
    }
   }else{
   throw new exception("error emailaddr type!");
   }
   return mailaddr;
  }
    
 /**
  * 获得邮件主题
  */


  public string getsubject()throws messagingexception{
   string subject = "";
   try{
    subject = mimeutility.decodetext(mimemessage.getsubject());
    if(subject == null) subject="";
   }catch(exception exce){
   }
   return subject;
  }
    
 /**
  * 获得邮件发送日期
  */


  public string getsentdate()throws exception{
    date sentdate = mimemessage.getsentdate();
    simpledateformat format = new simpledateformat(dateformat);
    return format.format(sentdate);
  }
    
 /**
  * 获得邮件正文内容
  */


  public string getbodytext(){
   return bodytext.tostring();
  }
    
 /**
  * 解析邮件,把得到的邮件内容保存到一个stringbuffer对象中,解析邮件
  * 主要是根据mimetype类型的不同执行不同的操作,一步一步的解析
  */


  public void getmailcontent(part part)throws exception{
    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 counts = multipart.getcount();
      for(int i=0;i<counts;i++){
        getmailcontent(multipart.getbodypart(i));
      }
     }else if(part.ismimetype("message/rfc822")){
      getmailcontent((part)part.getcontent());
     }else{}
    }

 /**
  * 判断此邮件是否需要回执,如果需要回执返回"true",否则返回"false"
  */

  public boolean getreplysign()throws messagingexception{
    boolean replysign = false;
    string needreply[] = mimemessage.getheader("disposition-notification-to");
    if(needreply != null){
     replysign = true;
    }
    return replysign;
  }
    
 /**
  * 获得此邮件的message-id
  */

  public string getmessageid()throws messagingexception{
   return mimemessage.getmessageid();
  }
    
 /**
  * 【判断此邮件是否已读,如果未读返回返回false,反之返回true】
  */

  public boolean isnew()throws messagingexception{
   boolean isnew = false;
   flags flags = ((message)mimemessage).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;
 }
 
/**
 * 判断此邮件是否包含附件
 */

 public boolean iscontainattach(part part)throws exception{
  boolean attachflag = false;
  string contenttype = part.getcontenttype();
  if(part.ismimetype("multipart/*")){
   multipart mp = (multipart)part.getcontent();
   for(int i=0;i<mp.getcount();i++){
    bodypart mpart = mp.getbodypart(i);
    string disposition = mpart.getdisposition();
    if((disposition != null) &&((disposition.equals(part.attachment)) ||(disposition.equals(part.inline))))
     attachflag = true;
    else if(mpart.ismimetype("multipart/*")){
     attachflag = iscontainattach((part)mpart);
    }else{
     string contype = mpart.getcontenttype();
     if(contype.tolowercase().indexof("application") != -1) attachflag=true;
     if(contype.tolowercase().indexof("name") != -1) attachflag=true;
    }
   }
  }else if(part.ismimetype("message/rfc822")){
   attachflag = iscontainattach((part)part.getcontent());
  }
  return attachflag;
 }
   
/**
 * 【保存附件】
 */


 public void saveattachment(part part)throws exception{
  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 disposition = mpart.getdisposition();
    if((disposition != null) &&((disposition.equals(part.attachment)) ||(disposition.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/*")){
 saveattachment(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")){
  saveattachment((part)part.getcontent());
}
}
    
/**
 * 【设置附件存放路径】
 */


 public void setattachpath(string attachpath){
  this.saveattachpath = attachpath;
 }
    
/**
 * 【设置日期显示格式】
 */


 public void setdateformat(string format)throws exception{
   this.dateformat = format;
 }
    
/**
 * 【获得附件存放路径】
 */


 public string getattachpath(){
   return saveattachpath;
 }
    
/**
 * 【真正的保存附件到指定目录里】
 */


 private void savefile(string filename,inputstream in)throws exception{
  string osname = system.getproperty("os.name");
  string storedir = getattachpath();
  string separator = "";
  if(osname == null) osname="";
  if(osname.tolowercase().indexof("win") != -1){
    separator = "//"
  if(storedir == null || storedir.equals("")) storedir="c://tmp";
  }else{
   separator = "/";
   storedir = "/tmp";
  }
  file storefile = new file(storedir+separator+filename);
  system.out.println("storefile's path: "+storefile.tostring());
 //for(int i=0;storefile.exists();i++){
 //storefile = new file(storedir+separator+filename+i);
 //}
 bufferedoutputstream bos = null;
 bufferedinputstream  bis = null;
 try{
  bos = new bufferedoutputstream(new fileoutputstream(storefile));
  bis = new bufferedinputstream(in);
  int c;
  while((c=bis.read()) != -1){
    bos.write(c);
    bos.flush();
  }
 }catch(exception exception){
   exception.printstacktrace();
   throw new exception("文件保存失败!");
 }finally{
   bos.close();
   bis.close();
 }
}
   
/**
 * prasemimemessage类测试
 */


 public static void main(string args[])throws exception{
  string host = "主机名/ip";     //【pop.mail.yahoo.com.cn】
  string username ="用户名";     //【wwp_1124】
  string password ="密码";       //【........】
  properties props = new properties();
  session session = session.getdefaultinstance(props, null);
  store store = session.getstore("pop3");
  store.connect(host, username, password);
  folder folder = store.getfolder("inbox");
  folder.open(folder.read_only);
  message message[] = folder.getmessages();
  system.out.println("messages's length: "+message.length);
  prasemimemessage pmm = null;
  for(int i=0;i<message.length;i++){
   pmm = new prasemimemessage((mimemessage)message[i]);
   system.out.println("message "+i+" subject: "+pmm.getsubject());
   system.out.println("message "+i+" sentdate: "+pmm.getsentdate());
   system.out.println("message "+i+" replysign: "+pmm.getreplysign());
   system.out.println("message "+i+" hasread: "+pmm.isnew());
   system.out.println("message "+i+"  containattachment: "+pmm.iscontainattach((part)message[i]));
   system.out.println("message "+i+" form: "+pmm.getfrom());
   system.out.println("message "+i+" to: "+pmm.getmailaddress("to"));
   system.out.println("message "+i+" cc: "+pmm.getmailaddress("cc"));
   system.out.println("message "+i+" bcc: "+pmm.getmailaddress("bcc"));
   pmm.setdateformat("yy年mm月dd日 hh:mm");
   system.out.println("message "+i+" sentdate: "+pmm.getsentdate());
   system.out.println("message "+i+" message-id: "+pmm.getmessageid());
   pmm.getmailcontent((part)message[i]);
   system.out.println("message "+i+" bodycontent: /r/n"+pmm.getbodytext());
   pmm.setattachpath("c://tmp//coffeecat1124");
   pmm.saveattachment((part)message[i]);
  }
 }
}

  上面就是用javamail来解析mimemessage的具体程序代码,具体使用方法参考main方法里的测试代码,请大家在看过之余多提宝贵的意见,共同学习,共同成长!!

扫描关注微信公众号