Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Inbox {
- public static final String INBOX = "INBOX";
- public static final String POP3 = "pop3";
- public Message[] inboxMessages;
- public Inbox(final MailAdress mailAdress) throws Exception {
- Folder folder = openInboxFolder(mailAdress);
- inboxMessages = folder.getMessages();
- }
- private Folder openInboxFolder(final MailAdress mailAdress) {
- try {
- Store store = getMailStore(mailAdress);
- return inboxFolderFrom(store);
- } catch (Exception ex) {
- throw new RuntimeException("java mail error, ", ex);
- }
- }
- private Folder inboxFolderFrom(Store store) throws MessagingException {
- Folder folder = store.getFolder(INBOX);
- folder.open(Folder.READ_WRITE);
- return folder;
- }
- private Store getMailStore(final MailAdress mailAdress) throws MessagingException, NoSuchProviderException {
- Session session = Session.getDefaultInstance(new Properties());
- Store store = session.getStore(POP3);
- store.connect(mailAdress.domainPart(), mailAdress.localPart(), "");
- return store;
- }
- boolean haveMeesageWithSubject(String expectedSubject) {
- for (Message message : inboxMessages) {
- if (subjectOf(message).equals(expectedSubject)) {
- return true;
- }
- }
- return false;
- }
- private Object subjectOf(Message message) {
- try {
- return message.getSubject();
- } catch (MessagingException ex) {
- throw new RuntimeException("error reading subject", ex);
- }
- }
- @Override
- public String toString() {
- StringBuilder stringInbox = new StringBuilder();
- stringInbox.append("Mails in inbox: " + inboxMessages.length + " ");
- for (Message message : inboxMessages) {
- try {
- stringInbox.append(" [subject: " + message.getSubject() + "] ");
- } catch (MessagingException ex) {
- stringInbox.append(" [error reading message: " + ex.getMessage() + "] ");
- }
- }
- return stringInbox.toString();
- }
- }
Add Comment
Please, Sign In to add comment