JackChap77
JackChap77

Reputation: 68

Javamail not connecting

Trying to use JavaMail for the first time. Upon putting in details it prints true (as if it were connected), but when trying to find a folder, it doesn't work.

private static void login() throws MessagingException {
    String host = "imap.gmail.com";
    String username = "[email protected]";
    String password = "password";
    Properties props = new Properties();
    props.setProperty("mail.imap.ssl.enable", "true");
    props.setProperty("mail.store.protocol", "imaps");
    session = Session.getInstance(props);
    store = session.getStore("imaps");
    store.connect(host, 993, username, password);
    System.out.println(store.isConnected()); //THIS HERE RETURNS TRUE
}

public static void check()
{
    try {
        //create the folder object and open it
        Folder emailFolder = store.getFolder("INBOX"); //ENDS PROGRAM LOGGING, "Not Connected"
        emailFolder.open(Folder.READ_ONLY);

        javax.mail.Message[] messages = emailFolder.getMessages();

        for (int i = 0, n = messages.length; i < n; i++) {
            javax.mail.Message message = messages[i];
            if(message.getSubject().contains("Optimism") && message.getSubject().contains("New reply to watched thread")) {
                for(Guild g : jda.getGuilds()) {
                    if(g.getName().equalsIgnoreCase("Optimism"))
                    for (TextChannel c : g.getTextChannels())
                        if (c.getName() == "staff_chat") {
                            c.sendMessage("**New Thread Reply! - " + new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(new Date()) + " EST.").queue();
                        }
                }

            }

        }

        //close the store and folder objects
        emailFolder.close(false);
        store.close();

    } catch (NoSuchProviderException e) {
        e.printStackTrace();
    } catch (MessagingException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Everthing in the if statement from the first loop all works

NOTE: It's in two methods as the check method is called every 2 mins.

Upvotes: 1

Views: 670

Answers (1)

Sanjeev
Sanjeev

Reputation: 9946

As you said, that check() method is getting called every two minutes. It will create problem as you are closing your store object in it store.close() . So it will work just the first time and after that it won't.

Either you call login() also every two minutes just before check() or do not close store in check and leave it open/connected.

Hope this helps.

Upvotes: 2

Related Questions