邮件下载及发送,获取邮件数各种数据

  1 import java.io.*;
  2 import java.text.*;
  3 import java.util.*;
  4 import javax.mail.*;
  5 import javax.mail.internet.*;
  6  
  7 public class PraseMimeMessage {
  8     private MimeMessage mimeMessage = null;
  9     private String saveAttachPath = "";// 附件下载后的存放目录
 10     private StringBuffer bodytext = new StringBuffer();
 11     // 存放邮件内容的StringBuffer对象
 12     private String dateformat = "yy-MM-dd HH:mm";// 默认的日前显示格式
 13     /**
 14      * 构造函数,初始化一个MimeMessage对象
 15      */
 16     public PraseMimeMessage() {
 17     }
 18     public PraseMimeMessage(MimeMessage mimeMessage) {
 19         this.mimeMessage = mimeMessage;
 20         System.out.println("create a PraseMimeMessage object........");
 21     }
 22     public void setMimeMessage(MimeMessage mimeMessage) {
 23         this.mimeMessage = mimeMessage;
 24     }
 25     /**
 26      * 获得发件人的地址和姓名
 27      */
 28     public String getFrom() throws Exception {
 29         InternetAddress address[] = (InternetAddress[]) mimeMessage.getFrom();
 30         String from = address[0].getAddress();
 31         if (from == null) from = "";
 32         String personal = address[0].getPersonal();
 33         if (personal == null) personal = "";
 34         String fromaddr = personal + "<" + from + ">";
 35         return fromaddr;
 36     }
 37     /**
 38      * 获得邮件的收件人,抄送,和密送的地址和姓名,根据所传递的参数的不同 "to"----收件人 "cc"---抄送人地址 "bcc"---密送人地址
 39      */
 40     public String getMailAddress(String type) throws Exception {
 41         String mailaddr = "";
 42         String addtype = type.toUpperCase();
 43         InternetAddress[] address = null;
 44         if (addtype.equals("TO") || addtype.equals("CC")|| addtype.equals("BCC")) {
 45             if (addtype.equals("TO")) {
 46                 address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.TO);
 47             } else if (addtype.equals("CC")) {
 48                 address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.CC);
 49             } else {
 50                 address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.BCC);
 51             }
 52             if (address != null) {
 53                 for (int i = 0; i < address.length; i++) {
 54                     String email = address[i].getAddress();
 55                     if (email == null) email = "";
 56                     else {
 57                         email = MimeUtility.decodeText(email);
 58                     }
 59                     String personal = address[i].getPersonal();
 60                     if (personal == null) personal = "";
 61                     else {
 62                         personal = MimeUtility.decodeText(personal);
 63                     }
 64                     String compositeto = personal + "<" + email + ">";
 65                     mailaddr += "," + compositeto;
 66                 }
 67                 mailaddr = mailaddr.substring(1);
 68             }
 69         } else {
 70             throw new Exception("Error emailaddr type!");
 71         }
 72         return mailaddr;
 73     }
 74     /**
 75      * 获得邮件主题
 76      */
 77     public String getSubject() throws MessagingException {
 78         String subject = "";
 79         try {
 80             subject = MimeUtility.decodeText(mimeMessage.getSubject());
 81             if (subject == null) subject = "";
 82         } catch (Exception exce) {}
 83         return subject;
 84     }
 85  
 86     /**
 87      * 获得邮件发送日期
 88      */
 89     public String getSentDate() throws Exception {
 90         Date sentdate = mimeMessage.getSentDate();
 91         SimpleDateFormat format = new SimpleDateFormat(dateformat);
 92         return format.format(sentdate);
 93     }
 94  
 95     /**
 96      * 获得邮件正文内容
 97      */
 98     public String getBodyText() {
 99         return bodytext.toString();
100     }
101     /**
102      * 解析邮件,把得到的邮件内容保存到一个StringBuffer对象中,解析邮件 主要是根据MimeType类型的不同执行不同的操作,一步一步的解析
103      */
104     public void getMailContent(Part part) throws Exception {
105         String contenttype = part.getContentType();
106         int nameindex = contenttype.indexOf("name");
107         boolean conname = false;
108         if (nameindex != -1) conname = true;
109         System.out.println("CONTENTTYPE: " + contenttype);
110         if (part.isMimeType("text/plain") && !conname) {
111             bodytext.append((String) part.getContent());
112         } else if (part.isMimeType("text/html") && !conname) {
113             bodytext.append((String) part.getContent());
114         } else if (part.isMimeType("multipart/*")) {
115             Multipart multipart = (Multipart) part.getContent();
116             int counts = multipart.getCount();
117             for (int i = 0; i < counts; i++) {
118                 getMailContent(multipart.getBodyPart(i));
119             }
120         } else if (part.isMimeType("message/rfc822")) {
121             getMailContent((Part) part.getContent());
122         } else {}
123     }
124     /**
125      * 判断此邮件是否需要回执,如果需要回执返回"true",否则返回"false"
126      */
127     public boolean getReplySign() throws MessagingException {
128         boolean replysign = false;
129         String needreply[] = mimeMessage.getHeader("Disposition-Notification-To");
130         if (needreply != null) {
131             replysign = true;
132         }
133         return replysign;
134     }
135     /**
136      * 获得此邮件的Message-ID
137      */
138     public String getMessageId() throws MessagingException {
139         return mimeMessage.getMessageID();
140     }
141     /**
142      * 【判断此邮件是否已读,如果未读返回返回false,反之返回true】
143      */
144     public boolean isNew() throws MessagingException {
145         boolean isnew = false;
146         Flags flags = ((Message) mimeMessage).getFlags();
147         Flags.Flag[] flag = flags.getSystemFlags();
148         System.out.println("flags's length: " + flag.length);
149         for (int i = 0; i < flag.length; i++) {
150             if (flag[i] == Flags.Flag.SEEN) {
151                 isnew = true;System.out.println("seen Message.......");break;
152             }
153         }
154         return isnew;
155     }
156  
157     /**
158      * 判断此邮件是否包含附件
159      */
160     public boolean isContainAttach(Part part) throws Exception {
161         boolean attachflag = false;
162         String contentType = part.getContentType();
163         if (part.isMimeType("multipart/*")) {
164             Multipart mp = (Multipart) part.getContent();
165             for (int i = 0; i < mp.getCount(); i++) {
166                 BodyPart mpart = mp.getBodyPart(i);
167                 String disposition = mpart.getDisposition();
168                 if ((disposition != null)&& ((disposition.equals(Part.ATTACHMENT)) || (disposition.equals(Part.INLINE))))
169                     attachflag = true;
170                 else if (mpart.isMimeType("multipart/*")) {
171                     attachflag = isContainAttach((Part) mpart);
172                 } else {
173                     String contype = mpart.getContentType();
174                     if (contype.toLowerCase().indexOf("application") != -1)
175                         attachflag = true;
176                      if (contype.toLowerCase().indexOf("name") != -1)
177                         attachflag = true;
178                 }
179             }
180         } else if (part.isMimeType("message/rfc822")) {
181             attachflag = isContainAttach((Part) part.getContent());
182          }
183         return attachflag;
184     }
185     /**
186      * 【保存附件】
187      */
188     public void saveAttachMent(Part part) throws Exception {
189          String fileName = "";
190         if (part.isMimeType("multipart/*")) {
191             Multipart mp = (Multipart) part.getContent();
192             for (int i = 0; i < mp.getCount(); i++) {
193                 BodyPart mpart = mp.getBodyPart(i);
194                 String disposition = mpart.getDisposition();
195                 if ((disposition != null)
196                     && ((disposition.equals(Part.ATTACHMENT)) || (disposition.equals(Part.INLINE)))) {
197                     fileName = mpart.getFileName();
198                      if (fileName.toLowerCase().indexOf("gb2312") != -1) {
199                          fileName = MimeUtility.decodeText(fileName);
200                     }
201                     saveFile(fileName, mpart.getInputStream());
202                  } else if (mpart.isMimeType("multipart/*")) {
203                     saveAttachMent(mpart);
204                 } else {
205                     fileName = mpart.getFileName();
206                     if ((fileName != null)&& (fileName.toLowerCase().indexOf("GB2312") != -1)) {
207                         fileName = MimeUtility.decodeText(fileName);
208                         saveFile(fileName, mpart.getInputStream());
209                     }
210                 }
211             }
212          } else if (part.isMimeType("message/rfc822")) {
213              saveAttachMent((Part) part.getContent());
214         }
215     /**
216      * 【设置附件存放路径】
217      */
218     public void setAttachPath(String attachpath) {
219          this.saveAttachPath = attachpath;
220     }
221     /**
222      * 【设置日期显示格式】
223      */
224     public void setDateFormat(String format) throws Exception {
225         this.dateformat = format;
226     }
227     /**
228      * 【获得附件存放路径】
229      */
230     public String getAttachPath() {
231         return saveAttachPath;
232     }
233     /**
234      * 【真正的保存附件到指定目录里】
235      */
236     private void saveFile(String fileName, InputStream in) throws Exception {
237         String osName = System.getProperty("os.name");
238          String storedir = getAttachPath();String separator = "";
239         if (osName == null)osName = "";
240         if (osName.toLowerCase().indexOf("win") != -1) {
241             separator = "\\";
242             if (storedir == null || storedir.equals(""))
243                 storedir = "c:\\tmp";
244         } else {
245             separator = "/";storedir = "/tmp";
246         }
247          File storefile = new File(storedir + separator + fileName);
248          System.out.println("storefile's path: " + storefile.toString());
249         BufferedOutputStream bos = null;
250         BufferedInputStream bis = null;
251          try {
252             bos = new BufferedOutputStream(new FileOutputStream(storefile));
253             bis = new BufferedInputStream(in);
254             int c;
255             while ((c = bis.read()) != -1) {
256                 bos.write(c);
257                 bos.flush();
258             }
259         } catch (Exception exception) {
260             exception.printStackTrace();
261              throw new Exception("文件保存失败!");
262         } finally {
263             bos.close();
264             bis.close();
265          }
266     }
267     /**
268      * PraseMimeMessage类测试
269      */
270     public static void main(String args[]) throws Exception {
271         String host = "pop3.163.com"; // 【pop.mail.yahoo.com.cn】
272         String username = "***@163.com"; 
273         String password = "***";
274          Properties props = new Properties();
275          Session session = Session.getDefaultInstance(props, null);
276         Store store = session.getStore("pop3");
277         store.connect(host, username, password);
278         Folder folder = store.getFolder("INBOX");
279         folder.open(Folder.READ_ONLY);
280         Message message[] = folder.getMessages();
281         System.out.println("Messages's length: " + message.length);
282         PraseMimeMessage pmm = null;
283         for (int i = 0; i < message.length; i++) {
284             pmm = new PraseMimeMessage((MimeMessage) message[i]);
285             System.out.println("Message " + i + " subject: " + pmm.getSubject());
286             System.out.println("Message " + i + "  containAttachment: "+ 
                              pmm.isContainAttach((Part) message[i]));
287 System.out.println("Message " + i + " form: " + pmm.getFrom()); 288 System.out.println("Message " + i + " to: "+ pmm.getMailAddress("to")); 289 pmm.setDateFormat("yy年MM月dd日 HH:mm"); 290 pmm.getMailContent((Part) message[i]); 291 System.out.println("Message " + i + " bodycontent: \r\n"+ pmm.getBodyText()); 292 File file = new File("e:\\tmp\\"); 293 if (!file.exists()) { 294 file.mkdirs(); 295 } 296 pmm.setAttachPath(file.toString()); 297 pmm.saveAttachMent((Part) message[i]); 298 } 299 } 300 301 302 /***************下载邮件保存到本地*******************/ 303 /**305 * @param date 306 * @return 307 * @throws MessagingException 308 * @throws FileNotFoundException 309 */ 310 public MimeMessage getEmailInstance(Date date, String path, String from, String to, String subjects, String cc) throws Exception{ 311 MimeMessage msg = new MimeMessage(session); 312 msg.setFrom(new InternetAddress(from)); 313 msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)) ; 314 if(null!=cc&&!"".equals(cc)){ 315 msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc)); 316 } 317 msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc)) ; 318 subjects = transferChinese(subjects); 319 msg.setSubject(subjects); 320 // 构造Multipart 321 Multipart mp = getMultipartEmailInstance(); 322 // 向Multipart添加MimeMessage 323 msg.setContent(mp); 324 msg.setSentDate(date); 325 File file = new File(path); 326 FileOutputStream fs = new FileOutputStream(file); 327 msg.writeTo(fs); 328 fs.close(); 329 return msg; 330 } 331 //处理附件 332 public Multipart getMultipartEmailInstance(){ 333 Multipart mp = new MimeMultipart(); 334 try{ 335 // 向Multipart添加正文 336 MimeBodyPart mbpContent = new MimeBodyPart(); 337 mbpContent.setContent(contents, "text/html;charset=utf-8"); 338 // 向MimeMessage添加(Multipart代表正文) 339 mp.addBodyPart(mbpContent); 340 // 向Multipart添加附件 341 Enumeration<String> efile = file.elements(); 342 while (efile.hasMoreElements()) { 343 344 MimeBodyPart mbpFile = new MimeBodyPart(); 345 filename = efile.nextElement().toString(); 346 FileDataSource fds = new FileDataSource(filename); 347 mbpFile.setDataHandler(new DataHandler(fds)); 348 // <span style="color: #ff0000;">//这个方法可以解决附件乱码问题。</span> 349 String filename= new String(MimeUtility.encodeText(new String(fds.getName().getBytes(),"GB2312"), "GB2312", "B")); 350 mbpFile.setFileName(filename); 351 // 向MimeMessage添加(Multipart代表附件) 352 mp.addBodyPart(mbpFile); 353 } 354 file.removeAllElements(); 355 }catch(Exception ce){ 356 log.error("==========邮件附件异常=================="+ce.getMessage()); 357 } 358 return mp; 359 } 360 361 //处理抄送信息 362 public String formatAddress(Address[] addr) { 363 StringBuffer sb = new StringBuffer(); 364 if (addr == null) { 365 return ""; 366 } 367 for (int i = 0; i < addr.length; i++) { 368 Address a = addr[i]; 369 if (a instanceof InternetAddress) { 370 InternetAddress ia = (InternetAddress)a; 371 sb.append(ia.getPersonal() + "<" + ia.getAddress() + ">,"); 372 } else { 373 sb.append(a.toString()); 374 } 375 } 376 if (sb.length() != 0) { 377 return sb.substring(0,sb.length()-1); 378 } 379 return ""; 380 } 381 /************************************************/ 384 }

 

不通过服务,通过 cmd 命令打开,用 java 实现

Runtime.getRuntime().exec("cmd/C" + path);  //path 根据文件实际路径设置

 

posted @ 2019-06-05 09:33  奋进的小土豆  阅读(898)  评论(0编辑  收藏  举报