Guest User

Untitled

a guest
Jul 16th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. public class Inbox {
  2.  
  3. public static final String INBOX = "INBOX";
  4. public static final String POP3 = "pop3";
  5. public Message[] inboxMessages;
  6.  
  7. public Inbox(final MailAdress mailAdress) throws Exception {
  8. Folder folder = openInboxFolder(mailAdress);
  9. inboxMessages = folder.getMessages();
  10. }
  11.  
  12. private Folder openInboxFolder(final MailAdress mailAdress) {
  13. try {
  14. Store store = getMailStore(mailAdress);
  15. return inboxFolderFrom(store);
  16. } catch (Exception ex) {
  17. throw new RuntimeException("java mail error, ", ex);
  18. }
  19. }
  20.  
  21. private Folder inboxFolderFrom(Store store) throws MessagingException {
  22. Folder folder = store.getFolder(INBOX);
  23. folder.open(Folder.READ_WRITE);
  24. return folder;
  25. }
  26.  
  27. private Store getMailStore(final MailAdress mailAdress) throws MessagingException, NoSuchProviderException {
  28. Session session = Session.getDefaultInstance(new Properties());
  29. Store store = session.getStore(POP3);
  30. store.connect(mailAdress.domainPart(), mailAdress.localPart(), "");
  31. return store;
  32. }
  33.  
  34. boolean haveMeesageWithSubject(String expectedSubject) {
  35. for (Message message : inboxMessages) {
  36. if (subjectOf(message).equals(expectedSubject)) {
  37. return true;
  38. }
  39. }
  40. return false;
  41. }
  42.  
  43. private Object subjectOf(Message message) {
  44. try {
  45. return message.getSubject();
  46. } catch (MessagingException ex) {
  47. throw new RuntimeException("error reading subject", ex);
  48. }
  49. }
  50.  
  51. @Override
  52. public String toString() {
  53. StringBuilder stringInbox = new StringBuilder();
  54. stringInbox.append("Mails in inbox: " + inboxMessages.length + " ");
  55. for (Message message : inboxMessages) {
  56. try {
  57. stringInbox.append(" [subject: " + message.getSubject() + "] ");
  58. } catch (MessagingException ex) {
  59. stringInbox.append(" [error reading message: " + ex.getMessage() + "] ");
  60. }
  61. }
  62. return stringInbox.toString();
  63. }
  64.  
  65. }
Add Comment
Please, Sign In to add comment