gnu.inet.imap

Class IMAPConnection

Implemented Interfaces:
IMAPConstants

public class IMAPConnection
extends Object
implements IMAPConstants

The protocol class implementing IMAP4rev1.

Field Summary

protected static int
DEFAULT_PORT
The default IMAP port.
protected static int
DEFAULT_SSL_PORT
The default IMAP-SSL port.
protected static String
TAG_PREFIX
Prefix for tags.
protected static String
US_ASCII
The encoding used to create strings for IMAP commands.
protected List
asyncResponses
List of responses received asynchronously.
protected IMAPResponseTokenizer
in
The tokenizer used to read IMAP responses from.
protected CRLFOutputStream
out
The output stream.
protected Socket
socket
The socket used for communication with the server.

Fields inherited from interface gnu.inet.imap.IMAPConstants

ACL, ALERT, APPEND, AUTHENTICATE, BAD, BODY, BODYSTRUCTURE, BODY_PEEK, BYE, CAPABILITY, CHECK, CLOSE, COPY, CRAM_MD5, CREATE, DELETE, DELETEACL, ENVELOPE, EXAMINE, EXISTS, EXPUNGE, FETCH, FETCH_FLAGS, FLAGS, FLAG_ANSWERED, FLAG_DELETED, FLAG_DRAFT, FLAG_FLAGGED, FLAG_RECENT, FLAG_SEEN, GETACL, GETQUOTA, GETQUOTAROOT, GSSAPI, HEADER, HEADER_FIELDS, HEADER_FIELDS_NOT, INTERNALDATE, KERBEROS_V4, LIST, LISTRIGHTS, LIST_MARKED, LIST_NOINFERIORS, LIST_NOSELECT, LIST_UNMARKED, LOGIN, LOGINDISABLED, LOGOUT, LSUB, MESSAGES, MYRIGHTS, NAMESPACE, NEWNAME, NIL, NO, NOOP, OK, PARSE, PERMANENTFLAGS, PREAUTH, QUOTA, QUOTAROOT, READ_ONLY, READ_WRITE, RECENT, RENAME, RFC822, RFC822_HEADER, RFC822_SIZE, RFC822_TEXT, RIGHTS_ADMIN, RIGHTS_CREATE, RIGHTS_DELETE, RIGHTS_INSERT, RIGHTS_LOOKUP, RIGHTS_POST, RIGHTS_READ, RIGHTS_SEEN, RIGHTS_WRITE, SEARCH, SEARCH_ALL, SEARCH_ANSWERED, SEARCH_BCC, SEARCH_BEFORE, SEARCH_BODY, SEARCH_CC, SEARCH_DELETED, SEARCH_DRAFT, SEARCH_FLAGGED, SEARCH_FROM, SEARCH_HEADER, SEARCH_KEYWORD, SEARCH_LARGER, SEARCH_NEW, SEARCH_NOT, SEARCH_OLD, SEARCH_ON, SEARCH_OR, SEARCH_RECENT, SEARCH_SEEN, SEARCH_SENTBEFORE, SEARCH_SENTON, SEARCH_SENTSINCE, SEARCH_SINCE, SEARCH_SMALLER, SEARCH_SUBJECT, SEARCH_TEXT, SEARCH_TO, SEARCH_UID, SEARCH_UNANSWERED, SEARCH_UNDELETED, SEARCH_UNDRAFT, SEARCH_UNFLAGGED, SEARCH_UNKEYWORD, SEARCH_UNSEEN, SELECT, SETACL, SETQUOTA, SKEY, STARTTLS, STATUS, STORAGE, STORE, SUBSCRIBE, TRYCREATE, UID, UIDNEXT, UIDVALIDITY, UNSEEN, UNSUBSCRIBE

Constructor Summary

IMAPConnection(String host)
Creates a new connection to the default IMAP port.
IMAPConnection(String host, int port)
Creates a new connection.
IMAPConnection(String host, int port, int connectionTimeout, int timeout, boolean debug)
Creates a new connection.
IMAPConnection(String host, int port, int connectionTimeout, int timeout, boolean secure, TrustManager tm, boolean debug)
Creates a new connection.
IMAPConnection(String host, int port, TrustManager tm)
Creates a new secure connection using the specified trust manager.

