Skip to content
Advertisement

Spring boot read and new mail Listener on spring-boot-starter-mail

I want to demonstrate the email application using the spring boot MVC in that web application I follow this tutorial I can easily send the emails using spring boot.

Here my question is

  1. how can I read the emails using spring boot..?
  2. how can I listen for new emails and how to update the inbox on the view..?

please suggest me any solutions for that because I searched a lot but I can find only send email example.please share me if you have any working samples for that using spring boot. Thanks in advance.

Advertisement

Answer

You could consider using Spring integration mail support

There is a Java DSL for this purposes.
An example of IMAP config could be found here

The key aspects are like this

@Configuration
@EnableIntegration
public class IntegrationConfig {
    ...

    @Bean
    public IntegrationFlow imapIdleFlow() {
        return IntegrationFlows
                .from(Mail.imapIdleAdapter("imap://user:pw@localhost:" + imapIdleServer.getPort() + "/INBOX")
                        .autoStartup(true)
                        .searchTermStrategy(this::fromAndNotSeenTerm)
                        .userFlag("testSIUserFlag")
                        .javaMailProperties(p -> p.put("mail.debug", "false")
                                .put("mail.imap.connectionpoolsize", "5"))
                        .shouldReconnectAutomatically(false)
                        .headerMapper(mailHeaderMapper()))
                .channel(MessageChannels.queue("imapIdleChannel"))
                .get();
    }

    @Bean
    public HeaderMapper<MimeMessage> mailHeaderMapper() {
        return new DefaultMailHeaderMapper();
    }

    private SearchTerm fromAndNotSeenTerm(Flags supportedFlags, Folder folder) {
        try {
            FromTerm fromTerm = new FromTerm(new InternetAddress("bar@baz"));
            return new AndTerm(fromTerm, new FlagTerm(new Flags(Flags.Flag.SEEN), false));
        }
        catch (AddressException e) {
            throw new RuntimeException(e);
        }

    }
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement