用Javamail写的邮件接收程序

来源:互联网 发布:王者和lol的区别 知乎 编辑:程序博客网 时间:2024/05/16 02:00

       最近在修改一个项目,里面用到了javamail,可是在学校的时候这一块根本没仔细听,现在终于苦恼了。在网上搜索这一块的相关资料,可是发现这方面的资料都零零散散,于是集大家所长,把代码汇总到一起,呵呵。

       由于发送邮件一块蛮简单,就没贴上来,接收邮件这一块倒是有点复杂,就贴了上来,望大家指点.

 

package util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

/**
 * 邮件解析类
 * @author Administrator
 *
 */
@SuppressWarnings("all")
public class ParseMimeMessage {
 //邮件消息对象
 private MimeMessage msg;
 //附件保存路径
 private String attachmentSavePath = "d:/temp";
 //邮件内容
 private StringBuffer bodyText = new StringBuffer();
 //默认的日期显示格式
 private String defaultDateFormatString = "yyyy-MM-dd HH:mm:ss";
 //默认构造函数
 public ParseMimeMessage(){}
 public void setMsg(MimeMessage msg)
 {
  this.msg = msg;
 }
 //重载的构造函数
 public ParseMimeMessage(MimeMessage msg)
 {
  this.msg = msg;
 } 
 /**
  * 获得邮件发件人的地址和姓名
  * @return
  */
 public String getFrom()
 {
  StringBuffer address = new StringBuffer();
  try {
   InternetAddress[] addresses = (InternetAddress[])msg.getFrom();   
   if(addresses!=null&&addresses.length>0)
   {
    //获得邮箱地址
    String from ,personal;
    for(int i=0;i<addresses.length;i++)
    {
     from = addresses[i].getAddress();
     from = from == null ? "" : from;
     personal = addresses[i].getPersonal();
     personal = personal == null ? "" : personal;
     address.append(personal + "<"+from+">");
     if(i < addresses.length-1)
     {
      address.append(";");
     }
    }    
   }   
   return address.toString();
  } catch (Exception e) {
   return null;
  }  
 }
 
 /**
  * 获得邮件的收件人、抄送和密送的地址和姓名,根据所传递的参数的不同
  * to-收件人;cc-抄送人地址;bcc-密送人地址
  * 如果参数为空,则默认为to-即收件人
  * @return
  */
 public String getTo(String type)
 {
  StringBuffer address = new StringBuffer();
  InternetAddress[] addresses = null;
  try {
   if(type==null || "".equals(type))
   {
    type = "to";
   }
   //转化为大写
   type = type.toUpperCase();
   //判读类型是否正确
   if(type.equals("TO") || type.equals("CC") || type.equals("BCC"))
   {
    if(type.equals("TO"))
    {
     addresses = (InternetAddress[])msg.getRecipients(Message.RecipientType.TO);
    }
    else if(type.equals("CC"))
    {
     addresses = (InternetAddress[])msg.getRecipients(Message.RecipientType.CC);    
    }
    else
    {
     addresses = (InternetAddress[])msg.getRecipients(Message.RecipientType.BCC);
    }
    if(addresses != null && addresses.length>0)
    {
     String to ,personal;
     for(int i=0;i<addresses.length;i++)
     {
      to = addresses[i].getAddress();
      to = to == null ? "" : MimeUtility.decodeText(to);
      personal = addresses[i].getPersonal();
      personal = personal == null ? "" : MimeUtility.decodeText(personal);
      address.append(personal + "<"+to+">");
      if(i < addresses.length-1)
      {
       address.append(";");
      }
     }
    }    
   }
   else
   {
    throw new Exception("Error emailAddr type");
   }
   
   return address.toString();
  } catch (Exception e) {
   return null;
  }
 }
 
 /**
  * 获得邮件主题
  * @return
  */
 public String getSubject()
 {
  String subject = null;
  try {
   subject = MimeUtility.decodeText(msg.getSubject());
   subject = subject == null ? "" : subject;
   return subject;
  } catch (Exception e) {
   return null;
  }
 }
 
 /**
  * 获得邮件发送日期
  * @return
  */
 public String getSendDate()
 {
  String sendDateStr = null;
  try {
   Date date = msg.getSentDate();
   SimpleDateFormat fmt = new SimpleDateFormat(defaultDateFormatString);
   sendDateStr = fmt.format(date);
   return sendDateStr;
  } catch (Exception e) {
   return null;
  }  
 } 
 
 /**
  * 获得邮件文本内容
  * @return
  */
 public String getBodyText()
 {  
  return this.bodyText.toString();
 }
 