Method Summary

boolean
alertsPending()
Indicates if there are alerts pending for the user-agent.
boolean
append(String mailbox, String[] flags, byte[] content)
Append a message to the specified mailbox.
boolean
authenticate(String mechanism, String username, String password)
Authenticates the connection using the specified SASL mechanism, username, and password.
List
capability()
Returns a list of the capabilities of the IMAP server.
void
check()
Request a checkpoint of the currently selected mailbox.
boolean
close()
Permanently remove all messages that have the \Deleted flags set, and close the mailbox.
boolean
copy(int[] messages, String mailbox)
Copies the specified messages to the end of the destination mailbox.
boolean
create(String mailbox)
Creates a mailbox with the specified name.
boolean
delete(String mailbox)
Deletes the mailbox with the specified name.
boolean
deleteacl(String mailbox, String principal)
Removes any access rights for the given authentication principal on the specified mailbox.
MailboxStatus
examine(String mailbox)
Selects the specified mailbox.
int[]
expunge()
Permanently removes all messages that have the \Delete flag set.
MessageStatus[]
fetch(int start, int end, String[] fetchCommands)
Retrieves data associated with the specified range of messages in the mailbox.
MessageStatus
fetch(int message, String[] fetchCommands)
Retrieves data associated with the specified message in the mailbox.
MessageStatus[]
fetch(int[] messages, String[] fetchCommands)
Retrieves data associated with messages in the mailbox.
String[]
getAlerts()
Returns the pending alerts for the user-agent as an array.
protected SSLSocketFactory
getSSLSocketFactory(TrustManager tm)
Returns a configured SSLSocketFactory to use in creating new SSL sockets.
Map
getacl(String mailbox)
Returns the access control list for the specified mailbox.
Quota
getquota(String quotaRoot)
Returns the specified quota root's resource usage and limits.
Quota[]
getquotaroot(String mailbox)
Returns the quotas for the given mailbox.
protected boolean
invokeSimpleCommand(String command)
Sends the specified IMAP command.
ListEntry[]
list(String reference, String mailbox)
Returns a subset of names from the compete set of names available to the client.
protected ListEntry[]
listImpl(String command, String reference, String mailbox)
int
listrights(String mailbox, String principal)
Returns the rights for the given principal for the specified mailbox.
boolean
login(String username, String password)
Login to the connection using the username and password method.
void
logout()
Logout this connection.
ListEntry[]
lsub(String reference, String mailbox)
Returns a subset of subscribed names.
int
myrights(String mailbox)
Returns the rights for the current principal for the specified mailbox.
Namespaces
namespace()
Returns the namespaces available on the server.
protected String
newTag()
Returns a new tag for a command.
MailboxStatus
noop()
Ping the server.
protected IMAPResponse
readResponse()
Reads an IMAP response from the server.
boolean
rename(String source, String target)
Renames the source mailbox to the specified name.
int[]
search(String charset, String[] criteria)
Searches the currently selected mailbox for messages matching the specified criteria.
MailboxStatus
select(String mailbox)
Selects the specified mailbox.
protected MailboxStatus
selectImpl(String mailbox, String command)
protected void
sendCommand(String tag, String command)
Sends the specified IMAP tagged command to the server.
void
setAnsiDebug(boolean flag)
Sets whether debugging output should use ANSI colour escape sequences.
boolean
setacl(String mailbox, String principal, int rights)
Changes the access rights on the specified mailbox such that the authentication principal is granted the specified permissions.
Quota
setquota(String quotaRoot, Quota.Resource resources)
Sets the quota for the specified quota root.
boolean
starttls()
Attempts to start TLS on the specified connection.
boolean
starttls(TrustManager tm)
Attempts to start TLS on the specified connection.
MailboxStatus
status(String mailbox, String[] statusNames)
Requests the status of the specified mailbox.
MessageStatus[]
store(int start, int end, String flagCommand, String[] flags)
Alters data associated with the specified range of messages in the mailbox.
MessageStatus
store(int message, String flagCommand, String[] flags)
Alters data associated with the specified message in the mailbox.
MessageStatus[]
store(int[] messages, String flagCommand, String[] flags)
Alters data associated with messages in the mailbox.
boolean
subscribe(String mailbox)
Adds the specified mailbox to the set of subscribed mailboxes as returned by the LSUB command.
MessageStatus
uidFetch(long uid, String[] fetchCommands)
Retrieves data associated with the specified message in the mailbox.
MessageStatus[]
uidFetch(long start, long end, String[] fetchCommands)
Retrieves data associated with the specified range of messages in the mailbox.
MessageStatus[]
uidFetch(long[] uids, String[] fetchCommands)
Retrieves data associated with messages in the mailbox.
MessageStatus
uidStore(long uid, String flagCommand, String[] flags)
Alters data associated with the specified message in the mailbox.
MessageStatus[]
uidStore(long start, long end, String flagCommand, String[] flags)
Alters data associated with the specified range of messages in the mailbox.
MessageStatus[]
uidStore(long[] uids, String flagCommand, String[] flags)
Alters data associated with messages in the mailbox.
boolean
unsubscribe(String mailbox)
Removes the specified mailbox from the set of subscribed mailboxes as returned by the LSUB command.
protected boolean
updateMailboxStatus(MailboxStatus ms, String id, IMAPResponse response)

