Class IMAPStore

  • All Implemented Interfaces:
    ResponseHandler, java.lang.AutoCloseable, QuotaAwareStore
    Direct Known Subclasses:
    GmailStore, IMAPSSLStore

    public class IMAPStore
    extends Store
    implements QuotaAwareStore, ResponseHandler
    This class provides access to an IMAP message store.

    Applications that need to make use of IMAP-specific features may cast a Store object to an IMAPStore object and use the methods on this class. The getQuota and setQuota methods support the IMAP QUOTA extension. Refer to RFC 2087 for more information.

    The id method supports the IMAP ID extension; see RFC 2971. The fields ID_NAME, ID_VERSION, etc. represent the suggested field names in RFC 2971 section 3.3 and may be used as keys in the Map containing client values or server values.

    See the com.sun.mail.imap package documentation for further information on the IMAP protocol provider.

    WARNING: The APIs unique to this class should be considered EXPERIMENTAL. They may be changed in the future in ways that are incompatible with applications using the current APIs.

    • Field Detail

      • RESPONSE

        public static final int RESPONSE
        A special event type for a StoreEvent to indicate an IMAP response, if the mail.imap.enableimapevents property is set.
        See Also:
        Constant Field Values
      • name

        protected final java.lang.String name
      • defaultPort

        protected final int defaultPort
      • isSSL

        protected final boolean isSSL
      • blksize

        private final int blksize
      • ignoreSize

        private boolean ignoreSize
      • statusCacheTimeout

        private final int statusCacheTimeout
      • appendBufferSize

        private final int appendBufferSize
      • minIdleTime

        private final int minIdleTime
      • port

        private volatile int port
      • host

        protected java.lang.String host
      • user

        protected java.lang.String user
      • password

        protected java.lang.String password
      • proxyAuthUser

        protected java.lang.String proxyAuthUser
      • authorizationID

        protected java.lang.String authorizationID
      • saslRealm

        protected java.lang.String saslRealm
      • enableStartTLS

        private boolean enableStartTLS
      • requireStartTLS

        private boolean requireStartTLS
      • usingSSL

        private boolean usingSSL
      • enableSASL

        private boolean enableSASL
      • saslMechanisms

        private java.lang.String[] saslMechanisms
      • forcePasswordRefresh

        private boolean forcePasswordRefresh
      • enableResponseEvents

        private boolean enableResponseEvents
      • enableImapEvents

        private boolean enableImapEvents
      • guid

        private java.lang.String guid
      • throwSearchException

        private boolean throwSearchException
      • peek

        private boolean peek
      • closeFoldersOnStoreFailure

        private boolean closeFoldersOnStoreFailure
      • enableCompress

        private boolean enableCompress
      • finalizeCleanClose

        private boolean finalizeCleanClose
      • connectionFailed

        private volatile boolean connectionFailed
      • forceClose

        private volatile boolean forceClose
      • connectionFailedLock

        private final java.lang.Object connectionFailedLock
      • debugusername

        private boolean debugusername
      • debugpassword

        private boolean debugpassword
      • messageCacheDebug

        private boolean messageCacheDebug
      • folderConstructor

        private volatile java.lang.reflect.Constructor<?> folderConstructor
      • folderConstructorLI

        private volatile java.lang.reflect.Constructor<?> folderConstructorLI
      • nonStoreResponseHandler

        private ResponseHandler nonStoreResponseHandler
        A special response handler for connections that are being used to perform operations on behalf of an object other than the Store. It DOESN'T cause the Store to be cleaned up if a BYE is seen. The BYE may be real or synthetic and in either case just indicates that the connection is dead.
    • Constructor Detail

      • IMAPStore

        public IMAPStore​(Session session,
                         URLName url)
        Constructor that takes a Session object and a URLName that represents a specific IMAP server.
        Parameters:
        session - the Session
        url - the URLName of this store
      • IMAPStore

        protected IMAPStore​(Session session,
                            URLName url,
                            java.lang.String name,
                            boolean isSSL)
        Constructor used by this class and by IMAPSSLStore subclass.
        Parameters:
        session - the Session
        url - the URLName of this store
        name - the protocol name for this store
        isSSL - use SSL?
    • Method Detail

      • protocolConnect

        protected boolean protocolConnect​(java.lang.String host,
                                          int pport,
                                          java.lang.String user,
                                          java.lang.String password)
                                   throws MessagingException
        Implementation of protocolConnect(). Will create a connection to the server and authenticate the user using the mechanisms specified by various properties.

        The host, user, and password parameters must all be non-null. If the authentication mechanism being used does not require a password, an empty string or other suitable dummy password should be used.

        Overrides:
        protocolConnect in class Service
        Parameters:
        host - the name of the host to connect to
        pport - the port to use (-1 means use default port)
        user - the name of the user to login as
        password - the user's password
        Returns:
        true if connection successful, false if authentication failed
        Throws:
        AuthenticationFailedException - for authentication failures
        MessagingException - for non-authentication failures
      • newIMAPProtocol

        protected IMAPProtocol newIMAPProtocol​(java.lang.String host,
                                               int port)
                                        throws java.io.IOException,
                                               ProtocolException
        Create an IMAPProtocol object connected to the host and port. Subclasses of IMAPStore may override this method to return a subclass of IMAPProtocol that supports product-specific extensions.
        Parameters:
        host - the host name
        port - the port number
        Returns:
        the new IMAPProtocol object
        Throws:
        java.io.IOException - for I/O errors
        ProtocolException - for protocol errors
        Since:
        JavaMail 1.4.6
      • authenticate

        private void authenticate​(IMAPProtocol p,
                                  java.lang.String authzid,
                                  java.lang.String user,
                                  java.lang.String password)
                           throws ProtocolException
        Authenticate using one of the non-SASL mechanisms.
        Parameters:
        p - the IMAPProtocol object
        authzid - the authorization ID
        user - the user name
        password - the password
        Throws:
        ProtocolException - on failures
      • preLogin

        protected void preLogin​(IMAPProtocol p)
                         throws ProtocolException
        This method is called after the connection is made and TLS is started (if needed), but before any authentication is attempted. Subclasses can override this method to issue commands that are needed in the "not authenticated" state. Note that if the connection is pre-authenticated, this method won't be called.

        The implementation of this method in this class does nothing.

        Parameters:
        p - the IMAPProtocol connection
        Throws:
        ProtocolException - for protocol errors
        Since:
        JavaMail 1.4.4
      • isSSL

        public boolean isSSL()
        Does this IMAPStore use SSL when connecting to the server?
        Returns:
        true if using SSL
        Since:
        JavaMail 1.4.6
      • setUsername

        public void setUsername​(java.lang.String user)
        Set the user name that will be used for subsequent connections after this Store is first connected (for example, when creating a connection to open a Folder). This value is overridden by any call to the Store's connect method.

        Some IMAP servers may provide an authentication ID that can be used for more efficient authentication for future connections. This authentication ID is provided in a server-specific manner not described here.

        Most applications will never need to use this method.

        Parameters:
        user - the user name for the store
        Since:
        JavaMail 1.3.3
      • setPassword

        public void setPassword​(java.lang.String password)
        Set the password that will be used for subsequent connections after this Store is first connected (for example, when creating a connection to open a Folder). This value is overridden by any call to the Store's connect method.

        Most applications will never need to use this method.

        Parameters:
        password - the password for the store
        Since:
        JavaMail 1.3.3
      • getStoreProtocol

        private IMAPProtocol getStoreProtocol()
                                       throws ProtocolException
        Get this Store's protocol connection. When acquiring a store protocol object, it is important to use the following steps: IMAPProtocol p = null; try { p = getStoreProtocol(); // perform the command } catch (ConnectionException cex) { throw new StoreClosedException(this, cex.getMessage()); } catch (WhateverException ex) { // handle it } finally { releaseStoreProtocol(p); }
        Throws:
        ProtocolException
      • refreshPassword

        private void refreshPassword()
      • allowReadOnlySelect

        boolean allowReadOnlySelect()
        If a SELECT succeeds, but indicates that the folder is READ-ONLY, and the user asked to open the folder READ_WRITE, do we allow the open to succeed?
      • hasSeparateStoreConnection

        boolean hasSeparateStoreConnection()
        Report whether the separateStoreConnection is set.
      • getConnectionPoolLogger

        MailLogger getConnectionPoolLogger()
        Return the connection pool logger.
      • getMessageCacheDebug

        boolean getMessageCacheDebug()
        Report whether message cache debugging is enabled.
      • isConnectionPoolFull

        boolean isConnectionPoolFull()
        Report whether the connection pool is full.
      • releaseProtocol

        void releaseProtocol​(IMAPFolder folder,
                             IMAPProtocol protocol)
        Release the protocol object back to the connection pool.
      • releaseStoreProtocol

        private void releaseStoreProtocol​(IMAPProtocol protocol)
        Release the store connection.
      • releaseFolderStoreProtocol

        void releaseFolderStoreProtocol​(IMAPProtocol protocol)
        Release a store protocol object that was being used by a folder.
      • emptyConnectionPool

        private void emptyConnectionPool​(boolean force)
        Empty the connection pool.
      • timeoutConnections

        private void timeoutConnections()
        Check to see if it's time to shrink the connection pool.
      • getFetchBlockSize

        int getFetchBlockSize()
        Get the block size to use for fetch requests on this Store.
      • ignoreBodyStructureSize

        boolean ignoreBodyStructureSize()
        Ignore the size reported in the BODYSTRUCTURE when fetching data?
      • getSession

        Session getSession()
        Get a reference to the session.
      • getStatusCacheTimeout

        int getStatusCacheTimeout()
        Get the number of milliseconds to cache STATUS response.
      • getAppendBufferSize

        int getAppendBufferSize()
        Get the maximum size of a message to buffer for append.
      • getMinIdleTime

        int getMinIdleTime()
        Get the minimum amount of time to delay when returning from idle.
      • throwSearchException

        boolean throwSearchException()
        Throw a SearchException if the search expression is too complex?
      • getPeek

        boolean getPeek()
        Get the default "peek" value.
      • hasCapability

        public boolean hasCapability​(java.lang.String capability)
                              throws MessagingException
        Return true if the specified capability string is in the list of capabilities the server announced.
        Parameters:
        capability - the capability string
        Returns:
        true if the server supports this capability
        Throws:
        MessagingException - for failures
        Since:
        JavaMail 1.3.3
      • setProxyAuthUser

        public void setProxyAuthUser​(java.lang.String user)
        Set the user name to be used with the PROXYAUTH command. The PROXYAUTH user name can also be set using the mail.imap.proxyauth.user property when this Store is created.
        Parameters:
        user - the user name to set
        Since:
        JavaMail 1.5.1
      • getProxyAuthUser

        public java.lang.String getProxyAuthUser()
        Get the user name to be used with the PROXYAUTH command.
        Returns:
        the user name
        Since:
        JavaMail 1.5.1
      • isConnected

        public boolean isConnected()
        Check whether this store is connected. Override superclass method, to actually ping our server connection.
        Overrides:
        isConnected in class Service
        Returns:
        true if the service is connected, false if it is not connected
      • finalize

        protected void finalize()
                         throws java.lang.Throwable
        Description copied from class: Service
        Stop the event dispatcher thread so the queue can be garbage collected.
        Overrides:
        finalize in class Service
        Throws:
        java.lang.Throwable
      • cleanup

        private void cleanup()
        Cleanup before dying.
      • closeAllFolders

        private void closeAllFolders​(boolean force)
        Close all open Folders. If force is true, close them forcibly.
      • getFolder

        public Folder getFolder​(java.lang.String name)
                         throws MessagingException
        Get named folder. Returns a new, closed IMAPFolder.
        Specified by:
        getFolder in class Store
        Parameters:
        name - The name of the Folder. In some Stores, name can be an absolute path if it starts with the hierarchy delimiter. Else it is interpreted relative to the 'root' of this namespace.
        Returns:
        Folder object
        Throws:
        MessagingException - for other failures
        See Also:
        Folder.exists(), Folder.create(int)
      • newIMAPFolder

        protected IMAPFolder newIMAPFolder​(java.lang.String fullName,
                                           char separator,
                                           java.lang.Boolean isNamespace)
        Create an IMAPFolder object. If user supplied their own class, use it. Otherwise, call the constructor.
        Parameters:
        fullName - the full name of the folder
        separator - the separator character for the folder hierarchy
        isNamespace - does this name represent a namespace?
        Returns:
        the new IMAPFolder object
      • newIMAPFolder

        protected IMAPFolder newIMAPFolder​(java.lang.String fullName,
                                           char separator)
        Create an IMAPFolder object. Call the newIMAPFolder method above with a null isNamespace.
        Parameters:
        fullName - the full name of the folder
        separator - the separator character for the folder hierarchy
        Returns:
        the new IMAPFolder object
      • newIMAPFolder

        protected IMAPFolder newIMAPFolder​(ListInfo li)
        Create an IMAPFolder object. If user supplied their own class, use it. Otherwise, call the constructor.
        Parameters:
        li - the ListInfo for the folder
        Returns:
        the new IMAPFolder object
      • getUserNamespaces

        public Folder[] getUserNamespaces​(java.lang.String user)
                                   throws MessagingException
        Using the IMAP NAMESPACE command (RFC 2342), return a set of folders representing the User's namespaces.
        Overrides:
        getUserNamespaces in class Store
        Parameters:
        user - the user name
        Returns:
        array of Folder objects
        Throws:
        MessagingException - for other failures
      • getQuota

        public Quota[] getQuota​(java.lang.String root)
                         throws MessagingException
        Get the quotas for the named quota root. Quotas are controlled on the basis of a quota root, not (necessarily) a folder. The relationship between folders and quota roots depends on the IMAP server. Some servers might implement a single quota root for all folders owned by a user. Other servers might implement a separate quota root for each folder. A single folder can even have multiple quota roots, perhaps controlling quotas for different resources.
        Specified by:
        getQuota in interface QuotaAwareStore
        Parameters:
        root - the name of the quota root
        Returns:
        array of Quota objects
        Throws:
        MessagingException - if the server doesn't support the QUOTA extension
      • setQuota

        public void setQuota​(Quota quota)
                      throws MessagingException
        Set the quotas for the quota root specified in the quota argument. Typically this will be one of the quota roots obtained from the getQuota method, but it need not be.
        Specified by:
        setQuota in interface QuotaAwareStore
        Parameters:
        quota - the quota to set
        Throws:
        MessagingException - if the server doesn't support the QUOTA extension
      • checkConnected

        private void checkConnected()
      • idle

        public void idle()
                  throws MessagingException
        Use the IMAP IDLE command (see RFC 2177), if supported by the server, to enter idle mode so that the server can send unsolicited notifications without the need for the client to constantly poll the server. Use a ConnectionListener to be notified of events. When another thread (e.g., the listener thread) needs to issue an IMAP comand for this Store, the idle mode will be terminated and this method will return. Typically the caller will invoke this method in a loop.

        If the mail.imap.enableimapevents property is set, notifications received while the IDLE command is active will be delivered to ConnectionListeners as events with a type of IMAPStore.RESPONSE. The event's message will be the raw IMAP response string. Note that most IMAP servers will not deliver any events when using the IDLE command on a connection with no mailbox selected (i.e., this method). In most cases you'll want to use the idle method on IMAPFolder.

        NOTE: This capability is highly experimental and likely will change in future releases.

        The mail.imap.minidletime property enforces a minimum delay before returning from this method, to ensure that other threads have a chance to issue commands before the caller invokes this method again. The default delay is 10 milliseconds.

        Throws:
        MessagingException - if the server doesn't support the IDLE extension
        java.lang.IllegalStateException - if the store isn't connected
        Since:
        JavaMail 1.4.1
      • id

        public java.util.Map<java.lang.String,​java.lang.String> id​(java.util.Map<java.lang.String,​java.lang.String> clientParams)
                                                                  throws MessagingException
        Send the IMAP ID command (if supported by the server) and return the result from the server. The ID command identfies the client to the server and returns information about the server to the client. See RFC 2971. The returned Map is unmodifiable.
        Parameters:
        clientParams - a Map of keys and values identifying the client
        Returns:
        a Map of keys and values identifying the server
        Throws:
        MessagingException - if the server doesn't support the ID extension
        Since:
        JavaMail 1.5.1
      • handleResponseCode

        void handleResponseCode​(Response r)
        Handle notifications and alerts. Response must be an OK, NO, BAD, or BYE response.
      • traceUser

        private java.lang.String traceUser​(java.lang.String user)
      • tracePassword

        private java.lang.String tracePassword​(java.lang.String password)