 /**
  * 解析邮件,把得到的邮件内容保存到一个StringBuffer对象中
  * 解析邮件主要根据MIMETYPE类型的不同执行不同的操作
  * @param part
  */
 public void parseMailContent(Part part)
 {
  try {
   String contentType = part.getContentType();
   int nameIndex = contentType.indexOf("name");
   boolean isContainName = false;
   if(nameIndex != -1)
   {
    isContainName = true;
   }
   System.out.println("contentType:"+contentType);
   if(part.isMimeType("text/plain") && !isContainName)
   {
    bodyText.append(part.getContent().toString());
   }
   else if(part.isMimeType("text/html") && !isContainName)
   {
    bodyText.append(part.getContent().toString());
   }
   else if(part.isMimeType("multipart/*"))
   {
    Multipart multipart = (Multipart)part.getContent();
    int count = multipart.getCount();
    if(count>0)
    {
     for(int i=0;i<count;i++)
     {
      parseMailContent(multipart.getBodyPart(i));
     }
    }
   }
   else if(part.isMimeType("message/rfc822"))
   {
    parseMailContent((Part)part.getContent());
   }
   
  }
  catch(IOException ex)
  {
   
  }
  catch (MessagingException e) { 
   
  }
 }
 
 /**
  * 判断当前邮件是否需要回执
  * 需要回执返回true;不需要回执返回false
  * @return
  */
 public boolean getReplySign()
 {
  boolean replySign = false;
  try {
   String replyAddr[] = msg.getHeader("Disposition-Notification-To");
   if(replyAddr!=null)
   {
    replySign = true;
   }
   return replySign;
  } catch (MessagingException e) {
   return false;
  }
 }
 
 /**
  * 获得此邮件的Message-ID
  * @return
  */
 public String getMessageId()
 {
  try {
   String messageId = msg.getMessageID();
   return messageId;
  } catch (MessagingException e) {
   return null;
  }
 }
 /**
  * 判断此邮件是否已经查看
  * 如果未查看则返回true;如果查看则返回false
  * @return
  */
 public boolean hasSeen()
 {
  boolean isnew = false;
  try {
   Flags flags = msg.getFlags();
   Flags.Flag[] flagArr = flags.getSystemFlags();
   if(flagArr!=null && flagArr.length>0)
   {
    for(int i=0;i<flagArr.length;i++)
    {
     if(flagArr[i] == Flags.Flag.SEEN)
     {
      isnew = true;
      break;
     }
    }
   }
   return isnew;
  } catch (MessagingException e) {
   return false;
  }
  
 }
 /**
  * 判断此邮件是否包含附件
  * @param part
  * @return
  */
 public boolean isContainAttachment(Part part)
 {
  boolean iscontain = false;
  try {   
   if(part.isMimeType("multipart/*"))
   {
    Multipart multipart = (Multipart)part.getContent();
    BodyPart bodyPart = null;
    String disposition = null;
    String bodyCntType = null;
    for(int i=0;i<multipart.getCount();i++)
    {
     bodyPart = multipart.getBodyPart(i);
     disposition = bodyPart.getDisposition();
     if(disposition!=null && (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE)))
     {
      iscontain = true;
     }
     else if(bodyPart.isMimeType("multipart/*"))
     {
      isContainAttachment(bodyPart);
     }
     else
     {
      bodyCntType = bodyPart.getContentType();
      bodyCntType = bodyCntType.toLowerCase();
      if(bodyCntType.indexOf("application")!=-1 || bodyCntType.indexOf("name")!=-1)
      {
       iscontain = true;
      }
     }
     
    }
   }
   else if(part.isMimeType("message/rfc822"))
   {
    iscontain = isContainAttachment((Part)part.getContent());
   }
   return iscontain;   
  } catch (MessagingException e) {
   return false;
  } catch (IOException e) {
   return false;
  }
  
 }
 /**
  * 保存附件
  * @param part
  */
 public void saveAttachment(Part part)
 {
  String fileName = null;
  try {
   if(part.isMimeType("multipart/*"))
   {
    Multipart multipart = (Multipart)part.getContent();
    BodyPart bodyPart = null;
    String disposition = null;
    String contentType = null;
    for(int i=0;i<multipart.getCount();i++)
    {
     bodyPart = multipart.getBodyPart(i);
     disposition = bodyPart.getDisposition();
     if(disposition!=null && (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE)))
     {
      fileName = bodyPart.getFileName();
      if(fileName != null && fileName.toLowerCase().indexOf("gb2312")!=-1 || fileName.toLowerCase().indexOf("gbk")!=-1)
      {
       fileName = MimeUtility.decodeText(fileName);
      }
      saveFile(fileName,bodyPart.getInputStream());
     }
     else if(bodyPart.isMimeType("multipart/*"))
     {
      saveAttachment(bodyPart);
     }
     else
     {
      contentType = bodyPart.getContentType();
      contentType = contentType.toLowerCase();
      if(contentType.indexOf("application")!=-1 || contentType.indexOf("name")!=-1)
      {
       fileName = bodyPart.getFileName();
       if(fileName != null && fileName.toLowerCase().indexOf("gb2312")!=-1 || fileName.toLowerCase().indexOf("gbk")!=-1)
       {
        fileName = MimeUtility.decodeText(fileName);
       }
       saveFile(fileName,bodyPart.getInputStream());
      }      
     }
    }
   }
   else if(part.isMimeType("message/rfc822"))
   {
    saveAttachment((Part)part.getContent());
   }
  } catch (MessagingException e) {   
   e.printStackTrace();
  } catch (IOException e) {   
   e.printStackTrace();
  }
 }
 /**
  * 保存附件到目标位置
  * @param fileName
  * @param is
  */
 public void saveFile(String fileName,InputStream is)
 {
  if(fileName == null || fileName.equals(""))
  {
   return ;
  }
  if(is == null)
  {
   return ;
  }
  String savePath = this.getAttachmentSavePath();
  if(savePath!=null&&!"".equals(savePath))
  {
   if(savePath.indexOf("/")!=-1)
   {
    if(!savePath.substring(savePath.length()-1).equals("/"))
    {
     savePath = savePath + "/";
    }    
   }
   if(savePath.indexOf("//")!=-1)
   {
    if(!savePath.substring(savePath.length()-1).equals("//"))
    {
     savePath = savePath + "//";
    }    
   }
  }
  String filePath = savePath + fileName;
  File file = new File(filePath);
  FileOutputStream os =null;
  int c = 0 ;
  try {
   os = new FileOutputStream(file);   
   while(((c=is.read())!=-1))
   {
    os.write(c);
    os.flush();
   }
   os.close();
   is.close();
  } catch (Exception e) {
   System.out.println("附件"+fileName+"保存失败");
  }  
  finally
  {
   try {
    os.close();
    is.close(); 
   } catch (Exception e) {
    os = null;
    is = null;
   }
   
  }
 }
 
 public String getAttachmentSavePath() {
  return attachmentSavePath;
 }
 public void setAttachmentSavePath(String attachmentSavePath) {
  this.attachmentSavePath = attachmentSavePath;
 }
 public String getDefaultDateFormatString() {
  return defaultDateFormatString;
 }
 public void setDefaultDateFormatString(String defaultDateFormatString) {
  this.defaultDateFormatString = defaultDateFormatString;
 }
 

}

 

