Example usage for javax.mail Folder getMessages

List of usage examples for javax.mail Folder getMessages

Introduction

In this page you can find the example usage for javax.mail Folder getMessages.

Prototype

public synchronized Message[] getMessages() throws MessagingException 

Source Link

Document

Get all Message objects from this Folder.

Usage

From source file:org.alfresco.repo.imap.RemoteLoadTester.java

public void testMailbox() {
    logger.info("Getting folder...");
    long t = System.currentTimeMillis();

    // Create empty properties
    Properties props = new Properties();
    props.setProperty("mail.imap.partialfetch", "false");

    // Get session
    Session session = Session.getDefaultInstance(props, null);

    Store store = null;//from  ww w  .  ja v  a2s .c om
    Folder folder = null;
    try {
        // Get the store
        store = session.getStore("imap");
        store.connect(REMOTE_HOST, USER_NAME, USER_PASSWORD);

        // Get folder
        folder = store.getFolder(TEST_FOLDER_NAME);
        folder.open(Folder.READ_ONLY);

        // Get directory
        Message message[] = folder.getMessages();

        for (int i = 0, n = message.length; i < n; i++) {
            message[i].getAllHeaders();

            Address[] from = message[i].getFrom();
            System.out.print(i + ": ");
            if (from != null) {
                System.out.print(message[i].getFrom()[0] + "\t");
            }
            System.out.println(message[i].getSubject());

            Object content = message[i].getContent();
            if (content instanceof MimeMultipart) {
                for (int j = 0, m = ((MimeMultipart) content).getCount(); j < m; j++) {
                    BodyPart part = ((MimeMultipart) content).getBodyPart(j);
                    Object partContent = part.getContent();

                    if (partContent instanceof String) {
                        String body = (String) partContent;
                    } else if (partContent instanceof FilterInputStream) {
                        FilterInputStream fis = (FilterInputStream) partContent;
                        BufferedInputStream bis = new BufferedInputStream(fis);

                        /* while (bis.available() > 0) 
                         {
                            bis.read();
                         }*/
                        byte[] bytes = new byte[524288];
                        while (bis.read(bytes) != -1) {
                        }
                        bis.close();
                        fis.close();
                    }
                }
            }

            int nn = 0;

        }

        t = System.currentTimeMillis() - t;
        logger.info("Time: " + t + " ms (" + t / 1000 + " s)");
        logger.info("Length: " + message.length);

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        fail(e.getMessage());
    } finally {
        // Close connection
        try {
            if (folder != null) {
                folder.close(false);
            }
        } catch (MessagingException e) {
            logger.error(e.getMessage(), e);
            fail(e.getMessage());
        }
        try {
            if (store != null) {
                store.close();
            }
        } catch (MessagingException e) {
            logger.error(e.getMessage(), e);
            fail(e.getMessage());
        }
    }

}

From source file:com.aquest.emailmarketing.web.service.BouncedEmailService.java

/**
 * Process bounces.//  w ww .j a  v  a 2  s .  c o  m
 *
 * @param protocol the protocol
 * @param host the host
 * @param port the port
 * @param userName the user name
 * @param password the password
 */
