Ivy does not offer an own handy API to read mails from an IMAP server, so far. No problem, you can always use the full Java ecosystem 🧤. Here you could use the official Java mail classes - javax.mail
, which are also part of the Ivy Platform. Here you see Java code which would read mails from an IMAP server and prints the subject and content to the log.
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Session;
public void readMessages() {
try {
var session = Session.getDefaultInstance(new Properties());
try (var store = session.getStore("imap")) {
store.connect("localhost", 143, "admin", "password");
try (var folder = store.getFolder("INBOX")) {
folder.open(Folder.READ_ONLY);
for (var message : folder.getMessages()) {
Ivy.log().info("Subject: " + message.getSubject());
Ivy.log().info("Content: " + message.getContent());
}
}
}
} catch (Exception ex) {
throw new RuntimeException("could not read mails", ex);
}
}
But the content won't get logged 🤯. There is always just com.sun.mail.imap.IMAPInputStream
. This is because we live in an OSGi environment. You need to change the context classloader to the one which is able to load the mail classes, for example, e.g:
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Session;
public void readMessages() {
var ccl = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(Session.class.getClassLoader());
var session = Session.getDefaultInstance(new Properties());
try (var store = session.getStore("imap")) {
store.connect("localhost", 143, "admin", "password");
try (var folder = store.getFolder("INBOX")) {
folder.open(Folder.READ_ONLY);
for (var message : folder.getMessages()) {
Ivy.log().info("Subject: " + message.getSubject());
Ivy.log().info("Content: " + message.getContent());
}
}
}
} catch (Exception ex) {
throw new RuntimeException("could not read mails", ex);
} finally {
Thread.currentThread().setContextClassLoader(ccl);
}
}
This will work and you will be able to read the content of the mails. Don't forget to set back the context classloader to the original one in a finally
block!