3

I am trying to read all mails from google mail (Gmail - imaps) account and download its attachments but I am only able to get one unread mail and its attachments.

Posting my code snippet.

// Download function 

public void  download() throws Exception {

        PollingConsumer pollingConsumer = null;
        CamelContext context = new DefaultCamelContext();

        Endpoint endpoint =
                context.getEndpoint("imaps://imap.gmail.com?username="
                        + mailId + "&password=" + password 
                        + "&delete=false&peek=false&unseen=true&consumer.delay=60000&closeFolder=false&disconnect=false");

        pollingConsumer = endpoint.createPollingConsumer();
        pollingConsumer.start();

        pollingConsumer.getEndpoint().createExchange();
        Exchange exchange = pollingConsumer.receive();

        log.info("exchange : " + exchange.getExchangeId());
        process(exchange);

}

// mail process function

public void process(Exchange exchange) throws Exception {
    Map<String, DataHandler> attachments = exchange.getIn().getAttachments();

    Message messageCopy = exchange.getIn().copy();

    if (messageCopy.getAttachments().size() > 0) {
        for (Map.Entry<String, DataHandler> entry : messageCopy.getAttachments().entrySet()) {
            DataHandler dHandler = entry.getValue();
            // get the file name
            String filename = dHandler.getName();

            // get the content and convert it to byte[]
            byte[] data =
                    exchange.getContext().getTypeConverter().convertTo(byte[].class, dHandler.getInputStream());

            FileOutputStream out = new FileOutputStream(filename);
            out.write(data);
            out.flush();
            out.close();
            log.info("Downloaded attachment, file name : " + filename);

        }
    }
}

Help me to iterate through all the mails(from inbox,unread).

Mardoz
  • 1,617
  • 1
  • 13
  • 26
Benoy Prakash
  • 436
  • 5
  • 17

1 Answers1

4

You need to run Exchange exchange = pollingConsumer.receive(); in a loop.

For e.g.

Exchange ex = pollingConsumer.receive();
while (ex != null) {
    process(ex);
    ex = pollingConsumer.receive();
}
Ravi Kiran
  • 1,139
  • 6
  • 10
  • but my question is how i can iterate through my mails. Right now i am getting 1 unread mail, but i need all unread mails from inbox – Benoy Prakash Sep 10 '14 at 11:43
  • I am sorry. I misread your question based on the title. Editing the answer for the fix. – Ravi Kiran Sep 10 '14 at 12:52
  • Gmail has disabled access by third party apps with less security through IMAP. Is there any alternative to read the gmail – user1326784 Aug 18 '22 at 00:30