Hi,
In most cases, working with IMAP involves monitoring the mailbox and reacting to new messages. This doesn’t require much coding and can be easily implemented in a project.
Here is the example. Is uses the implementation 'org.eclipse.angus:angus-mail'
as an implementation of Jakarta Mail specification.
You need to define a bean for mail Session
and a bean that will read the messages: MailReader
.
import jakarta.mail.Session;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
@Configuration
public class MailReaderConfiguration {
@Bean
Session mailSession(ImapProperties imapProperties) {
Properties properties = new Properties();
String protocol = imapProperties.getProtocol();
properties.put("mail.store.protocol", protocol);
properties.put("mail." + protocol + ".host", imapProperties.getHost());
properties.put("mail." + protocol + ".port", imapProperties.getPort());
return Session.getInstance(properties);
}
@Bean
MailReader mailReader(Session mailSession, ImapProperties imapProperties) {
return new MailReader(mailSession, imapProperties);
}
}
The MailReader
bean looks as follows:
import jakarta.mail.*;
import jakarta.mail.search.FlagTerm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import java.util.concurrent.TimeUnit;
public class MailReader {
private static final Logger log = LoggerFactory.getLogger(MailReader.class);
private final Session session;
private final ImapProperties imapProperties;
public MailReader(Session session, ImapProperties imapProperties) {
this.session = session;
this.imapProperties = imapProperties;
}
//you can use spring scheduled annotation or use Quartz add-on
@Scheduled(fixedRate = 10, timeUnit = TimeUnit.SECONDS)
public void readUnseenMessages() {
log.debug("Mail reading started");
try {
Store store = session.getStore();
store.connect(imapProperties.getUsername(), imapProperties.getPassword());
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message[] messages = inbox.search(
new FlagTerm(new Flags(Flags.Flag.SEEN), false));
log.info("New messages in INBOX: {}", messages.length);
for (Message message : messages) {
log.info("Subject: {}", message.getSubject());
log.info("From: {}", message.getFrom()[0]);
log.info("Sent date: {}", message.getSentDate());
log.info("Content: {}", message.getContent());
}
inbox.close(false);
store.close();
} catch (Exception e) {
log.error("Error on reading the INBOX folder", e);
}
log.debug("Mail reading completed");
}
}
In this sample, mail server configuration should be defined in the application.properties file.
app.imap.host=<your-host>
app.imap.port=<your-port>
app.imap.username=<your-username>
app.imap.password=<your-password>
Here is the project:
imap-sample.zip (103.8 KB)