Field Details

DEFAULT_PORT

protected static final int DEFAULT_PORT
The default IMAP port.

Field Value:
143


DEFAULT_SSL_PORT

protected static final int DEFAULT_SSL_PORT
The default IMAP-SSL port.

Field Value:
993


TAG_PREFIX

protected static final String TAG_PREFIX
Prefix for tags.

Field Value:
""


US_ASCII

protected static final String US_ASCII
The encoding used to create strings for IMAP commands.

Field Value:
""


asyncResponses

protected List asyncResponses
List of responses received asynchronously.


in

protected IMAPResponseTokenizer in
The tokenizer used to read IMAP responses from.


out

protected CRLFOutputStream out
The output stream.


socket

protected Socket socket
The socket used for communication with the server.

Constructor Details

IMAPConnection

public IMAPConnection(String host)
            throws UnknownHostException,
                   IOException
Creates a new connection to the default IMAP port.

Parameters:
host - the name of the host to connect to


IMAPConnection

public IMAPConnection(String host,
                      int port)
            throws UnknownHostException,
                   IOException
Creates a new connection.

Parameters:
host - the name of the host to connect to
port - the port to connect to, or -1 for the default


IMAPConnection

public IMAPConnection(String host,
                      int port,
                      int connectionTimeout,
                      int timeout,
                      boolean debug)
            throws UnknownHostException,
                   IOException
Creates a new connection.

Parameters:
host - the name of the host to connect to
port - the port to connect to, or -1 for the default
connectionTimeout - the socket connection timeout
timeout - the socket timeout
debug - log debugging information


IMAPConnection

public IMAPConnection(String host,
                      int port,
                      int connectionTimeout,
                      int timeout,
                      boolean secure,
                      TrustManager tm,
                      boolean debug)
            throws UnknownHostException,
                   IOException
Creates a new connection.

Parameters:
host - the name of the host to connect to
port - the port to connect to, or -1 for the default
connectionTimeout - the socket connection timeout
timeout - the socket timeout
secure - if an IMAP-SSL connection should be made
tm - a trust manager used to check SSL certificates, or null to use the default
debug - log debugging information


IMAPConnection

public IMAPConnection(String host,
                      int port,
                      TrustManager tm)
            throws UnknownHostException,
                   IOException
Creates a new secure connection using the specified trust manager.

Parameters:
host - the name of the host to connect to
port - the port to connect to, or -1 for the default
tm - a trust manager used to check SSL certificates, or null to use the default

Method Details

alertsPending

public boolean alertsPending()
Indicates if there are alerts pending for the user-agent.


append

public boolean append(String mailbox,
                      String[] flags,
                      byte[] content)
            throws IOException
Append a message to the specified mailbox. This method returns an OutputStream to which the message should be written and then closed.

Parameters:
mailbox - the mailbox name
flags - optional list of flags to specify for the message
content - the message body(including headers)

Returns:
true if successful, false if error in flags/text


