views:

32

answers:

1

I sometimes get "Host is unresolved: imap.gmail.com:993" when I try the javamail/gmail store.connect in the Android development environment using GMailReader below. Why might this fail sometimes and not others?

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;
        }
    }
A: 

I may have been opening too many instances of GMailReader, and not closing them properly. I haven't seen this issue in some time since I move the open out of the creator, and added a close method. It seems to be working well this way:

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);
        }
    }
...
JackN