public void processBounces(String protocol, String host, String port, String userName, String password) {
    Properties properties = getServerProperties(protocol, host, port);
    Session session = Session.getDefaultInstance(properties);

    List<BounceCode> bounceCodes = bounceCodeService.getAllBounceCodes();

    try {
        // connects to the message store
        Store store = session.getStore(protocol);
        System.out.println(userName);
        System.out.println(password);
        System.out.println(userName.length());
        System.out.println(password.length());
        //store.connect(userName, password);
        //TODO: ispraviti username i password da idu iz poziva a ne hardcoded
        store.connect("bojan.dimic@aquest-solutions.com", "bg181076");

        // opens the inbox folder
        Folder folderInbox = store.getFolder("INBOX");
        folderInbox.open(Folder.READ_ONLY);

        // fetches new messages from server
        Message[] messages = folderInbox.getMessages();

        for (int i = 0; i < messages.length; i++) {
            BouncedEmail bouncedEmail = new BouncedEmail();
            Message msg = messages[i];
            Address[] fromAddress = msg.getFrom();
            String from = fromAddress[0].toString();
            String failedAddress = "";
            Enumeration<?> headers = messages[i].getAllHeaders();
            while (headers.hasMoreElements()) {
                Header h = (Header) headers.nextElement();
                //System.out.println(h.getName() + ":" + h.getValue());
                //System.out.println("");                
                String mID = h.getName();
                if (mID.contains("X-Failed-Recipients")) {
                    failedAddress = h.getValue();
                }
            }
            String subject = msg.getSubject();
            String toList = parseAddresses(msg.getRecipients(RecipientType.TO));
            String ccList = parseAddresses(msg.getRecipients(RecipientType.CC));
            String sentDate = msg.getSentDate().toString();

            String contentType = msg.getContentType();
            String messageContent = "";

            if (contentType.contains("text/plain") || contentType.contains("text/html")) {
                try {
                    Object content = msg.getContent();
                    if (content != null) {
                        messageContent = content.toString();
                    }
                } catch (Exception ex) {
                    messageContent = "[Error downloading content]";
                    ex.printStackTrace();
                }
            }

            String bounceReason = "Unknown reason";

            for (BounceCode bounceCode : bounceCodes) {
                if (messageContent.contains(bounceCode.getCode())) {
                    bounceReason = bounceCode.getExplanation();
                }
            }

            //                if(messageContent.contains(" 550 ") || messageContent.contains(" 550-")) {bounceReason="Users mailbox was unavailable (such as not found)";}
            //                if(messageContent.contains(" 554 ") || messageContent.contains(" 554-")) {bounceReason="The transaction failed for some unstated reason.";}
            //                
            //                // enhanced bounce codes
            //                if(messageContent.contains("5.0.0")) {bounceReason="Unknown issue";}
            //                if(messageContent.contains("5.1.0")) {bounceReason="Other address status";}
            //                if(messageContent.contains("5.1.1")) {bounceReason="Bad destination mailbox address";}
            //                if(messageContent.contains("5.1.2")) {bounceReason="Bad destination system address";}
            //                if(messageContent.contains("5.1.3")) {bounceReason="Bad destination mailbox address syntax";}
            //                if(messageContent.contains("5.1.4")) {bounceReason="Destination mailbox address ambiguous";}
            //                if(messageContent.contains("5.1.5")) {bounceReason="Destination mailbox address valid";}
            //                if(messageContent.contains("5.1.6")) {bounceReason="Mailbox has moved";}
            //                if(messageContent.contains("5.7.1")) {bounceReason="Delivery not authorized, message refused";}

            // print out details of each message
            System.out.println("Message #" + (i + 1) + ":");
            System.out.println("\t From: " + from);
            System.out.println("\t To: " + toList);
            System.out.println("\t CC: " + ccList);
            System.out.println("\t Subject: " + subject);
            System.out.println("\t Sent Date: " + sentDate);
            System.out.println("\t X-Failed-Recipients:" + failedAddress);
            System.out.println("\t Content Type:" + contentType);
            System.out.println("\t Bounce reason:" + bounceReason);
            //System.out.println("\t Message: " + messageContent);

            bouncedEmail.setEmail_address(failedAddress);
            bouncedEmail.setBounce_reason(bounceReason);

            //Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
            SimpleDateFormat sqlFormat = new SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH);
            //String strDate = date.toString();
            System.out.println(sentDate);
            Date dt = null;
            //Date nd = null;
            try {
                dt = formatter.parse(sentDate);
                //nd = sqlFormat.parse(dt.toString());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            System.out.println("Date " + dt.toString());
            //System.out.println("Date " + nd.toString());
            System.out.println(new Timestamp(new Date().getTime()));
            bouncedEmail.setSend_date(dt);
            bouncedEmailDao.saveOrUpdate(bouncedEmail);
        }

        // disconnect
        folderInbox.close(false);
        store.close();
    } catch (NoSuchProviderException ex) {
        System.out.println("No provider for protocol: " + protocol);
        ex.printStackTrace();
    } catch (MessagingException ex) {
        System.out.println("Could not connect to the message store");
        ex.printStackTrace();
    }
}