authenticate

public boolean authenticate(String mechanism,
                            String username,
                            String password)
            throws IOException
Authenticates the connection using the specified SASL mechanism, username, and password.

Parameters:
mechanism - a SASL authentication mechanism, e.g. LOGIN, PLAIN, CRAM-MD5, GSSAPI
username - the authentication principal
password - the authentication credentials

Returns:
true if authentication was successful, false otherwise


capability

public List capability()
            throws IOException
Returns a list of the capabilities of the IMAP server.


check

public void check()
            throws IOException
Request a checkpoint of the currently selected mailbox.


close

public boolean close()
            throws IOException
Permanently remove all messages that have the \Deleted flags set, and close the mailbox.

Returns:
true if successful, false if no mailbox was selected


copy

public boolean copy(int[] messages,
                    String mailbox)
            throws IOException
Copies the specified messages to the end of the destination mailbox.

Parameters:
messages - the message numbers
mailbox - the destination mailbox


create

public boolean create(String mailbox)
            throws IOException
Creates a mailbox with the specified name.

Parameters:
mailbox - the mailbox name

Returns:
true if the mailbox was successfully created, false otherwise


delete

public boolean delete(String mailbox)
            throws IOException
Deletes the mailbox with the specified name.

Parameters:
mailbox - the mailbox name

Returns:
true if the mailbox was successfully deleted, false otherwise


deleteacl

public boolean deleteacl(String mailbox,
                         String principal)
            throws IOException
Removes any access rights for the given authentication principal on the specified mailbox.

Parameters:
mailbox - the mailbox name
principal - the authentication identifier


examine

public MailboxStatus examine(String mailbox)
            throws IOException
Selects the specified mailbox. The mailbox is identified as read-only.

Parameters:
mailbox - the mailbox name

Returns:
a MailboxStatus containing the state of the selected mailbox


expunge

public int[] expunge()
            throws IOException
Permanently removes all messages that have the \Delete flag set.

Returns:
the numbers of the messages expunged


fetch

public MessageStatus[] fetch(int start,
                             int end,
                             String[] fetchCommands)
            throws IOException
Retrieves data associated with the specified range of messages in the mailbox.

Parameters:
start - the message number of the first message
end - the message number of the last message
fetchCommands - the fetch commands, e.g. FLAGS


fetch

public MessageStatus fetch(int message,
                           String[] fetchCommands)
            throws IOException
Retrieves data associated with the specified message in the mailbox.

Parameters:
message - the message number
fetchCommands - the fetch commands, e.g. FLAGS


fetch

public MessageStatus[] fetch(int[] messages,
                             String[] fetchCommands)
            throws IOException
Retrieves data associated with messages in the mailbox.

Parameters:
messages - the message numbers
fetchCommands - the fetch commands, e.g. FLAGS


getAlerts

public String[] getAlerts()
Returns the pending alerts for the user-agent as an array.


getSSLSocketFactory

protected SSLSocketFactory getSSLSocketFactory(TrustManager tm)
            throws GeneralSecurityException
Returns a configured SSLSocketFactory to use in creating new SSL sockets.

Parameters:
tm - an optional trust manager to use


getacl

public Map getacl(String mailbox)
            throws IOException
Returns the access control list for the specified mailbox. The returned rights are a logical OR of RIGHTS_* bits.

Parameters:
mailbox - the mailbox name

Returns:
a map of principal names to Integer rights


getquota

public Quota getquota(String quotaRoot)
            throws IOException
Returns the specified quota root's resource usage and limits.

Parameters:
quotaRoot - the quota root


getquotaroot

public Quota[] getquotaroot(String mailbox)
            throws IOException
Returns the quotas for the given mailbox.

Parameters:
mailbox - the mailbox name


invokeSimpleCommand

protected boolean invokeSimpleCommand(String command)
            throws IOException
Sends the specified IMAP command.

Parameters:
command - the command

Returns:
true if OK was received, or false if NO was received

Throws:
IOException - if BAD was received or an I/O error occurred


list

public ListEntry[] list(String reference,
                        String mailbox)
            throws IOException
Returns a subset of names from the compete set of names available to the client.

