电子邮件系统 1----JavaMail解析电子邮件初步示例(Web程序不完全版)

此次示例有点仿照163邮箱的收件箱,不过目前实现的功能非常少,重点在练习POP3协议解析电子邮件的知识点,所以此Web程序只是随便做做(用的是Struts2)。目前未完全实现的效果图:

 

电子邮件系统 1----JavaMail解析电子邮件初步示例(Web程序不完全版)_第1张图片

电子邮件系统 1----JavaMail解析电子邮件初步示例(Web程序不完全版)_第2张图片

 

电子邮件系统 1----JavaMail解析电子邮件初步示例(Web程序不完全版)_第3张图片

Web工程结构:

电子邮件系统 1----JavaMail解析电子邮件初步示例(Web程序不完全版)_第4张图片

所有代码:

  1. /** 
  2.  * ParseEmailTest 
  3.  * 解决中文乱码的过滤器 
  4.  */  
  5. package com.labci.javamail.filter;  
  6. import java.io.IOException;  
  7. import java.util.logging.LogRecord;  
  8. import javax.servlet.Filter;  
  9. import javax.servlet.FilterChain;  
  10. import javax.servlet.FilterConfig;  
  11. import javax.servlet.ServletException;  
  12. import javax.servlet.ServletRequest;  
  13. import javax.servlet.ServletResponse;  
  14. /** 
  15.  * @author Bill Tu(tujiyue/iwtxokhtd) 
  16.  * May 28, 2011[3:06:09 PM] 
  17.  * 
  18.  */  
  19. public class CharacterEncodingFilter implements Filter,  
  20.         java.util.logging.Filter {  
  21.     private String encoding="gbk";  
  22.     public void destroy() {  
  23.     }  
  24.     public void doFilter(ServletRequest request, ServletResponse response,  
  25.             FilterChain chain) throws IOException, ServletException {  
  26.         request.setCharacterEncoding(encoding);  
  27.         response.setContentType("message/rfc822");  
  28.         chain.doFilter(request, response);  
  29.     }  
  30.     public void init(FilterConfig config) throws ServletException {  
  31.           
  32.         encoding=config.getInitParameter("encode");  
  33.     }  
  34.     public boolean isLoggable(LogRecord record) {  
  35.         return false;  
  36.     }  
  37. }  

 

 

  1. /** 
  2.  * ParseEmailTest 
  3.  * 封装Message的vo类 
  4.  */  
  5. package com.labci.javamail.vo;  
  6. import javax.mail.Message;  
  7. /** 
  8.  * @author Bill Tu(tujiyue/iwtxokhtd) 
  9.  * May 28, 2011[1:43:00 PM] 
  10.  * 
  11.  */  
  12. public class MessageVo {  
  13.     private Message msg;//邮件实体类   
  14.     private int messageId;//自定义的邮件id   
  15.     private String from;//邮件发送人地址   
  16.     private String personal;//邮件发送显示名   
  17.     private String subject;//邮件主题   
  18.     private String content;//邮件内容,此字段暂时未用上   
  19.     private String sentDate;//收件箱列表时间的显示格式   
  20.     private boolean unRead;//判断邮件是否是新邮件   
  21.     private boolean hasAttach=false;//是否有附件   
  22.       
  23.     public Message getMsg() {  
  24.         return msg;  
  25.     }  
  26.     public void setMsg(Message msg) {  
  27.         this.msg = msg;  
  28.     }  
  29.     public String getFrom() {  
  30.         return from;  
  31.     }  
  32.     public void setFrom(String from) {  
  33.         this.from = from;  
  34.     }  
  35.     public int getMessageId() {  
  36.         return messageId;  
  37.     }  
  38.     public void setMessageId(int messageId) {  
  39.         this.messageId = messageId;  
  40.     }  
  41.     public boolean isHasAttach() {  
  42.         return hasAttach;  
  43.     }  
  44.     public void setHasAttach(boolean hasAttach) {  
  45.         this.hasAttach = hasAttach;  
  46.     }  
  47.     public String getContent() {  
  48.         return content;  
  49.     }  
  50.     public void setContent(String content) {  
  51.         this.content = content;  
  52.     }  
  53.     public String getSubject() {  
  54.         return subject;  
  55.     }  
  56.     public void setSubject(String subject) {  
  57.         this.subject = subject;  
  58.     }  
  59.     public String getPersonal() {  
  60.         return personal;  
  61.     }  
  62.     public void setPersonal(String personal) {  
  63.         this.personal = personal;  
  64.     }  
  65.     public String getSentDate() {  
  66.         return sentDate;  
  67.     }  
  68.     public void setSentDate(String sentDate) {  
  69.         this.sentDate = sentDate;  
  70.     }  
  71.     public boolean isUnRead() {  
  72.         return unRead;  
  73.     }  
  74.     public void setUnRead(boolean unRead) {  
  75.         this.unRead = unRead;  
  76.     }  
  77.       
  78. }  

 

 

  1. /** 
  2.  * ParseEmailTest 
  3.  * 一个简单地邮件分页组件 
  4.  */  
  5. package com.labci.javamail.utils;  
  6. import java.util.HashMap;  
  7. import java.util.List;  
  8. import java.util.Map;  
  9. import com.labci.javamail.vo.MessageVo;  
  10. /** 
  11.  * @author Bill Tu(tujiyue/iwtxokhtd) 
  12.  * May 28, 2011[9:29:53 AM] 
  13.  * 
  14.  */  
  15. public class MessagePageBean {  
  16.     //总邮件数   
  17.     private List<MessageVo> recordsList=null;  
  18.     //当前页码   
  19.     private Integer pageNo=1;  
  20.     //总页数   
  21.     @SuppressWarnings("unused")  
  22.     private Integer totalPage=1;  
  23.     //总记录数   
  24.     private Integer totalCount=0;  
  25.     //每页大小   
  26.     private Integer pageSize=20;  
  27.     //是否有下一页   
  28.     private Boolean hasNext=false;  
  29.     //是否有上一页   
  30.     private Boolean hasPrev=false;  
  31.       
  32.       
  33.     /** 
  34.      * 构造初始化邮件列表和邮件总数 
  35.      * @param recordsList 
  36.      */  
  37.     public MessagePageBean(List<MessageVo> recordsList) {  
  38.         this.recordsList = recordsList;  
  39.         if(!isListNull(recordsList)){  
  40.             totalCount=recordsList.size();  
  41.         }  
  42.     }  
  43.       
  44.     /** 
  45.      * 取得每页的邮件数据 
  46.      * @param pageNo 当前页码 
  47.      * @param pageSize 取多少条记录 
  48.      * @return {"currentPage":当前第几页,"pageSize":每页大小,"totalCount":总记录数,"totalPage":总页数, 
  49.      *          "recordsList":List<Message> list 每页邮件列表,"hasNext":是否有下一页,"hasPrev":是否有上一页} 
  50.      */  
  51.     public Map<String,Object> getPageRecordsMap(int pageNo,int pageSize){  
  52.         Map<String,Object> pageRecordsMap=new HashMap<String,Object>();  
  53.         pageRecordsMap.put("currentPage", pageNo);  
  54.         pageRecordsMap.put("pageSize", pageSize);  
  55.         pageRecordsMap.put("totalCount", getTotalCount());  
  56.         pageRecordsMap.put("totalPage", getTotalPage());  
  57.           
  58.         int fromIndex=0;  
  59.         int toIndex=0;  
  60.         fromIndex=pageSize*(pageNo-1);  
  61.         toIndex=fromIndex+pageSize;  
  62.         if(toIndex>getTotalCount()){  
  63.             toIndex=getTotalCount();  
  64.         }  
  65.         if(fromIndex<0){  
  66.             fromIndex=0;  
  67.         }  
  68.         setPageNo(pageNo);  
  69.         pageRecordsMap.put("recordsList", recordsList.subList(fromIndex, toIndex));  
  70.         pageRecordsMap.put("hasNext", getHasNext());  
  71.         pageRecordsMap.put("hasPrev", getHasPrev());  
  72.         return pageRecordsMap;  
  73.           
  74.     }  
  75.       
  76.     private boolean isListNull(List<MessageVo> recordsList){  
  77.         boolean isNull=false;  
  78.         if(null==recordsList||recordsList.size()<=0){  
  79.             isNull=true;  
  80.         }  
  81.         return isNull;  
  82.     }  
  83.       
  84.     public Integer getPageNo() {  
  85.         return pageNo;  
  86.     }  
  87.     public void setPageNo(Integer pageNo) {  
  88.         this.pageNo = pageNo;  
  89.     }  
  90.     public Integer getTotalPage() {  
  91.         return (getTotalCount()+pageSize-1)/pageSize;  
  92.     }  
  93.     public Integer getTotalCount() {  
  94.         return totalCount;  
  95.     }  
  96.     public Integer getPageSize() {  
  97.         return pageSize<=0?10:pageSize;  
  98.     }  
  99.     public Boolean getHasNext() {  
  100.         hasNext=pageNo<getTotalPage()?true:false;  
  101.         return hasNext;  
  102.     }  
  103.     public Boolean getHasPrev() {  
  104.         hasPrev=pageNo>1?true:false;  
  105.         return hasPrev;  
  106.     }  
  107.       
  108.       
  109. }  

 

 

  1. /** 
  2.  * ParseEmailTest 
  3.  * 对邮件按时间排序,即最新的邮件显示在最上面 
  4.  * 由于是通过API去访问而不是通过数据库的形式,所以这里的排序性能很差 
  5.  */  
  6. package com.labci.javamail.utils;  
  7. import java.util.Comparator;  
  8. import javax.mail.Message;  
  9. import javax.mail.MessagingException;  
  10. /** 
  11.  * @author Bill Tu(tujiyue/iwtxokhtd) 
  12.  * May 28, 2011[12:05:48 PM] 
  13.  * 
  14.  */  
  15. public class MessageComparator implements Comparator<Message> {  
  16.     public int compare(Message o1, Message o2) {  
  17.         boolean isBefore=false;  
  18.         try {  
  19.             isBefore = o1.getSentDate().before(o2.getSentDate());  
  20.         } catch (MessagingException e) {  
  21.             e.printStackTrace();  
  22.         }  
  23.         int rntValue=0;  
  24.         if(isBefore){  
  25.             rntValue=1;  
  26.         }else{  
  27.             rntValue=-1;  
  28.         }  
  29.         return rntValue;  
  30.     }  
  31. }  

 

 

  1. /** 
  2.  * ParseEmailTest 
  3.  * 用BASE64算法解析指定字符串 
  4.  */  
  5. package com.labci.javamail.utils;  
  6. import java.io.IOException;  
  7. import sun.misc.BASE64Decoder;  
  8. /** 
  9.  * @author Bill Tu(tujiyue/iwtxokhtd) 
  10.  * May 28, 2011[1:36:22 PM] 
  11.  * 
  12.  */  
  13. public class DecodeFrom {  
  14.     private DecodeFrom(){  
  15.           
  16.     }  
  17.       
  18.     public static String getDecondedString(String from){  
  19.         String fromStr="";  
  20.         try {  
  21.             fromStr=new String(new BASE64Decoder().decodeBuffer(from));  
  22.         } catch (IOException e) {  
  23.             e.printStackTrace();  
  24.         }  
  25.         return fromStr;  
  26.     }  
  27. }  

 

 

  1. /** 
  2.  * ParseEmailTest 
  3.  * 查询邮件列表的公用类 
  4.  * 也即简单单例模式的使用 
  5.  */  
  6. package com.labci.javamail.utils;  
  7. import java.io.IOException;  
  8. import java.util.ArrayList;  
  9. import java.util.Arrays;  
  10. import java.util.Collections;  
  11. import java.util.HashMap;  
  12. import java.util.List;  
  13. import java.util.Map;  
  14. import javax.mail.Folder;  
  15. import javax.mail.Message;  
  16. import javax.mail.MessagingException;  
  17. import javax.mail.Store;  
  18. import javax.mail.internet.InternetAddress;  
  19. import com.labci.javamail.vo.MessageVo;  
  20. /** 
  21.  * @author Bill Tu(tujiyue/iwtxokhtd) 
  22.  * May 28, 2011[12:14:37 PM] 
  23.  * 
  24.  */  
  25. public class GetMessageList {  
  26.     private static GetMessageList instance=null;  
  27.       
  28.     private GetMessageList(){  
  29.           
  30.     }  
  31.     //延迟双重检查机制   
  32.     public static GetMessageList getInstance(){  
  33.         if(null == instance){  
  34.             synchronized(GetMessageList.class){  
  35.                 if(null == instance){  
  36.                     instance= new GetMessageList();  
  37.                 }  
  38.             }  
  39.         }  
  40.         return instance;   
  41.     }  
  42.       
  43.     @SuppressWarnings({ "unused""static-access" })  
  44.     public Map<String,Object>  getEmailsMap(Store store,int pageNo,int pageSize) throws MessagingException{  
  45.           
  46.         Map<String,Object> rntMap=new HashMap<String,Object>();  
  47.           
  48.         Folder receiveFolder=store.getFolder("inbox");//对于POP3协议此参数值只能是inbox   
  49.         receiveFolder.open(Folder.READ_WRITE);//设置收件夹打开后的读写权限   
  50.         int messageCount=receiveFolder.getMessageCount();  
  51.         if(messageCount<=0){  
  52.             return null;  
  53.         }  
  54.           
  55.         Message []messages=receiveFolder.getMessages();  
  56.         List<Message> messagesList=Arrays.asList(messages);  
  57.           
  58.         //对发送邮件时间按倒序排,这样最新的邮件显示在最上面   
  59.         Collections.sort(messagesList, new MessageComparator());  
  60.         List<MessageVo> messagesVoList=new ArrayList<MessageVo>();  
  61.         int i=0;  
  62.         for(Message msg:messagesList){  
  63.               
  64.             InternetAddress[] iAddress=(InternetAddress[]) msg.getFrom();  
  65.             String from=iAddress[0].getAddress();  
  66.             if(null==from){  
  67.                 from="";  
  68.             }  
  69.             String personal=iAddress[0].getPersonal();  
  70.             if(null==personal){  
  71.                 personal="";  
  72.             }  
  73.               
  74.             MessageVo mv=new MessageVo();  
  75.             mv.setMessageId(i++);  
  76.             mv.setMsg(msg);  
  77.             mv.setSubject(msg.getSubject());  
  78.               
  79.             try {  
  80.                 mv.setHasAttach(CommonUtils.getInstance().hasAttach(msg));  
  81.             } catch (IOException e) {  
  82.                 e.printStackTrace();  
  83.             }  
  84.             mv.setPersonal(personal);  
  85.             if(!"".equals(personal)){  
  86.                 from="<"+from+">";  
  87.             }  
  88.             mv.setFrom(from);  
  89.             mv.setUnRead(CommonUtils.getInstance().isNewMsg(msg));//POP3协议不支持是否是新邮件判断   
  90.             mv.setSentDate(DateUtils.getMsgSentDateString(msg.getSentDate()));  
  91.             messagesVoList.add(mv);  
  92.         }  
  93.         Map<String,Object> pageMessageMap=new MessagePageBean(messagesVoList).getPageRecordsMap(pageNo, pageSize);  
  94.         rntMap.put("msgMap", pageMessageMap);  
  95.         rntMap.put("msgVoList", messagesVoList);  
  96.         return rntMap;  
  97.     }  
  98. }  

 

 

  1. /** 
  2.  * ParseEmailTest 
  3.  * 处理邮件发送时间格式 
  4.  * 该类用到了一个开源jar包,名为date4j.jar 
  5.  */  
  6. package com.labci.javamail.utils;  
  7. import hirondelle.date4j.DateTime;  
  8. import java.text.DateFormat;  
  9. import java.text.SimpleDateFormat;  
  10. import java.util.Calendar;  
  11. import java.util.Date;  
  12. /** 
  13.  * @author Bill Tu(tujiyue/iwtxokhtd) 
  14.  * May 28, 2011[9:00:31 PM] 
  15.  * 
  16.  */  
  17. public class DateUtils {  
  18.     private DateUtils(){  
  19.           
  20.     }  
  21.       
  22.     public static String getMsgSentDateString(Date sentDate){  
  23.         String dateString="";  
  24.         DateFormat hhmmSDF=new SimpleDateFormat("HH:mm");  
  25.         DateFormat mmddSDF=new SimpleDateFormat("MM月dd日");  
  26.         DateFormat yyyySDF=new SimpleDateFormat("yyyy-MM-dd");  
  27.         DateFormat fullSDF=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  28.           
  29.         DateTime sentDateTime=new DateTime(fullSDF.format(sentDate));  
  30.         DateTime todayDateTime=new DateTime(fullSDF.format(new Date()));  
  31.         //如果是在今天之内   
  32.         if(sentDateTime.isSameDayAs(todayDateTime)){  
  33.             dateString=hhmmSDF.format(sentDate);  
  34.         }else if(sentDateTime.numDaysFrom(todayDateTime)<=90){  
  35.             //如果在三个月内,就显示月和日   
  36.             dateString=mmddSDF.format(sentDate);  
  37.         }else{  
  38.             //否则就显示yyyy-MM-dd   
  39.             dateString=yyyySDF.format(sentDate);  
  40.         }  
  41.         return dateString;  
  42.     }  
  43.       
  44.     public static String getSentDateFullString(Date sentDate){  
  45.         DateFormat fullSDF=new SimpleDateFormat("yyyy年MM月dd日 HH:mm");  
  46.         return fullSDF.format(sentDate);  
  47.     }  
  48.       
  49.     public static String getSentDateWeekString(Date sentDate){  
  50.         final String dayNames[] = { "星期日""星期一""星期二""星期三",   
  51.                 "星期四""星期五","星期六" };   
  52.         Calendar calendar = Calendar.getInstance();   
  53.         calendar.setTime(sentDate);   
  54.         int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK)-1;   
  55.         if(dayOfWeek <0){  
  56.             dayOfWeek=0;   
  57.         }  
  58.         return dayNames[dayOfWeek];  
  59.     }  
  60. }  

 

 

  1. /** 
  2.  * ParseEmailTest 
  3.  * 一些其它操作的工具类 
  4.  * 
  5.  */  
  6. package com.labci.javamail.utils;  
  7. import java.io.IOException;  
  8. import java.util.Properties;  
  9. import javax.mail.Flags;  
  10. import javax.mail.Message;  
  11. import javax.mail.MessagingException;  
  12. import javax.mail.Session;  
  13. import javax.servlet.http.HttpServletRequest;  
  14. /** 
  15.  * @author Bill Tu(tujiyue/iwtxokhtd) 
  16.  * May 28, 2011[12:27:03 PM] 
  17.  * 
  18.  */  
  19. public class CommonUtils {  
  20.     //此处的示例POP3服务器主机名写死为163的,不由用户输入   
  21.     private static final String HOST="pop3.163.com";  
  22.     private static final String PROTOCOL="pop3";  
  23.     private static CommonUtils instance=null;  
  24.       
  25.       
  26.     private CommonUtils(){  
  27.           
  28.     }  
  29.       
  30.     public static CommonUtils getInstance(){  
  31.         if(null == instance){  
  32.             synchronized(GetMessageList.class){  
  33.                 if(null == instance){  
  34.                     instance= new CommonUtils();  
  35.                 }  
  36.             }  
  37.         }  
  38.         return instance;   
  39.     }  
  40.       
  41.     public int getPageNo(HttpServletRequest request){  
  42.         int pageNo=1;  
  43.         if(null==request.getParameter("pageNo")  
  44.                 ||"".equals(request.getParameter("pageNo").trim())){  
  45.             pageNo=1;  
  46.         }else{  
  47.             pageNo=Integer.parseInt(request.getParameter("pageNo"));  
  48.         }  
  49.         return pageNo;  
  50.     }  
  51.       
  52.     //取得JavaMail的Session   
  53.     public Session getMailSession(){  
  54.         Properties mailProps=new Properties();  
  55.         mailProps.put("mail.store.protocol", PROTOCOL);  
  56.         mailProps.put("mail.pop3.host", HOST);  
  57.           
  58.         Session session=Session.getDefaultInstance(mailProps);  
  59.         return session;  
  60.     }  
  61.     /** 
  62.      * 是否有附件 
  63.      * @param msg 
  64.      * @return 
  65.      * @throws MessagingException 
  66.      * @throws IOException 
  67.      */  
  68.     public boolean hasAttach(Message msg) throws MessagingException, IOException{  
  69.         boolean hasAttach=false;  
  70.         if(msg.getContentType().contains("multipart/mixed")){  
  71.             hasAttach=true;  
  72.         }  
  73.         return hasAttach;  
  74.     }  
  75.       
  76.     public boolean isNewMsg(Message msg) throws MessagingException {     
  77.         boolean isNew = false;     
  78.         Flags flags = msg.getFlags();     
  79.         Flags.Flag[] flag = flags.getSystemFlags();     
  80.         for (int i = 0; i < flag.length; i++) {     
  81.             if (flag[i] == Flags.Flag.SEEN) {     
  82.                 isNew = true;     
  83.                 break;     
  84.             }     
  85.         }     
  86.         return isNew;     
  87.     }     
  88. }  

 

 

 

  1. /** 
  2.  * ParseEmailTest 
  3.  * 登录邮箱 
  4.  */  
  5. package com.labci.javamail.action;  
  6. import java.util.Map;  
  7. import javax.mail.MessagingException;  
  8. import javax.mail.Store;  
  9. import javax.servlet.http.HttpServletRequest;  
  10. import org.apache.struts2.interceptor.ServletRequestAware;  
  11. import com.labci.javamail.utils.CommonUtils;  
  12. import com.labci.javamail.utils.GetMessageList;  
  13. import com.opensymphony.xwork2.Action;  
  14. /** 
  15.  * @author Bill Tu(tujiyue/iwtxokhtd) 
  16.  * May 28, 2011[10:22:24 AM] 
  17.  * 
  18.  */  
  19. public class LoginMailAction implements Action, ServletRequestAware {  
  20.       
  21.     private HttpServletRequest request;  
  22.     //此处的示例POP3服务器主机名写死为163的,不由用户输入   
  23.     private static final String HOST="pop3.163.com";  
  24.     private static final int PAGESIZE=20;  
  25.       
  26.     public String execute() throws Exception {  
  27.           
  28.         String username=request.getParameter("username");  
  29.         String password=request.getParameter("password");  
  30.         Store store=CommonUtils.getInstance().getMailSession().getStore();  
  31.         try{  
  32.             store.connect(HOST,username,password);  
  33.             request.getSession().setAttribute("store", store);  
  34.         }catch(MessagingException e){  
  35.             //登录失败   
  36.             request.setAttribute("loginFailure""登录失败,请确认用户名或密码");  
  37.             return ERROR;  
  38.         }  
  39.           
  40.         //登录成功后的操作   
  41.         displayEmails(store,CommonUtils.getInstance().getPageNo(request),PAGESIZE);  
  42.         return SUCCESS;//去邮件列表显示页   
  43.     }  
  44.     //登录成功后的操作   
  45.     @SuppressWarnings("unchecked")  
  46.     private void displayEmails(Store store,int pageNo,int pageSize) throws MessagingException{  
  47.         Map<String,Object> rntMap = GetMessageList.getInstance().getEmailsMap(store, pageNo, pageSize);  
  48.           
  49.         Map<String,Object> mailsMap=(Map<String, Object>) rntMap.get("msgMap");  
  50.           
  51.         if(null == mailsMap){  
  52.             request.setAttribute("notAvailableEmail""您当前的邮箱中没有收到任何邮件");  
  53.         }else{  
  54.             request.setAttribute("recordsMap", mailsMap);  
  55.         }  
  56.     }  
  57.       
  58.     public void setServletRequest(HttpServletRequest arg0) {  
  59.         this.request=arg0;  
  60.     }  
  61. }  

 

 

  1. /** 
  2.  * ParseEmailTest 
  3.  * 邮件列表翻页类 
  4.  */  
  5. package com.labci.javamail.action;  
  6. import java.util.Map;  
  7. import javax.mail.MessagingException;  
  8. import javax.mail.Store;  
  9. import javax.servlet.http.HttpServletRequest;  
  10. import org.apache.struts2.interceptor.ServletRequestAware;  
  11. import com.labci.javamail.utils.CommonUtils;  
  12. import com.labci.javamail.utils.GetMessageList;  
  13. import com.opensymphony.xwork2.Action;  
  14. /** 
  15.  * @author Bill Tu(tujiyue/iwtxokhtd) 
  16.  * May 28, 2011[12:25:20 PM] 
  17.  * 
  18.  */  
  19. public class MailListAction implements Action, ServletRequestAware{  
  20.       
  21.     private HttpServletRequest request;  
  22.     private static final int PAGESIZE=20;  
  23.       
  24.     public String execute() throws Exception {  
  25.         int pageNo=CommonUtils.getInstance().getPageNo(request);  
  26.         Store store=null;  
  27.         if(null != request.getSession().getAttribute("store")){  
  28.             store=(Store) request.getSession().getAttribute("store");  
  29.         }  
  30.           
  31.         displayEmails(store,pageNo,PAGESIZE);  
  32.         return SUCCESS;  
  33.     }  
  34.     //登录成功后的操作   
  35.     @SuppressWarnings("unchecked")  
  36.     private void displayEmails(Store store,int pageNo,int pageSize) throws MessagingException{  
  37.         Map<String,Object> rntMap = GetMessageList.getInstance().getEmailsMap(store, pageNo, pageSize);  
  38.         Map<String,Object> mailsMap=(Map<String, Object>) rntMap.get("msgMap");  
  39.         if(null == mailsMap){  
  40.             request.setAttribute("notAvailableEmail""您当前的邮箱中没有收到任何邮件");  
  41.         }else{  
  42.             request.setAttribute("recordsMap", mailsMap);  
  43.         }  
  44.     }  
  45.     public void setServletRequest(HttpServletRequest arg0) {  
  46.         this.request=arg0;  
  47.     }  
  48. }  

 

 

  1. /** 
  2.  * ParseEmailTest 
  3.  * 查看邮件的类 
  4.  */  
  5. package com.labci.javamail.action;  
  6. import java.io.BufferedReader;  
  7. import java.io.FileOutputStream;  
  8. import java.io.IOException;  
  9. import java.io.InputStream;  
  10. import java.io.InputStreamReader;  
  11. import java.util.HashMap;  
  12. import java.util.List;  
  13. import java.util.Map;  
  14. import javax.mail.Address;  
  15. import javax.mail.MessagingException;  
  16. import javax.mail.Multipart;  
  17. import javax.mail.Part;  
  18. import javax.mail.Store;  
  19. import javax.mail.Message.RecipientType;  
  20. import javax.servlet.http.HttpServletRequest;  
  21. import org.apache.struts2.interceptor.ServletRequestAware;  
  22. import com.labci.javamail.utils.CommonUtils;  
  23. import com.labci.javamail.utils.DateUtils;  
  24. import com.labci.javamail.utils.GetMessageList;  
  25. import com.labci.javamail.vo.MessageVo;  
  26. import com.opensymphony.xwork2.Action;  
  27. /** 
  28.  * @author Bill Tu(tujiyue/iwtxokhtd) 
  29.  * May 28, 2011[12:25:20 PM] 
  30.  * 
  31.  */  
  32. public class ViewMailAction implements Action, ServletRequestAware{  
  33.       
  34.     private HttpServletRequest request;  
  35.     private static final int PAGESIZE=20;  
  36.       
  37.     @SuppressWarnings("unchecked")  
  38.     public String execute() throws Exception {  
  39.         int pageNo=CommonUtils.getInstance().getPageNo(request);  
  40.         int messageId=Integer.parseInt(request.getParameter("messageId"));  
  41.         Store store=null;  
  42.         if(null != request.getSession().getAttribute("store")){  
  43.             store=(Store) request.getSession().getAttribute("store");  
  44.         }  
  45.         Map<String,Object> rntMap = GetMessageList.getInstance().getEmailsMap(store, pageNo, PAGESIZE);  
  46.         List<MessageVo> messageVoList=(List<MessageVo>) rntMap.get("msgVoList");  
  47.         MessageVo msgVo=null;  
  48.         if(!isMessageListNull(messageVoList)){  
  49.             msgVo=messageVoList.get(messageId);  
  50.         }  
  51.           
  52.         Map<String,Object> msgMap=new HashMap<String,Object>();  
  53.           
  54.         if(null!=msgVo){  
  55.             msgMap.put("from", msgVo.getFrom());  
  56.             msgMap.put("personal", msgVo.getPersonal());  
  57.             msgMap.put("messageId", msgVo.getMessageId());  
  58.             msgMap.put("subject", msgVo.getSubject());  
  59.             msgMap.put("sentDate", DateUtils.getSentDateFullString(msgVo.getMsg().getSentDate())  
  60.                     +"("+DateUtils.getSentDateWeekString(msgVo.getMsg().getSentDate())+")");  
  61.             Address []toAddress=msgVo.getMsg().getRecipients(RecipientType.TO);  
  62.             if(null!=toAddress && toAddress.length>0){  
  63.                 StringBuilder addressStr=new StringBuilder("");  
  64.                 for(Address address:toAddress){  
  65.                     addressStr.append(address.toString()).append(";");  
  66.                 }  
  67.                 addressStr.deleteCharAt(addressStr.length()-1);  
  68.                 msgMap.put("receiver", addressStr.toString());  
  69.             }else{  
  70.                 msgMap.put("receiver""(无)");  
  71.             }  
  72.             if(!msgVo.getMsg().getContentType().trim().equals("multipart/mixed")){  
  73.                 msgMap.put("content",getHtmlContent(msgVo));  
  74.             }else{  
  75.                 //这里对附件的解析还没完全实现   
  76.                 Multipart mp = (Multipart) msgVo.getMsg().getContent();  
  77.                 for(int i=0;i<mp.getCount();i++){  
  78.                     Part part=mp.getBodyPart(i);  
  79.                     if(part.getContent() instanceof Multipart){//此条件可能不成立   
  80.                         Multipart p=(Multipart) part.getContent();  
  81.                         for(int j=0;j<p.getCount();j++){  
  82.                             if(p.getBodyPart(j).getContentType().startsWith("text/plain")){  
  83.                                 msgMap.put("content",p.getBodyPart(j).getContent()+"");  
  84.                             }else{  
  85.                                 msgMap.put("content",p.getBodyPart(j).getContent()+"");  
  86.                             }  
  87.                         }  
  88.                     }  
  89.                       
  90.                     if(null !=part.getDisposition()){//如果有附件   
  91.                         InputStream is=part.getInputStream();  
  92.                         FileOutputStream fos=new FileOutputStream(part.getFileName());  
  93.                         int readData=0;  
  94.                         while((readData=is.read())!=-1){  
  95.                             fos.write(readData);  
  96.                         }  
  97.                         is.close();  
  98.                         fos.close();  
  99.                     }  
  100.                 }  
  101.             }  
  102.         }  
  103.           
  104.         request.setAttribute("msgMap", msgMap);  
  105.         return SUCCESS;  
  106.     }  
  107.     private String getHtmlContent(MessageVo msgVo) throws IOException, MessagingException{  
  108.         InputStream is=msgVo.getMsg().getDataHandler().getInputStream();  
  109.         BufferedReader br=new BufferedReader(new InputStreamReader(is));  
  110.         StringBuilder sb=new StringBuilder("");  
  111.         String input=null;  
  112.         while(null !=(input=br.readLine())){  
  113.             sb.append(input);  
  114.         }  
  115.         return sb.toString();  
  116.     }  
  117.       
  118.     private boolean isMessageListNull(List<MessageVo> messageVoList){  
  119.         boolean isListNull=false;  
  120.         if(null ==messageVoList || messageVoList.size()<=0){  
  121.             isListNull=true;  
  122.         }  
  123.         return isListNull;  
  124.     }  
  125.       
  126.       
  127.     public void setServletRequest(HttpServletRequest arg0) {  
  128.         this.request=arg0;  
  129.     }  
  130. }  

 

 

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.4"   
  3.     xmlns="http://java.sun.com/xml/ns/j2ee"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   
  6.     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
  7.   <welcome-file-list>  
  8.     <welcome-file>index.jsp</welcome-file>  
  9.   </welcome-file-list>  
  10.     
  11.   <filter>  
  12.     <filter-name>encoding</filter-name>  
  13.     <filter-class>com.labci.javamail.filter.CharacterEncodingFilter</filter-class>  
  14.      <init-param>  
  15.         <param-name>encode</param-name>  
  16.         <param-value>gbk</param-value>  
  17.     </init-param>  
  18.   </filter>  
  19.     
  20.   <filter-mapping>  
  21.     <filter-name>encoding</filter-name>  
  22.     <url-pattern>/*</url-pattern>  
  23.   </filter-mapping>  
  24.     
  25.   <filter>  
  26.     <filter-name>struts2</filter-name>  
  27.     <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>  
  28.   </filter>  
  29.   <filter-mapping>  
  30.     <filter-name>struts2</filter-name>  
  31.     <url-pattern>*.do</url-pattern>  
  32.   </filter-mapping>  
  33.   <session-config>  
  34.     <session-timeout>1440</session-timeout>  
  35.   </session-config>  
  36. </web-app>  

 

 

  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE struts PUBLIC  
  3.     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
  4.     "http://struts.apache.org/dtds/struts-2.0.dtd">  
  5. <struts>  
  6.     <constant name="struts.action.extension" value="do" />  
  7.     <constant name="struts.devMode" value="false" />  
  8.     <package name="mail" extends="struts-default">  
  9.         <action name="login" class="com.labci.javamail.action.LoginMailAction">  
  10.             <result name="success">mailList.jsp</result>  
  11.             <result name="error">index.jsp</result>  
  12.         </action>  
  13.         <action name="mailList" class="com.labci.javamail.action.MailListAction">  
  14.             <result name="success">mailList.jsp</result>  
  15.         </action>  
  16.         <action name="viewMail" class="com.labci.javamail.action.ViewMailAction">  
  17.             <result name="success">viewMail.jsp</result>  
  18.         </action>  
  19.           
  20.     </package>  
  21. </struts>  

 

 

  1. <%@ page language="java" pageEncoding="gbk"%>  
  2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  • <html>  
  •   <head>  
  •     <title>登录网易邮箱</title>  
  •   </head>  
  •     
  •   <body>  
  •     <form action="login.do" method="post">  
  •         请使用163邮箱账号进行登录<br/>  
  •         用户名:<input type="text" name="username"/><br/>  
  •         密  码:<input type="password" name="password"/><br/>  
  •             <input type="submit" value="登录"/>  
  •             <input type="reset" value="重置"/>  
  •     </form>  
  •   </body>  
  • </html>  

 

  1. <%@ page language="java" pageEncoding="gbk"%>  
  2. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
  • <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  • <html>  
  •   <head>  
  •     <title>收件箱</title>  
  •   </head>  
  •     
  •   <body>  
  •     <table>  
  •     <c:choose>  
  •         <c:when test="${!empty notAvailableEmail}">  
  •            <tr>  
  •                 <td>  
  •                 <c:out value="${notAvailableEmail}"/>  
  •                 </td>  
  •             </tr>  
  •         </c:when>  
  •         <c:otherwise>  
  •             <tr>  
  •             <td>共有<b>${recordsMap['totalCount']}</b>封邮件,当前第<b>${recordsMap['currentPage']}</b>页,  
  •             每页显示<b>${recordsMap['pageSize']}</b>封,共有<b>${recordsMap['totalPage']}</b></td>  
  •             </tr>  
  •             <tr><td><hr/></td></tr>  
  •             <tr>  
  •             <td>  
  •                 <input type="checkbox" name="selectAll"/> <input type="button" name="deleteMsg" value="删除">  
  •             </td>  
  •             </tr>  
  •              <tr><td colspan="4"><b><hr/></b></td></tr>  
  •             <c:forEach items="${recordsMap['recordsList']}" var="mailVo">  
  •                 <tr>  
  •                  <td><input type="checkbox" name="messageId" value="${mailVo.messageId}"/><b>${mailVo.personal}</b>${mailVo.from}</td>  
  •                  <td>  
  •                   <c:choose>  
  •                     <c:when test="${mailVo.unRead}">  
  •                      <b><a href="viewMail.do?messageId=${mailVo.messageId}&pageNo=${recordsMap['currentPage']}" mce_href="viewMail.do?messageId=${mailVo.messageId}&pageNo=${recordsMap['currentPage']}">${mailVo.subject}</a></b>  
  •                     </c:when>  
  •                     <c:otherwise>  
  •                         <a href="viewMail.do?messageId=${mailVo.messageId}&pageNo=${recordsMap['currentPage']}" mce_href="viewMail.do?messageId=${mailVo.messageId}&pageNo=${recordsMap['currentPage']}">${mailVo.subject}</a>  
  •                     </c:otherwise>  
  •                   </c:choose>  
  •                 </td>  
  •                 <td>  
  •                 <c:if test="${mailVo.hasAttach}">  
  •                     <img src="images/attach.jpg" mce_src="images/attach.jpg" title="附件"/>  
  •                 </c:if>  
  •                 </td>  
  •                  <td>  
  •                  ${mailVo.sentDate}  
  •                 </td>  
  •                 </tr>  
  •             </c:forEach>  
  •             <tr>  
  •             <td>  
  •                 <c:if test="${recordsMap['hasNext']}"><a href="mailList.do?pageNo=${recordsMap['currentPage']+1}" mce_href="mailList.do?pageNo=${recordsMap['currentPage']+1}">下一页</a></c:if>  
  •                  <c:if test="${recordsMap['hasPrev']}"><a href="mailList.do?pageNo=${recordsMap['currentPage']-1}" mce_href="mailList.do?pageNo=${recordsMap['currentPage']-1}">上一页</a></c:if>  
  •             </td>  
  •             </tr>  
  •         </c:otherwise>  
  •     </c:choose>  
  •     </table>  
  •   </body>  
  • </html>  

 

  1. <%@ page language="java" pageEncoding="utf-8"  contentType="text/html;charset=utf-8"%>  
  2. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
  • <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  • <html>  
  •   <head>  
  •     <title>查看邮件</title>  
  •   </head>  
  •     
  •   <body>  
  •     <table>  
  •         <tr>  
  •             <td><b>${msgMap['subject']}</b></td>  
  •         </tr>  
  •         <tr>  
  •             <td>发件人:<b>${msgMap['personal']}</b>${msgMap['from']}</td>  
  •         </tr>  
  •         <tr>  
  •             <td>时间:${msgMap['sentDate']}</td>  
  •         </tr>  
  •         <tr>  
  •             <td>收件人:${msgMap['receiver']}</td>  
  •         </tr>  
  •         <tr>  
  •         <td>  
  •          <hr/>  
  •          </td>  
  •         </tr>  
  •         <tr>  
  •           <td>${msgMap['content']}</td>  
  •         </tr>  
  •         <tr>  
  •         <td>  
  •             <c:if test="${!empty msgMap['attachNameList']}">  
  •                 <c:forEach items="${msgMap['attachNameList']}" var="attach">  
  •                     ${attach}  
  •                 </c:forEach>  
  •             </c:if>  
  •         </td>  
  •         </tr>  
  •     </table>  
  •   </body>  
  • </html>  

你可能感兴趣的:(javamail)