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