简体   繁体   中英

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 = "user@gmail.com";
    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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM