31.14. 使用带有附加示例的邮件
在该示例中,我们轮询邮箱并将邮件中的所有附件存储为文件。首先,我们定义一个路由来轮询邮箱。因为这个示例基于 google 邮件,它使用与 SSL 示例中显示的相同路由:
from("imaps://imap.gmail.com?username=YOUR_USERNAME@gmail.com&password=YOUR_PASSWORD"
+ "&delete=false&unseen=true&delay=60000").process(new MyMailProcessor());
我们使用处理器从 java 代码处理邮件,而不是记录邮件:
public void process(Exchange exchange) throws Exception {
// the API is a bit clunky so we need to loop
AttachmentMessage attachmentMessage = exchange.getMessage(AttachmentMessage.class);
Map<String, DataHandler> attachments = attachmentMessage.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 处理附件。