Parameters:
reference - the context relative to which mailbox names are defined
mailbox - a mailbox name, possibly including IMAP wildcards


listImpl

protected ListEntry[] listImpl(String command,
                               String reference,
                               String mailbox)
            throws IOException


listrights

public int listrights(String mailbox,
                      String principal)
            throws IOException
Returns the rights for the given principal for the specified mailbox. The returned rights are a logical OR of RIGHTS_* bits.

Parameters:
mailbox - the mailbox name
principal - the authentication identity


login

public boolean login(String username,
                     String password)
            throws IOException
Login to the connection using the username and password method.

Parameters:
username - the authentication principal
password - the authentication credentials

Returns:
true if authentication was successful, false otherwise


logout

public void logout()
            throws IOException
Logout this connection. Underlying network resources will be freed.


lsub

public ListEntry[] lsub(String reference,
                        String mailbox)
            throws IOException
Returns a subset of subscribed names.

See Also:
list(String,String)


myrights

public int myrights(String mailbox)
            throws IOException
Returns the rights for the current principal for the specified mailbox. The returned rights are a logical OR of RIGHTS_* bits.

Parameters:
mailbox - the mailbox name


namespace

public Namespaces namespace()
            throws IOException
Returns the namespaces available on the server. See RFC 2342 for details.


newTag

protected String newTag()
Returns a new tag for a command.


noop

public MailboxStatus noop()
            throws IOException
Ping the server. If a change in mailbox state is detected, a new mailbox status is returned, otherwise this method returns null.


readResponse

protected IMAPResponse readResponse()
            throws IOException
Reads an IMAP response from the server. The response will consist of either:
  • A tagged response corresponding to a pending command
  • An untagged error response
  • A continuation response


rename

public boolean rename(String source,
                      String target)
            throws IOException
Renames the source mailbox to the specified name.

Parameters:
source - the source mailbox name
target - the target mailbox name

Returns:
true if the mailbox was successfully renamed, false otherwise


search

public int[] search(String charset,
                    String[] criteria)
            throws IOException
Searches the currently selected mailbox for messages matching the specified criteria.


select

public MailboxStatus select(String mailbox)
            throws IOException
Selects the specified mailbox. The mailbox is identified as read-write if writes are permitted.

Parameters:
mailbox - the mailbox name

Returns:
a MailboxStatus containing the state of the selected mailbox


selectImpl

protected MailboxStatus selectImpl(String mailbox,
                                   String command)
            throws IOException


sendCommand

protected void sendCommand(String tag,
                           String command)
            throws IOException
Sends the specified IMAP tagged command to the server.


setAnsiDebug

public void setAnsiDebug(boolean flag)
Sets whether debugging output should use ANSI colour escape sequences.


setacl

public boolean setacl(String mailbox,
                      String principal,
                      int rights)
            throws IOException
Changes the access rights on the specified mailbox such that the authentication principal is granted the specified permissions.

Parameters:
mailbox - the mailbox name
principal - the authentication identifier
rights - the rights to assign


setquota

public Quota setquota(String quotaRoot,
                      Quota.Resource resources)
            throws IOException
Sets the quota for the specified quota root.

Parameters:
quotaRoot - the quota root
resources - the list of resources and associated limits to set

Returns:
the new quota, or null if the operation failed


starttls

public boolean starttls()
            throws IOException
Attempts to start TLS on the specified connection. See RFC 2595 for details.

Returns:
true if successful, false otherwise


starttls

public boolean starttls(TrustManager tm)
            throws IOException
Attempts to start TLS on the specified connection. See RFC 2595 for details.

Parameters:
tm - the custom trust manager to use

Returns:
true if successful, false otherwise


status

public MailboxStatus status(String mailbox,
                            String[] statusNames)
            throws IOException
Requests the status of the specified mailbox.


store

public MessageStatus[] store(int start,
                             int end,
                             String flagCommand,
                             String[] flags)
            throws IOException
Alters data associated with the specified range of messages in the mailbox.

Parameters:
start - the message number of the first message
end - the message number of the last message
flagCommand - FLAGS, +FLAGS, -FLAGS(or .SILENT versions)
flags - message flags to set

Returns:
a list of message-number to current flags


