2014-09-08 8 views
1

Java 프로그램을 사용하여 Gmail 계정에서 첨부 파일을 다운로드해야합니다. Apache Camel을 사용하십시오.Gmail에서 메일 첨부 파일 다운로드, Exchange 가져 오기 [MailMessage : null]

내가 무엇입니까 실행하는 동안,

교환 [은 MailMessage : 널 (null)], 따라서 attachments.size는()

0도

@Test 
public void configureExcange() throws Exception { 

    try { 
     CamelContext context = new DefaultCamelContext(); 

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

     // PollingConsumer consumer = endpoint.createPollingConsumer(); 
     Exchange exchange = endpoint.createExchange(); 

     process(exchange); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

public void process(Exchange exchange) throws Exception { 
    // the API is a bit clunky so we need to loop 
    Map<String, DataHandler> attachments = exchange.getIn().getAttachments(); 
    if (attachments.size() > 0) { 
     for (String name : attachments.keySet()) { 
      DataHandler dh = attachments.get(name); 
      // get the file name 
      String filename = dh.getName(); 

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

      // write the data to a file 
      FileOutputStream out = new FileOutputStream(filename); 
      out.write(data); 
      out.flush(); 
      out.close(); 
     } 
    } 
} 
을 내 테스트 코드를 게시 오전

첨부 파일을 어떻게받을 수 있습니까?

답변

1

메일 계정을 폴링하는 방법을 보여주는 함수 업데이트.

@Test 
public void configureExcange() throws Exception { 

    PollingConsumer pollingConsumer = null; 
    try { 
     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"); 
      // options unseen=true, will only poll unread mails 

      //Polling an END point 
      pollingConsumer = endpoint.createPollingConsumer(); 
      pollingConsumer.start(); 
      pollingConsumer.getEndpoint().createExchange(); 

      Exchange exchange = pollingConsumer.receive(60000); 

      while (exchange != null) { 
       process(exchange); 
       //each time "pollingConsumer" will poll 1 mail at a time 
       exchange = pollingConsumer.receive(60000); 
      } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 
2

Endpoint.createExchange()는 교환을 생성하기 만하면 메일 서버에서 메시지를 가져 오지 않습니다. Gmail 서버에서 메시지를 가져 오려면 ConsumerTemplate을 사용해야합니다.

관련 문제