当我使用下面的GMailReader在Android开发环境中尝试javamail / gmail store.connect时,有时会收到“主机未解析:imap.gmail.com:993”。为什么这有时会失败而不是其他人呢?

public class GMailReader extends javax.mail.Authenticator {
    private String user;
    private String password;
    public GMailReader(String user, String password) {
        this.user = user;
        this.password = password;
    }
    public int getUnreadMessageCount() throws Exception {
        try {
            Properties props = new Properties();
            props.setProperty("mail.store.protocol", "imaps");
            Session session = Session.getInstance(props, this);
            Store store = session.getStore("imaps");
            store.connect("imap.gmail.com", user, password);
            Folder inbox = store.getFolder("Inbox");
            inbox.open(Folder.READ_ONLY);
            int unreadMessageCount = inbox.getUnreadMessageCount();
            return unreadMessageCount;
        } catch (Exception e) {
            Log.e("getUnreadMessageCount", e.getMessage(), e);
            return -1;
        }
    }

最佳答案

我可能打开了太多的GMailReader实例,但没有正确关闭它们。自从我将打开位置移出创建者并添加了close方法以来,我已经有一段时间没有看到这个问题了。这样看来运作良好:

public class GMailReader extends javax.mail.Authenticator {
    private String user;
    private String password;
    private Properties properties;
    private Session session;
    private Store store;
    private Folder inbox;

    public GMailReader(String user, String password) {
        this.user = user;
        this.password = password;
    }

    public void open() throws Exception {
        try {
            properties = new Properties();
            properties.setProperty("mail.store.protocol", "imaps");
            session = Session.getInstance(properties, this);
            store = session.getStore("imaps");
            store.connect("imap.gmail.com", user, password);
            inbox = store.getFolder("Inbox");
            inbox.open(Folder.READ_ONLY);
        } catch (Exception e) {
            Log.e(this.getClass().toString(), e.getMessage(), e);
        }
    }
    public void close(boolean expunge) throws Exception {
        try {
            if (inbox.isOpen()) {
                inbox.close(expunge);
            }
            if (store.isConnected()) {
                store.close();
            }
        } catch (Exception e) {
            Log.e(this.getClass().toString(), e.getMessage(), e);
        }
    }
...

10-08 17:47