Мне нужно загрузить вложения из учетных записей Gmail с помощью java-программы. Использование Apache Camel.
Во время работы я получаю,
Exchange [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();
}
}
}
Как я могу получить вложения?
Обновление функции, показывающей, как опросить учетную запись электронной почты.
@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();
}
}
Endpoint.createExchange() просто создает обмен для использования, он не вытягивает сообщение с почтового сервера. Вам нужно использовать ConsumerTemplate, чтобы вытащить сообщение с сервера gmail.