Richard
Richard

Reputation: 8955

Java Spring Mail Receiver

I am using SpringBoot 2.5.1 with Java 11.

I need to write functionality that will receive emails, I have searched, but cannot find many examples. Please can someone advise where I can get some examples/tutorials?

I have found this from the Spring.io website: Mail Support.

More info:

I would like to create a gmail account to be the mail server. I think IMAP has advantages over POP, but I am not sure?

Upvotes: 1

Views: 7223

Answers (1)

Richard
Richard

Reputation: 8955

ReadEmailIMAPImpl.java

public class ReadEmailIMAPImpl extends ReadEmailBaseImpl {

    private static Logger logger = LogManager.getLogger(ReadEmailIMAPImpl.class);

    private static final String PROTOCOL = "imap";
    private static final String HOST = "imap.gmail.com";

    private static Properties getProperties() {
        Properties props = new Properties();
        props.put("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.imap.socketFactory.fallback", "false");
        props.put("mail.imap.socketFactory.port", "993");
        props.put("mail.imap.port", "993");
        props.put("mail.imap.host", HOST);
        props.put("mail.imap.user", USERNAME);
        props.put("mail.imap.protocol", PROTOCOL);
        return props;
    }

    public static void main(String[] args) throws Exception {
        ReadEmailIMAPImpl readEmailIMAP = new ReadEmailIMAPImpl();
        readEmailIMAP.process();
    }

    @Override
    public void process() {
        try {
            process(PROTOCOL, HOST, getProperties());
        } catch (MessagingException e) {
            logger.error("Error processing emails. "+e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            logger.error("Error processing emails. "+e.getMessage());
            e.printStackTrace();
        }
    }
}

ReadEmailBaseImpl.java

public class ReadEmailBaseImpl implements ReadEmail {

    protected static final String USERNAME = "*****@gmail.com";
    protected static final String PASSWORD = "*******";

    private static Logger logger = LogManager.getLogger(ReadEmailBaseImpl.class);

    @Autowired
    private ProconFileService proconFileService;

    protected void process(final String PROTOCOL, final String HOST, final Properties props) throws MessagingException, IOException {
        // Creates a javax.mail.Authenticator object.
        Authenticator auth = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(ReadEmailPopImpl.USERNAME, ReadEmailPopImpl.PASSWORD);
            }
        };

        // Creating mail session.
        Session session = Session.getDefaultInstance(props, auth);

        // Get the store provider and connect to the store.
        Store store = session.getStore(PROTOCOL);
        store.connect(HOST, ReadEmailPopImpl.USERNAME, ReadEmailPopImpl.PASSWORD);

        // Get folder and open the INBOX folder in the store.
        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_WRITE);

        // Retrieve the messages from the folder.
        Message[] messages = inbox.getMessages();
        for (Message message : messages) {
            //message.setFlag(Flags.Flag.SEEN, true);  // todo: put back
            if (message != null) {
                String sentDate = message.getSentDate().toString();
                List<MimeBodyPart> attachments = getAttachments(message);
                logger.info("Read email subject '"+message.getSubject()+"' from '"+getAddressesAsString(message)+"' at '"+sentDate+"' with "+attachments.size()+" attachment/s '"+getAttachmentsAsString(attachments)+"'.");
                if (!attachments.isEmpty()) {
                    save(message, attachments);
                    //message.setFlag(Flags.Flag.DELETED, true); // todo: put back
                }
            }
        }

        // Close folder and close store.
        inbox.close(true);
        store.close();
    }
}

Upvotes: 2

Related Questions