From source file:com.intranet.intr.inbox.EmpControllerInbox.java

public int todosCorreosNum(String name) {
    int num = 0;/*from www  .  j  a  v  a 2  s.  c o  m*/
    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imaps");
    try {
        users u = usuarioService.getByLogin(name);
        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore("imaps");
        store.connect("imap.1and1.es", u.getCorreoUsuario(), u.getCorreoContreasenna());
        System.out.println("ola" + store);
        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_ONLY);
        Message msg[] = inbox.getMessages();
        System.out.println("MAILS: " + msg.length);
        System.out.println(" " + msg.length);
        num = msg.length;
    } catch (Exception ex) {
        System.out.println(ex.toString());
    }
    return num;
}

From source file:de.saly.elasticsearch.imap.AbstractIMAPRiverUnitTest.java

protected void deleteMailsFromUserMailbox(final Properties props, final String folderName, final int start,
        final int deleteCount, final String user, final String password) throws MessagingException {
    final Store store = Session.getInstance(props).getStore();

    store.connect(user, password);//from   w  w w  .  j ava 2  s .c  om
    checkStoreForTestConnection(store);
    final Folder f = store.getFolder(folderName);
    f.open(Folder.READ_WRITE);

    final int msgCount = f.getMessageCount();

    final Message[] m = deleteCount == -1 ? f.getMessages()
            : f.getMessages(start, Math.min(msgCount, deleteCount + start - 1));
    int d = 0;

    for (final Message message : m) {
        message.setFlag(Flag.DELETED, true);
        logger.info("Delete msgnum: {} with sid {}", message.getMessageNumber(), message.getSubject());
        d++;
    }

    f.close(true);
    logger.info("Deleted " + d + " messages");
    store.close();

}

From source file:org.apache.synapse.transport.mail.MailEchoRawXMLTest.java

private Object getMessage(String requestMsgId) {
    Session session = Session.getInstance(props, null);
    session.setDebug(log.isTraceEnabled());
    Store store = null;/*from w w  w.  j av  a2 s.c  om*/

    try {
        store = session.getStore("pop3");
        store.connect(username, password);
        Folder folder = store.getFolder(MailConstants.DEFAULT_FOLDER);
        folder.open(Folder.READ_WRITE);
        Message[] msgs = folder.getMessages();
        log.debug(msgs.length + " replies in reply mailbox");
        for (Message m : msgs) {
            String[] inReplyTo = m.getHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO);
            log.debug("Got reply to : " + Arrays.toString(inReplyTo));
            if (inReplyTo != null && inReplyTo.length > 0) {
                for (int j = 0; j < inReplyTo.length; j++) {
                    if (requestMsgId.equals(inReplyTo[j])) {
                        m.setFlag(Flags.Flag.DELETED, true);
                        return m.getContent();
                    }
                }
            }
            m.setFlag(Flags.Flag.DELETED, true);
        }
        folder.close(true);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (store != null) {
            try {
                store.close();
            } catch (MessagingException ignore) {
            }
            store = null;
        }
    }
    return null;
}

From source file:ru.retbansk.utils.scheduled.impl.ReadEmailAndConvertToXmlSpringImpl.java

/**
 * Loads email properties, reads email messages, 
 * converts their multipart bodies into string,
 * send error emails if message doesn't contain valid report and at last returns a reversed Set of the Valid Reports
 * <p><b> deletes messages// ww  w . jav  a2  s.com
 * @see #readEmail()
 * @see #convertToXml(HashSet)
 * @see ru.retbansk.utils.scheduled.ReplyManager
 * @return HashSet<DayReport> of the Valid Day Reports
 */
