EmailUtil.java 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package com.fjhx.mail.util;
  2. import com.sun.mail.imap.IMAPFolder;
  3. import com.sun.mail.imap.IMAPStore;
  4. import javax.mail.Folder;
  5. import javax.mail.MessagingException;
  6. import javax.mail.Session;
  7. import java.util.ArrayList;
  8. import java.util.HashMap;
  9. import java.util.List;
  10. import java.util.Properties;
  11. public class EmailUtil {
  12. private static final HashMap<String, String> ImapStoreId = new HashMap<>();
  13. static {
  14. ImapStoreId.put("name", "fjhx");
  15. ImapStoreId.put("version", "1.0.0");
  16. ImapStoreId.put("vendor", "fjhxClient");
  17. ImapStoreId.put("support-email", "fjhx@fjhx.com");
  18. }
  19. /**
  20. * 获取imapStore
  21. * 993
  22. */
  23. public static IMAPStore getIMAPStore(String host, Integer port, String user, String password) throws MessagingException {
  24. Properties ImapProperties = new Properties();
  25. ImapProperties.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
  26. Session session = Session.getInstance(ImapProperties);
  27. IMAPStore store = (IMAPStore) session.getStore("imap");
  28. store.connect(host, port, user, password);
  29. store.id(ImapStoreId);
  30. return store;
  31. }
  32. /**
  33. * 获取邮箱文件夹
  34. */
  35. public static List<String> getFolderNameList(IMAPStore imapStore) throws MessagingException {
  36. IMAPFolder folder = (IMAPFolder) imapStore.getDefaultFolder();
  37. Folder[] folders = folder.list();
  38. List<String> mailFolderList = new ArrayList<>();
  39. addMailFolderList(mailFolderList, folders);
  40. return mailFolderList;
  41. }
  42. private static void addMailFolderList(List<String> mailFolderList, Folder[] folders) throws MessagingException {
  43. for (Folder folder : folders) {
  44. int type = folder.getType();
  45. if (type == 2) {
  46. addMailFolderList(mailFolderList, folder.list());
  47. } else if (type == 3) {
  48. mailFolderList.add(folder.getFullName());
  49. }
  50. }
  51. }
  52. }