217.15. 첨부 파일 샘플과 함께 메일 사용

이 예제에서는 사서함을 폴링하고 메일의 모든 첨부 파일을 파일로 저장합니다.In this sample we poll a mailbox and store all attachments from the mails as files. 먼저, 사서함을 폴링할 경로를 정의합니다. 이 샘플은 Google 메일을 기반으로 하므로 SSL 샘플에 표시된 것과 동일한 경로를 사용합니다.

from("imaps://imap.gmail.com?username=YOUR_USERNAME@gmail.com&password=YOUR_PASSWORD"
    + "&delete=false&unseen=true&consumer.delay=60000").process(new MyMailProcessor());

메일을 로깅하는 대신 Java 코드에서 메일을 처리할 수 있는 프로세서를 사용합니다.

    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();
            }
        }
   }

첨부 파일을 처리하는 API가 약간 문제이지만 javax.activation.DataHandler 를 가져올 수 있으므로 표준 API를 사용하여 첨부 파일을 처리할 수 있습니다.