用Java代码凭借邮箱及账号获取邮箱内容,这个需要不是很常见,笔者是突然有一需求要把邮件内容展示在网页端上,然后不断的百度,遇到了很多坑或者一些资料不全的文档,最终终终于找到了一个质量非常高的代码,这篇文章也是想把这个demo进行收录,防止源文档被删掉。

代码展示

原文作者:一曲破东风@CSDN
代码的注释相对来说是完善的,我就暂时不做完善啦😁,如果有需要欢迎在评论区评论。🤔

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