Java教程

javamail之使用 POP3 协议接收并解析电子邮件

Java1000个问题 小海豚博客管理员 2020-04-20 21:18:33.0 230 0条

POP协议支持离线邮件处理,当邮件发送到服务器后,电子邮件客户端会调用邮件客户端程序,下载所有未阅读的电子邮件(这种离线访问模式是一种存储转发服务).当邮件从邮件服务器发送到个人计算机上,同时邮件服务器会删除该邮件(但是很多POP3服务器都支持“下载邮件,服务器并不删除邮件”,也就是说在POP3中改进了POP协议)

特性

  1. POP3协议默认端口:110
  2. POP3协议默认传输协议:TCP
  3. POP3协议适用的构架结构:C/S
  4. POP3协议的访问模式:离线访问

使用 POP3 协议接收邮件

javamail之使用 POP3 协议接收并解析电子邮件,可以用在springboot中

  1. import java.io.BufferedInputStream;
  2. import java.io.BufferedOutputStream;
  3. import java.io.File;
  4. import java.io.FileNotFoundException;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7. import java.io.InputStream;
  8. import java.io.UnsupportedEncodingException;
  9. import java.text.SimpleDateFormat;
  10. import java.util.Date;
  11. import java.util.Properties;
  12. import javax.mail.Address;
  13. import javax.mail.BodyPart;
  14. import javax.mail.Flags;
  15. import javax.mail.Folder;
  16. import javax.mail.Message;
  17. import javax.mail.MessagingException;
  18. import javax.mail.Multipart;
  19. import javax.mail.Part;
  20. import javax.mail.Session;
  21. import javax.mail.Store;
  22. import javax.mail.internet.InternetAddress;
  23. import javax.mail.internet.MimeMessage;
  24. import javax.mail.internet.MimeMultipart;
  25. import javax.mail.internet.MimeUtility;
  26. /**
  27. * 使用POP3协议接收邮件
  28. */
  29. public class POP3ReceiveMailTest {
  30. public static void main(String[] args) throws Exception {
  31. receive();
  32. }
  33. /**
  34. * 接收邮件
  35. */
  36. public static void receive() throws Exception {
  37. // 准备连接服务器的会话信息
  38. Properties props = new Properties();
  39. props.setProperty("mail.store.protocol", "pop3"); // 协议
  40. props.setProperty("mail.pop3.port", "110"); // 端口
  41. props.setProperty("mail.pop3.host", "pop3.163.com"); // pop3服务器
  42. // 创建Session实例对象
  43. Session session = Session.getInstance(props);
  44. Store store = session.getStore("pop3");
  45. store.connect("xyang0917@163.com", "123456abc");
  46. // 获得收件箱
  47. Folder folder = store.getFolder("INBOX");
  48. /* Folder.READ_ONLY:只读权限
  49. * Folder.READ_WRITE:可读可写(可以修改邮件的状态)
  50. */
  51. folder.open(Folder.READ_WRITE); //打开收件箱
  52. // 由于POP3协议无法获知邮件的状态,所以getUnreadMessageCount得到的是收件箱的邮件总数
  53. System.out.println("未读邮件数: " + folder.getUnreadMessageCount());
  54. // 由于POP3协议无法获知邮件的状态,所以下面得到的结果始终都是为0
  55. System.out.println("删除邮件数: " + folder.getDeletedMessageCount());
  56. System.out.println("新邮件: " + folder.getNewMessageCount());
  57. // 获得收件箱中的邮件总数
  58. System.out.println("邮件总数: " + folder.getMessageCount());
  59. // 得到收件箱中的所有邮件,并解析
  60. Message[] messages = folder.getMessages();
  61. parseMessage(messages);
  62. //释放资源
  63. folder.close(true);
  64. store.close();
  65. }
  66. /**
  67. * 解析邮件
  68. * @param messages 要解析的邮件列表
  69. */
  70. public static void parseMessage(Message ...messages) throws MessagingException, IOException {
  71. if (messages == null || messages.length < 1)
  72. throw new MessagingException("未找到要解析的邮件!");
  73. // 解析所有邮件
  74. for (int i = 0, count = messages.length; i < count; i++) {
  75. MimeMessage msg = (MimeMessage) messages[i];
  76. System.out.println("------------------解析第" + msg.getMessageNumber() + "封邮件-------------------- ");
  77. System.out.println("主题: " + getSubject(msg));
  78. System.out.println("发件人: " + getFrom(msg));
  79. System.out.println("收件人:" + getReceiveAddress(msg, null));
  80. System.out.println("发送时间:" + getSentDate(msg, null));
  81. System.out.println("是否已读:" + isSeen(msg));
  82. System.out.println("邮件优先级:" + getPriority(msg));
  83. System.out.println("是否需要回执:" + isReplySign(msg));
  84. System.out.println("邮件大小:" + msg.getSize() * 1024 + "kb");
  85. boolean isContainerAttachment = isContainAttachment(msg);
  86. System.out.println("是否包含附件:" + isContainerAttachment);
  87. if (isContainerAttachment) {
  88. saveAttachment(msg, "c:\\mailtmp\\"+msg.getSubject() + "_"); //保存附件
  89. }
  90. StringBuffer content = new StringBuffer(30);
  91. getMailTextContent(msg, content);
  92. System.out.println("邮件正文:" + (content.length() > 100 ? content.substring(0,100) + "..." : content));
  93. System.out.println("------------------第" + msg.getMessageNumber() + "封邮件解析结束-------------------- ");
  94. System.out.println();
  95. }
  96. }
  97. /**
  98. * 获得邮件主题
  99. * @param msg 邮件内容
  100. * @return 解码后的邮件主题
  101. */
  102. public static String getSubject(MimeMessage msg) throws UnsupportedEncodingException, MessagingException {
  103. return MimeUtility.decodeText(msg.getSubject());
  104. }
  105. /**
  106. * 获得邮件发件人
  107. * @param msg 邮件内容
  108. * @return 姓名 <Email地址>
  109. * @throws MessagingException
  110. * @throws UnsupportedEncodingException
  111. */
  112. public static String getFrom(MimeMessage msg) throws MessagingException, UnsupportedEncodingException {
  113. String from = "";
  114. Address[] froms = msg.getFrom();
  115. if (froms.length < 1)
  116. throw new MessagingException("没有发件人!");
  117. InternetAddress address = (InternetAddress) froms[0];
  118. String person = address.getPersonal();
  119. if (person != null) {
  120. person = MimeUtility.decodeText(person) + " ";
  121. } else {
  122. person = "";
  123. }
  124. from = person + "<" + address.getAddress() + ">";
  125. return from;
  126. }
  127. /**
  128. * 根据收件人类型,获取邮件收件人、抄送和密送地址。如果收件人类型为空,则获得所有的收件人
  129. * <p>Message.RecipientType.TO 收件人</p>
  130. * <p>Message.RecipientType.CC 抄送</p>
  131. * <p>Message.RecipientType.BCC 密送</p>
  132. * @param msg 邮件内容
  133. * @param type 收件人类型
  134. * @return 收件人1 <邮件地址1>, 收件人2 <邮件地址2>, ...
  135. * @throws MessagingException
  136. */
  137. public static String getReceiveAddress(MimeMessage msg, Message.RecipientType type) throws MessagingException {
  138. StringBuffer receiveAddress = new StringBuffer();
  139. Address[] addresss = null;
  140. if (type == null) {
  141. addresss = msg.getAllRecipients();
  142. } else {
  143. addresss = msg.getRecipients(type);
  144. }
  145. if (addresss == null || addresss.length < 1)
  146. throw new MessagingException("没有收件人!");
  147. for (Address address : addresss) {
  148. InternetAddress internetAddress = (InternetAddress)address;
  149. receiveAddress.append(internetAddress.toUnicodeString()).append(",");
  150. }
  151. receiveAddress.deleteCharAt(receiveAddress.length()-1); //删除最后一个逗号
  152. return receiveAddress.toString();
  153. }
  154. /**
  155. * 获得邮件发送时间
  156. * @param msg 邮件内容
  157. * @return yyyy年mm月dd日 星期X HH:mm
  158. * @throws MessagingException
  159. */
  160. public static String getSentDate(MimeMessage msg, String pattern) throws MessagingException {
  161. Date receivedDate = msg.getSentDate();
  162. if (receivedDate == null)
  163. return "";
  164. if (pattern == null || "".equals(pattern))
  165. pattern = "yyyy年MM月dd日 E HH:mm ";
  166. return new SimpleDateFormat(pattern).format(receivedDate);
  167. }
  168. /**
  169. * 判断邮件中是否包含附件
  170. * @param msg 邮件内容
  171. * @return 邮件中存在附件返回true,不存在返回false
  172. * @throws MessagingException
  173. * @throws IOException
  174. */
  175. public static boolean isContainAttachment(Part part) throws MessagingException, IOException {
  176. boolean flag = false;
  177. if (part.isMimeType("multipart/*")) {
  178. MimeMultipart multipart = (MimeMultipart) part.getContent();
  179. int partCount = multipart.getCount();
  180. for (int i = 0; i < partCount; i++) {
  181. BodyPart bodyPart = multipart.getBodyPart(i);
  182. String disp = bodyPart.getDisposition();
  183. if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
  184. flag = true;
  185. } else if (bodyPart.isMimeType("multipart/*")) {
  186. flag = isContainAttachment(bodyPart);
  187. } else {
  188. String contentType = bodyPart.getContentType();
  189. if (contentType.indexOf("application") != -1) {
  190. flag = true;
  191. }
  192. if (contentType.indexOf("name") != -1) {
  193. flag = true;
  194. }
  195. }
  196. if (flag) break;
  197. }
  198. } else if (part.isMimeType("message/rfc822")) {
  199. flag = isContainAttachment((Part)part.getContent());
  200. }
  201. return flag;
  202. }
  203. /**
  204. * 判断邮件是否已读
  205. * @param msg 邮件内容
  206. * @return 如果邮件已读返回true,否则返回false
  207. * @throws MessagingException
  208. */
  209. public static boolean isSeen(MimeMessage msg) throws MessagingException {
  210. return msg.getFlags().contains(Flags.Flag.SEEN);
  211. }
  212. /**
  213. * 判断邮件是否需要阅读回执
  214. * @param msg 邮件内容
  215. * @return 需要回执返回true,否则返回false
  216. * @throws MessagingException
  217. */
  218. public static boolean isReplySign(MimeMessage msg) throws MessagingException {
  219. boolean replySign = false;
  220. String[] headers = msg.getHeader("Disposition-Notification-To");
  221. if (headers != null)
  222. replySign = true;
  223. return replySign;
  224. }
  225. /**
  226. * 获得邮件的优先级
  227. * @param msg 邮件内容
  228. * @return 1(High):紧急 3:普通(Normal) 5:低(Low)
  229. * @throws MessagingException
  230. */
  231. public static String getPriority(MimeMessage msg) throws MessagingException {
  232. String priority = "普通";
  233. String[] headers = msg.getHeader("X-Priority");
  234. if (headers != null) {
  235. String headerPriority = headers[0];
  236. if (headerPriority.indexOf("1") != -1 || headerPriority.indexOf("High") != -1)
  237. priority = "紧急";
  238. else if (headerPriority.indexOf("5") != -1 || headerPriority.indexOf("Low") != -1)
  239. priority = "低";
  240. else
  241. priority = "普通";
  242. }
  243. return priority;
  244. }
  245. /**
  246. * 获得邮件文本内容
  247. * @param part 邮件体
  248. * @param content 存储邮件文本内容的字符串
  249. * @throws MessagingException
  250. * @throws IOException
  251. */
  252. public static void getMailTextContent(Part part, StringBuffer content) throws MessagingException, IOException {
  253. //如果是文本类型的附件,通过getContent方法可以取到文本内容,但这不是我们需要的结果,所以在这里要做判断
  254. boolean isContainTextAttach = part.getContentType().indexOf("name") > 0;
  255. if (part.isMimeType("text/*") && !isContainTextAttach) {
  256. content.append(part.getContent().toString());
  257. } else if (part.isMimeType("message/rfc822")) {
  258. getMailTextContent((Part)part.getContent(),content);
  259. } else if (part.isMimeType("multipart/*")) {
  260. Multipart multipart = (Multipart) part.getContent();
  261. int partCount = multipart.getCount();
  262. for (int i = 0; i < partCount; i++) {
  263. BodyPart bodyPart = multipart.getBodyPart(i);
  264. getMailTextContent(bodyPart,content);
  265. }
  266. }
  267. }
  268. /**
  269. * 保存附件
  270. * @param part 邮件中多个组合体中的其中一个组合体
  271. * @param destDir 附件保存目录
  272. * @throws UnsupportedEncodingException
  273. * @throws MessagingException
  274. * @throws FileNotFoundException
  275. * @throws IOException
  276. */
  277. public static void saveAttachment(Part part, String destDir) throws UnsupportedEncodingException, MessagingException,
  278. FileNotFoundException, IOException {
  279. if (part.isMimeType("multipart/*")) {
  280. Multipart multipart = (Multipart) part.getContent(); //复杂体邮件
  281. //复杂体邮件包含多个邮件体
  282. int partCount = multipart.getCount();
  283. for (int i = 0; i < partCount; i++) {
  284. //获得复杂体邮件中其中一个邮件体
  285. BodyPart bodyPart = multipart.getBodyPart(i);
  286. //某一个邮件体也有可能是由多个邮件体组成的复杂体
  287. String disp = bodyPart.getDisposition();
  288. if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
  289. InputStream is = bodyPart.getInputStream();
  290. saveFile(is, destDir, decodeText(bodyPart.getFileName()));
  291. } else if (bodyPart.isMimeType("multipart/*")) {
  292. saveAttachment(bodyPart,destDir);
  293. } else {
  294. String contentType = bodyPart.getContentType();
  295. if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) {
  296. saveFile(bodyPart.getInputStream(), destDir, decodeText(bodyPart.getFileName()));
  297. }
  298. }
  299. }
  300. } else if (part.isMimeType("message/rfc822")) {
  301. saveAttachment((Part) part.getContent(),destDir);
  302. }
  303. }
  304. /**
  305. * 读取输入流中的数据保存至指定目录
  306. * @param is 输入流
  307. * @param fileName 文件名
  308. * @param destDir 文件存储目录
  309. * @throws FileNotFoundException
  310. * @throws IOException
  311. */
  312. private static void saveFile(InputStream is, String destDir, String fileName)
  313. throws FileNotFoundException, IOException {
  314. BufferedInputStream bis = new BufferedInputStream(is);
  315. BufferedOutputStream bos = new BufferedOutputStream(
  316. new FileOutputStream(new File(destDir + fileName)));
  317. int len = -1;
  318. while ((len = bis.read()) != -1) {
  319. bos.write(len);
  320. bos.flush();
  321. }
  322. bos.close();
  323. bis.close();
  324. }
  325. /**
  326. * 文本解码
  327. * @param encodeText 解码MimeUtility.encodeText(String text)方法编码后的文本
  328. * @return 解码后的文本
  329. * @throws UnsupportedEncodingException
  330. */
  331. public static String decodeText(String encodeText) throws UnsupportedEncodingException {
  332. if (encodeText == null || "".equals(encodeText)) {
  333. return "";
  334. } else {
  335. return MimeUtility.decodeText(encodeText);
  336. }
  337. }
  338. }
暗锚,解决锚点偏移

文章评论

嘿,来试试登录吧!