@Override
public HashSet<DayReport> readEmail() throws Exception {

    Properties prop = loadProperties();
    String host = prop.getProperty("host");
    String user = prop.getProperty("user");
    String password = prop.getProperty("password");
    path = prop.getProperty("path");

    // Get system properties
    Properties properties = System.getProperties();

    // Get the default Session object.
    Session session = Session.getDefaultInstance(properties);

    // Get a Store object that implements the specified protocol.
    Store store = session.getStore("pop3");

    // Connect to the current host using the specified username and
    // password.
    store.connect(host, user, password);

    // Create a Folder object corresponding to the given name.
    Folder folder = store.getFolder("inbox");

    // Open the Folder.
    folder.open(Folder.READ_WRITE);
    HashSet<DayReport> dayReportSet = new HashSet<DayReport>();
    try {

        // Getting messages from the folder
        Message[] message = folder.getMessages();
        // Reversing the order in the array with the use of Set to make the last one final
        Collections.reverse(Arrays.asList(message));

        // Reading messages.
        String body;
        for (int i = 0; i < message.length; i++) {
            DayReport dayReport = null;
            dayReport = new DayReport();
            dayReport.setPersonId(((InternetAddress) message[i].getFrom()[0]).getAddress());
            Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+3"));
            calendar.setTime(message[i].getSentDate());
            dayReport.setCalendar(calendar);
            dayReport.setSubject(message[i].getSubject());
            List<TaskReport> reportList = null;

            //Release the string from email message body
            body = "";
            Object content = message[i].getContent();
            if (content instanceof java.lang.String) {
                body = (String) content;
            } else if (content instanceof Multipart) {
                Multipart mp = (Multipart) content;

                for (int j = 0; j < mp.getCount(); j++) {
                    Part part = mp.getBodyPart(j);

                    String disposition = part.getDisposition();

                    if (disposition == null) {
                        MimeBodyPart mbp = (MimeBodyPart) part;
                        if (mbp.isMimeType("text/plain")) {
                            body += (String) mbp.getContent();
                        }
                    } else if ((disposition != null)
                            && (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE))) {
                        MimeBodyPart mbp = (MimeBodyPart) part;
                        if (mbp.isMimeType("text/plain")) {
                            body += (String) mbp.getContent();
                        }
                    }
                }
            }

            //Put the string (body of email message) and get list of valid reports else send error
            reportList = new ArrayList<TaskReport>();
            reportList = giveValidReports(body, message[i].getSentDate());
            //Check for valid day report. To be valid it should have size of reportList > 0.
            if (reportList.size() > 0) {
                // adding valid ones to Set
                dayReport.setReportList(reportList);
                dayReportSet.add(dayReport);
            } else {
                // This message doesn't have valid reports. Sending an error reply.
                logger.info("Invalid Day Report detected. Sending an error reply");
                ReplyManager man = new ReplyManagerSimpleImpl();
                man.sendError(dayReport);
            }
            // Delete message
            message[i].setFlag(Flags.Flag.DELETED, true);
        }

    } finally {
        // true tells the mail server to expunge deleted messages.
        folder.close(true);
        store.close();
    }

    return dayReportSet;
}

From source file:org.gcaldaemon.core.GmailEntry.java

public final GmailMessage[] receive(String title) throws Exception {

    // Open 'INBOX' folder
    Folder inbox = mailbox.getFolder("INBOX");
    inbox.open(Folder.READ_WRITE);//from  www  .  j a  va  2 s. c  o m
    Message[] messages = inbox.getMessages();
    if (messages == null || messages.length == 0) {
        return new GmailMessage[0];
    }

    // Loop on messages
    LinkedList list = new LinkedList();
    for (int i = 0; i < messages.length; i++) {
        Message msg = messages[i];
        if (!msg.isSet(Flag.SEEN)) {
            String subject = msg.getSubject();
            if (title == null || title.length() == 0 || title.equals(subject)) {
                GmailMessage gm = new GmailMessage();
                Address[] from = msg.getFrom();
                msg.setFlag(Flag.SEEN, true);
                if (from == null || from.length == 0) {
                    continue;
                }
                gm.subject = subject;
                gm.from = from[0].toString();
                gm.memo = String.valueOf(msg.getContent());
                list.addLast(gm);
            }
        }
    }
    inbox.close(true);

    // Return the array of the messages
    GmailMessage[] array = new GmailMessage[list.size()];
    list.toArray(array);
    return array;
}