store

public MessageStatus store(int message,
                           String flagCommand,
                           String[] flags)
            throws IOException
Alters data associated with the specified message in the mailbox.

Parameters:
message - the message number
flagCommand - FLAGS, +FLAGS, -FLAGS(or .SILENT versions)
flags - message flags to set

Returns:
the message status


store

public MessageStatus[] store(int[] messages,
                             String flagCommand,
                             String[] flags)
            throws IOException
Alters data associated with messages in the mailbox.

Parameters:
messages - the message numbers
flagCommand - FLAGS, +FLAGS, -FLAGS(or .SILENT versions)
flags - message flags to set

Returns:
a list of message-number to current flags


subscribe

public boolean subscribe(String mailbox)
            throws IOException
Adds the specified mailbox to the set of subscribed mailboxes as returned by the LSUB command.

Parameters:
mailbox - the mailbox name

Returns:
true if the mailbox was successfully subscribed, false otherwise


uidFetch

public MessageStatus uidFetch(long uid,
                              String[] fetchCommands)
            throws IOException
Retrieves data associated with the specified message in the mailbox.

Parameters:
uid - the message UID
fetchCommands - the fetch commands, e.g. FLAGS


uidFetch

public MessageStatus[] uidFetch(long start,
                                long end,
                                String[] fetchCommands)
            throws IOException
Retrieves data associated with the specified range of messages in the mailbox.

Parameters:
start - the message number of the first message
end - the message number of the last message
fetchCommands - the fetch commands, e.g. FLAGS


uidFetch

public MessageStatus[] uidFetch(long[] uids,
                                String[] fetchCommands)
            throws IOException
Retrieves data associated with messages in the mailbox.

Parameters:
uids - the message UIDs
fetchCommands - the fetch commands, e.g. FLAGS


uidStore

public MessageStatus uidStore(long uid,
                              String flagCommand,
                              String[] flags)
            throws IOException
Alters data associated with the specified message in the mailbox.

Parameters:
uid - the message UID
flagCommand - FLAGS, +FLAGS, -FLAGS(or .SILENT versions)
flags - message flags to set

Returns:
the message status


uidStore

public MessageStatus[] uidStore(long start,
                                long end,
                                String flagCommand,
                                String[] flags)
            throws IOException
Alters data associated with the specified range of messages in the mailbox.

Parameters:
start - the UID of the first message
end - the UID of the last message
flagCommand - FLAGS, +FLAGS, -FLAGS(or .SILENT versions)
flags - message flags to set

Returns:
a list of message-number to current flags


uidStore

public MessageStatus[] uidStore(long[] uids,
                                String flagCommand,
                                String[] flags)
            throws IOException
Alters data associated with messages in the mailbox.

Parameters:
uids - the message UIDs
flagCommand - FLAGS, +FLAGS, -FLAGS(or .SILENT versions)
flags - message flags to set

Returns:
a list of message-number to current flags


unsubscribe

public boolean unsubscribe(String mailbox)
            throws IOException
Removes the specified mailbox from the set of subscribed mailboxes as returned by the LSUB command.

Parameters:
mailbox - the mailbox name

Returns:
true if the mailbox was successfully unsubscribed, false otherwise


updateMailboxStatus

protected boolean updateMailboxStatus(MailboxStatus ms,
                                      String id,
                                      IMAPResponse response)
            throws IOException


* IMAPConnection.java * Copyright (C) 2003,2004 The Free Software Foundation * * This file is part of GNU inetlib, a library. * * GNU inetlib is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * GNU inetlib is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Linking this library statically or dynamically with other modules is * making a combined work based on this library. Thus, the terms and * conditions of the GNU General Public License cover the whole * combination. * * As a special exception, the copyright holders of this library give you * permission to link this library with independent modules to produce an * executable, regardless of the license terms of these independent * modules, and to copy and distribute the resulting executable under * terms of your choice, provided that you also meet, for each linked * independent module, the terms and conditions of the license of that * module. An independent module is a module which is not derived from * or based on this library. If you modify this library, you may extend * this exception to your version of the library, but you are not * obliged to do so. If you do not wish to do so, delete this * exception statement from your version.