测试程序如下:

 

package mail;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeMessage;

import util.ParseMimeMessage;

public class ReceiveMail {

 protected Session session;
 
 public ReceiveMail()
 {
  init();
 }
 
 public void init()
 {
  Properties props = new Properties();
  props.put("mail.transport.protocol","pop3");
  props.put("mail.pop3.disabletop", "true");  
  props.put("mail.pop3.host","pop3.163.com");  
  props.put("mail.pop3.port","110");
  session = Session.getDefaultInstance(props,null);
 }
 
 public void receiveMail() throws Exception
 {
  Store store = session.getStore("pop3");
  store.connect("xxx","xxx");
  Folder folder = store.getFolder("INBOX");
  if(folder!=null)
  {
   folder.open(Folder.READ_ONLY);
   Message[] msgs = folder.getMessages();
   if(msgs!=null && msgs.length>0)
   {
    System.out.println("收件箱中总邮件的个数:"+msgs.length);    
    ParseMimeMessage mailParser = null;
    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");        
    Date todayDate = fmt.parse(fmt.format(new Date()));    
    Date mailSendDate = null;
    String dateStr = null;
    int count = 0;
    for(int i=0;i<msgs.length;i++)
    {     
     mailParser = new ParseMimeMessage((MimeMessage)msgs[i]);     
     dateStr = mailParser.getSendDate();     
     if(dateStr!=null&&!"".equals(dateStr))
     {      
      mailSendDate = fmt.parse(dateStr);
      if(mailSendDate.getTime()>=todayDate.getTime())
      {
       count ++ ;
       System.out.println("今天的第"+count+"封邮件;");       
       System.out.println("发送时间:"+dateStr);       
       System.out.println("邮件发送者:"+mailParser.getFrom());
       System.out.println("邮件接受者:"+mailParser.getTo("to"));
       System.out.println("邮件编号:"+mailParser.getMessageId());
       System.out.println("邮件主题:"+mailParser.getSubject());
       //先解析内容
       mailParser.parseMailContent((Part)msgs[i]);
       System.out.println("邮件内容:"+mailParser.getBodyText());
       System.out.println("邮件是否已经查看:" + (mailParser.hasSeen() ? "是" : "否"));
       System.out.println("邮件是否含有附件:"+ (mailParser.isContainAttachment((Part)msgs[i]) ? "是" : "否" ));
       if(mailParser.isContainAttachment((Part)msgs[i]))
       {
        //保存附件
        System.out.println("正在保存附件,请稍后...");
        mailParser.saveAttachment((Part)msgs[i]);
        System.out.println("附件保存结束~!");
       }
      }
     }     
    }    
   }
  }
  
 }
 
 public static void main(String[] args) throws Exception
 {
  ReceiveMail obj = new ReceiveMail();
  obj.receiveMail();
 }
}