Red Hat Training
A Red Hat training course is available for Red Hat Fuse
208.14. 添付ファイル付きメールの利用例
このサンプルでは、メールボックスをポーリングし、メールのすべての添付ファイルをファイルとして保存します。まず、メールボックスをポーリングするルートを定義します。このサンプルは 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 を使用して添付を処理できます。