java Mail邮件接收工具类_java

下面是一个邮件接收的工具类,有点长!!!

public class ReciveMail {
 private MimeMessage msg = null;
  private String saveAttchPath = "";
  private StringBuffer bodytext = new StringBuffer();
  private String dateformate = "yy-MM-dd HH:mm"; 

  public ReciveMail(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 = 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; 

    //String contentType = part.getContentType();
    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) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }finally{
      bos.close();
      bis.close();
    } 

  } 

  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());
    setSaveAttchPath("c://temp//"+i);
    if(flag){
      saveAttchMent(part);
    }
    System.out.println("------------------END-----------------------");
  }

}

邮件接收与工具类的使用,有好几种邮件接收的写法!:

看了很多网上其他代码,pop3Server的值是pop.mail.163.com,但是试了试不成功,还有 user的值既可以是带有 username@...com也可以是username。

如果收件邮箱是163邮箱,必须先登陆163邮箱中设置,开启pop3服务。至于别的邮箱暂不知道。

public static void main(String[] args) throws Exception {
    // 连接pop3服务器的主机名、协议、用户名、密码
    String pop3Server = "pop.163.com";
    String protocol = "pop3";
    String user = "username";
    String pwd = "password"; 

    // 创建一个有具体连接信息的Properties对象
    Properties props = new Properties();
    props.setProperty("mail.store.protocol", protocol);
    props.setProperty("mail.pop3.host", pop3Server); 

    // 使用Properties对象获得Session对象
    Session session = Session.getInstance(props);
    session.setDebug(true); 

    // 利用Session对象获得Store对象,并连接pop3服务器
    Store store = session.getStore();
    store.connect(pop3Server, user, pwd); 

    // 获得邮箱内的邮件夹Folder对象,以"只读"打开
    Folder folder = store.getFolder("inbox");
    folder.open(Folder.READ_ONLY); 

    // 获得邮件夹Folder内的所有邮件Message对象
    Message [] messages = folder.getMessages();
    ReciveMail rm = null;
    for(int i=0;i< messages.size() ;i++){
      rm = new ReciveMail((MimeMessage) messages[i]);
      rm.recive(messages[i],i);;
    }
     folder.close(false);
    store.close();
}

以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索java
, 邮件
, mail
, 接收
工具类
javamail接收邮件、javamail接收qq邮件、javamail工具类、java发送邮件工具类、java邮件工具类utils,以便于您获取更多的相关知识。

时间: 2024-07-28 12:26:40

java Mail邮件接收工具类_java的相关文章

Java基础之java处理ip的工具类_java

java处理ip的工具类,包括把long类型的Ip转为一般Ip类型.把xx.xx.xx.xx类型的转为long类型.根据掩码位获取掩码.根据 ip/掩码位 计算IP段的起始IP.根据 ip/掩码位 计算IP段的终止IP等方法,可以直接使用! 复制代码 代码如下: package com.hh.test; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang3.StringUtils; /**

java实现的正则工具类_java

本文实例讲述了java实现的正则工具类.分享给大家供大家参考.具体如下: 这里实现的正则工具类适用于:正则电话号码.邮箱.QQ号码.QQ密码.手机号 java代码如下: package com.zhanggeng.contact.tools; /** * RegexTool is used to regex the string ,such as : phone , qq , password , email . * * @author ZHANGGeng * @version v1.0.1 *

5种java排序算法汇总工具类_java

工具类简单明了地总结了java的快速排序,希尔排序,插入排序,堆排序,归并排序五种排序算法,代码中并没有对这几种排序算法的一个说明,关于思想部分希望在自行查阅相关说明,这里只是对这几种算法进行一个概括,以供大家使用. public class Sort { public static <AnyType extends Comparable<? super AnyType>> void insertionSort(AnyType[] a) { insertionSort(a, 0,

redis-求 java Redis 连接池 工具类

问题描述 求 java Redis 连接池 工具类 谁有我一个 java Redis 连接池的工具类, 最好附上一些真删改查的小例子 解决方案 http://www.open-open.com/code/view/1430406110599 解决方案二: 最著名的就是jedis了 解决方案三: jedis自带连接池 JedisPoolConfig config = new JedisPoolConfig(); //控制一个pool可分配多少个jedis实例,通过pool.getResource(

java用ant.jar工具类执行sql脚本遇到问题

问题描述 java用ant.jar工具类执行sql脚本遇到问题 最近在研究用工具类ant.jar执行sql脚本文件,一般对数据和字段的操作都无问题,但当要执行生成触发器或者存储过程时却出错,有大神做过这方面的吗?或者用其他方法可以执行能生成存储过程和触发器的sql脚本?求解!新人无币,望见谅~ Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an

java连接Mysql数据库的工具类_java

一个封装好的链接Mysql数据库的工具类,可以方便的获取Connection对象关闭Statement.ResultSet.Statment对象等等 复制代码 代码如下: package myUtil; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLExceptio

java正则表达式验证工具类_java

分享一个用正则表达式校验电话号码.身份证号.日期格式.URL.Email等等格式的工具类 复制代码 代码如下: package com.eabax.util; import java.util.regex.Matcher;  import java.util.regex.Pattern;  /**  * 验证工具类  * @author admin  *  */ public class Validation {      //------------------常量定义      /**   

Java 随机取字符串的工具类_java

一.Java随机数的产生方式 在Java中,随机数的概念从广义上将,有三种. 1.通过System.currentTimeMillis()来获取一个当前时间毫秒数的long型数字. 2.通过Math.random()返回一个0到1之间的double值. 3.通过Random类来产生一个随机数,这个是专业的Random工具类,功能强大. 二.Random类API说明 1.Java API说明 Random类的实例用于生成伪随机数流.此类使用 48 位的种子,使用线性同余公式对其进行修改(请参阅 D

java实现excel导入数据的工具类_java

导入Excel数据的工具类,调用也就几行代码,很简单的. 复制代码 代码如下: import jxl.Cell;import jxl.Sheet;import jxl.Workbook;import jxl.read.biff.BiffException;import org.apache.commons.beanutils.BeanUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory; import java.io.IOExc