From source file:org.apache.syncope.core.notification.NotificationTest.java

private boolean verifyMail(final String sender, final String subject) throws Exception {
    LOG.info("Waiting for notification to be sent...");
    try {//w w w.ja va 2  s .c  o  m
        Thread.sleep(1000);
    } catch (InterruptedException e) {
    }

    boolean found = false;
    Session session = Session.getDefaultInstance(System.getProperties());
    Store store = session.getStore("pop3");
    store.connect(pop3Host, pop3Port, mailAddress, mailPassword);

    Folder inbox = store.getFolder("INBOX");
    assertNotNull(inbox);
    inbox.open(Folder.READ_WRITE);

    Message[] messages = inbox.getMessages();
    for (int i = 0; i < messages.length; i++) {
        if (sender.equals(messages[i].getFrom()[0].toString()) && subject.equals(messages[i].getSubject())) {
            found = true;
            messages[i].setFlag(Flag.DELETED, true);
        }
    }

    inbox.close(true);
    store.close();
    return found;
}

From source file:com.naryx.tagfusion.cfm.mail.cfPOP3.java

private void deleteMessagesFromServer(cfSession _Session) throws cfmRunTimeException {

    //--[ Get Message Store
    Store popStore = openConnection(_Session);

    //--[ Open up the Folder:INBOX and retrieve the headers
    Folder popFolder = openFolder(_Session, popStore);

    try {//from  ww  w .ja  va  2 s  . c  o  m
        Message[] listOfMessages = popFolder.getMessages();
        FetchProfile fProfile = new FetchProfile();
        fProfile.add(FetchProfile.Item.ENVELOPE);

        if (containsAttribute("UID")) {
            String[] messageUIDList = getMessageUIDList(getDynamic(_Session, "UID").getString());
            fProfile.add(UIDFolder.FetchProfileItem.UID);
            popFolder.fetch(listOfMessages, fProfile);

            for (int x = 0; x < listOfMessages.length; x++) {
                if (messageUIDValid(messageUIDList, getMessageUID(popFolder, listOfMessages[x]))) {
                    listOfMessages[x].setFlag(Flags.Flag.DELETED, true);
                }
            }

        } else if (containsAttribute("MESSAGENUMBER")) {
            int[] messageList = getMessageList(getDynamic(_Session, "MESSAGENUMBER").getString());
            popFolder.fetch(listOfMessages, fProfile);

            for (int x = 0; x < listOfMessages.length; x++) {
                if (messageIDValid(messageList, listOfMessages[x].getMessageNumber())) {
                    listOfMessages[x].setFlag(Flags.Flag.DELETED, true);
                }
            }

        } else {
            throw newRunTimeException(
                    "Either MESSAGENUMBER or UID attribute must be specified when ACTION=DELETE");
        }
    } catch (Exception ignore) {
    }

    //--[ Close off the folder      
    closeFolder(popFolder);
    closeConnection(popStore);
}

From source file:be.ibridge.kettle.job.entry.getpop.JobEntryGetPOP.java

public Message[] getPOPMessages(Folder folder, int retrievemails) throws Exception {
    // Get  messages ..
    try {//w  w w  . j av  a 2  s. c  o  m
        int newMsgs = folder.getNewMessageCount();
        int msgCount = folder.getMessageCount();
        Message msgsAll[] = folder.getMessages();

        if (retrievemails == 1) {
            Message msgsNew[] = folder.getMessages(msgCount - newMsgs + 1, msgCount);
            return (msgsNew);

        } else {
            return (msgsAll);
        }
    }

    catch (Exception e) {
        return null;
    }

}