Content-type: text/html Manpage of IMAPTalk


Section: User Contributed Perl Documentation (3)
Updated: 2005-09-29
Index Return to Main Contents


Mail::IMAPTalk - IMAP client interface with lots of features  


  use Mail::IMAPTalk;

  $IMAP = Mail::IMAPTalk->new(
      Server   => $IMAPServer,
      Username => 'foo',
      Password => 'bar',
      Uid      => 1 )
    || die "Failed to connect/login to IMAP server";

  # Append message to folder
  open(my $F, 'rfc822msg.txt');
  $IMAP->append($FolderName, $F) || dir $@;

  # Select folder and get first unseen message
  $IMAP->select($FolderName) || die $@;
  $MsgId = $IMAP->search('not', 'seen')->[0];

  # Get message envelope and print some details
  $MsgEV = $IMAP->fetch($MsgId, 'envelope')->{$MsgId}->{envelope};
  print "From: " . $MsgEv->{From};
  print "To: " . $MsgEv->{To};
  print "Subject: " . $MsgEv->{Subject};

  # Get message body structure
  $MsgBS = $IMAP->fetch($MsgId, 'bodystructure')->{$MsgId}->{bodystructure};

  # Find imap part number of text part of message
  $MsgTxtHash = Mail::IMAPTalk::find_message($MsgBS);
  $MsgPart = $MsgTxtHash->{plain}->{'IMAP-Partnum'};

  # Retrieve message text body
  $MsgTxt = $IMAP->fetch($MsgId, "body[$MsgPart]")->{$MsgId}->{body};




This module communicates with an IMAP server. Each IMAP server command is mapped to a method of this object.

Although other IMAP modules exist on CPAN, this has several advantages over other modules.

It parses the more complex IMAP structures like envelopes and body structures into nice Perl data structures.
It correctly supports atoms, quoted strings and literals at any point. Some parsers in other modules aren't fully IMAP compatiable and may break at odd times with certain messages on some servers.
It allows large return values (eg. attachments on a message) to be read directly into a file, rather than into memory.
It includes some helper functions to find the actual text/plain or text/html part of a message out of a complex MIME structure. It also can find a list of attachements, and CID links for HTML messages with attached images.
It supports decoding of MIME headers to Perl utf-8 strings automatically, so you don't have to deal with MIME encoded headers (enabled optionally).

While the IMAP protocol does allow for asynchronous running of commands, this module is designed to be used in a synchronous manner. That is, you issue a command by calling a method, and the command will block until the appropriate response is returned. The method will then return the parsed results from the given command.  


The object methods have been broken in several sections.  


Lists the available constants the class uses.
Explains all the options available when constructing a new instance of the "Mail::IMAPTalk" class.
These are methods which control the overall IMAP connection object, such as logging in and logging out, how results are parsed, how folder names and message id's are treated, etc.
These are methods to inspect, add, delete and rename IMAP folders on the server.
These are methods to retrieve, delete, move and add messages to/from IMAP folders.
These are extra methods that users of this class might find useful. They generally do extra parsing on returned structures to provide higher level functionality.
These are methods used internally by the "Mail::IMAPTalk" object to get work done. They may be useful if you need to extend the class yourself. Note that internal methods will always 'die' if they encounter any errors.
These are functions used internally by the "Mail::IMAPTalk" object to read/write data to/from the IMAP connection socket. The class does its own buffering so if you want to read/write to the IMAP socket, you should use these functions.
These are functions used to parse the results returned from the IMAP server into Perl style data structures.

Method results

All methods return undef on failure. There are four main modes of failure:
1. An error occurred reading/writing to a socket. Maybe the server closed it, or you're not connected to any server.
2. An error occurred parsing the response of an IMAP command. This is usually only a problem if your IMAP server returns invalid data.
3. An IMAP command didn't return an 'OK' response.
4. The socket read operation timed out waiting for a response from the server.

In each case, some readable form of error text is placed in $@, or you can call the "get_last_error()" method. For commands which return responses (e.g. fetch, getacl, etc), the result is returned. See each command for details of the response result. For commands with no response but which succeed (e.g. setacl, rename, etc) the result 'ok' is generally returned.  

Method parameters

All methods which send data to the IMAP server (e.g. "fetch()", "search()", etc) have their arguments processed before they are sent. Arguments may be specified in several ways:
The value is first checked and quoted if required. Values containing [\000\012\015] are turned into literals, values containing [\000-\040\{\} \%\*\``] are quoted by surrounding with a ''...`` pair (any '' themselves are turned into \").
file ref
The contents of the file is sent as an IMAP literal. Note that because IMAPTalk has to know the length of the file being sent, this must be a true file reference that can be seeked and not just some stream. The entire file will be sent regardless of the current seek point.
array ref
The array reference should contain only 2 items. The first item is a text string which specifies what to do with the second item of the array ref.
* 'Literal'
The string/data in the second item should be sent as an IMAP literal regardless of the actually data in the string/data.
* 'NoQuote'
The string/data in the second item should be sent as is, no quoting will occur, and the data won't be sent as quoted or as a literal regardless of the contents of the string/data.


    # Password is automatically quoted to "nasty%*\"passwd"
    $IMAP->login("joe", 'nasty%*"passwd');
    # Append $MsgTxt as string
    $IMAP->append("inbox", [ 'Literal', $MsgTxt ])
    # Append MSGFILE contents as new message
    $IMAP->append("inbox", \*MSGFILE ])



These constants relate to the standard 4 states that an IMAP connection can be in. They are passed and returned from the "state()" method. See RFC2060 for more details about IMAP connection states.
Current not connected to any server.
Connected to a server, but not logged in.
Connected and logged into a server, but not current folder.
Connected, logged in and have 'select'ed a current folder.


Creates new Mail::IMAPTalk object. The following options are supported.
Connection Options
The hostname or IP address to connect to. This must be supplied unless the Socket option is supplied.
The port number on the host to connect to. Defaults to 143 if not supplied.
An existing socket to use as the connection to the IMAP server. If you supply the Socket option, you should not supply a Server or Port option.

This is useful if you want to create an SSL socket connection using IO::Socket::SSL and then pass in the connected socket to the new() call.

It's also useful in conjunction with the "release_socket()" method described below for reusing the same socket beyond the lifetime of the IMAPTalk object. See a description in the section "release_socket()" method for more information.

You must have write flushing enabled for any socket you pass in here so that commands will actually be sent, and responses received, rather than just waiting and eventually timing out. you can do this using the Perl "select()" call and $| ($AUTOFLUSH) variable as shown below.

  my $ofh = select($Socket); $| = 1; select ($ofh);

If you supply a "Socket" option, you can specify the IMAP state the socket is currently in, namely one of 'Unconnected', 'Connected', 'Authenticated' or 'Selected'. This defaults to 'Connected' if not supplied and the "Socket" option is supplied.
If supplied and true, and a socket is supplied via the "Socket" option, checks that a greeting line is supplied by the server and reads the greeting line.
Login Options
The username to connect to the IMAP server as. If not supplied, no login is attempted and the IMAP object is left in the CONNECTED state. If supplied, you must also supply the Password option and a login is attempted. If the login fails, the connection is closed and undef is returned. If you want to do something with a connection even if the login fails, don't pass a Username option, but instead use the login method described below.
The password to use to login to the account.
IMAP message/folder options
Control whether message ids are message uids or not. This is 1 (on) by default because generally that's how most people want to use it. This affects most commands that require/use/return message ids (e.g. fetch, search, sort, etc)
If supplied, sets the root folder prefix. This is the same as calling "set_root_folder()" with the value passed. If no value is supplied, "set_root_folder()" is called with no value. See the "set_root_folder()" method for more details.
If supplied, sets the folder name text string separator character. Passed as the second parameter to the "set_root_folder()" method.
If supplied, passed along with RootFolder to the "set_root_folder()" method.
If supplied, passed along with RootFolder to the "set_root_folder()" method.


  $imap = Mail::IMAPTalk->new(
            Server          => '',
            Port            => 143,
            Username        => 'joebloggs',
            Password        => 'mypassword',
            Separator       => '.',
            RootFolder      => 'inbox',
            CaseInsensitive => 1)
          || die "Connection to failed. Reason: $@";

  $imap = Mail::IMAPTalk->new(
            Socket => $SSLSocket,
            State  => Mail::IMAPTalk::Authenticated,
            Uid    => 0)
          || die "Could not query on existing socket. Reason: $@";



login($UserName, $Password)
Attempt to login user specified username and password.

Currently there is only plain text password login support. If someone can give me a hand implementing others (like DIGEST-MD5, CRAM-MD5, etc) please contact me (see details below).

Log out of IMAP server. This usually closes the servers connection as well.
state(optional $State)
Set/get the current IMAP connection state. Returned or passed value should be one of the constants (Unconnected, Connected, Authenticated, Selected).
uid(optional $UidMode)
Get/set the UID status of all UID possible IMAP commands. If set to 1, all commands that can take a UID are set to 'UID Mode', where any ID sent to IMAPTalk is assumed to be a UID.
This method returns the IMAP servers capability command results. The result is a hash reference of (lc(Capability) => 1) key value pairs. This means you can do things like:

  if ($IMAP->capability()->{quota}) { ... }

to test if the server has the QUOTA capability. If you just want a list of capabilities, use the Perl 'keys' function to get a list of keys from the returned hash reference.

Returns the result of the IMAP servers namespace command.
Perform the standard IMAP 'noop' command which does nothing.
Returns true if the current socket connection is still open (e.g. the socket hasn't been closed this end or the other end due to a timeout).
set_root_folder($RootFolder, $Separator, optional $CaseInsensitive, $AltRoot)
Change the root folder prefix. Some IMAP servers require that all user folders/mailboxes live under a root folder prefix (current versions of cyrus for example use 'INBOX' for personal folders and 'user' for other users folders). If no value is specified, it sets it to ''. You might want to use the namespace() method to find out what roots are available. The $CaseInsensitive argument is a flag that determines whether the root folder should be matched in a case sensitive or insensitive way. See below.

Setting this affects all commands that take a folder argument. Basically if the foldername begins with root folder prefix (case sensitive or insensitive based on the second argument), it's left as is, otherwise the root folder prefix and separator char are prefixed to the folder name.


  # This is what cyrus uses
  $IMAP->set_root_folder('inbox', '.', 1, 'user');

  # Selects 'Inbox' (because 'Inbox' eq 'inbox' case insensitive)
  # Selects 'inbox.blah'
  # Selects 'INBOX.fred' (because 'INBOX' eq 'inbox' case insensitive)
  #IMAP->select('INBOX.fred'); # Selects 'INBOX.fred'
  # Selects 'user.john' (because 'user' is alt root)
  #IMAP->select('user.john'); # Selects 'user.john'

Checks if the given separator is the same as the one we used before. If not, it calls set_root_folder to recreate the settings with the new Separator.
literal_handle_control(optional $FileHandle)
Sets the mode whether to read literals as file handles or scalars.

You should pass a filehandle here that any literal will be read into. To turn off literal reads into a file handle, pass a 0.


  # Read rfc822 text of message 3 into file
  # (note that the file will have /r/n line terminators)
  open(F, ">messagebody.txt");
  $IMAP->fetch(3, 'rfc822');

Release IMAPTalk's ownership of the current socket it's using so it's not disconnected on DESTROY. This returns the socket, and makes sure that the IMAPTalk object doesn't hold a reference to it any more. This means you can't call any methods on the IMAPTalk object any more.
Returns a text string which describes the last error that occurred.
Returns the extra response data generated by a previous call. This is most often used after calling select which usually generates some set of the following sub-results.
* permanentflags
Array reference of flags which are stored permanently.
* uidvalidity
Whether the current UID set is valid. See the IMAP RFC for more information on this. If this value changes, then all UIDs in the folder have been changed.
* uidnext
The next UID number that will be assigned.
* exists
Number of messages that exist in the folder.
* recent
Number of messages that are recent in the folder.

Other possible responses are alert, newname, parse, trycreate, appenduid.


  # Select inbox and get list of permanent flags, uidnext and number
  #  of message in the folder
  my $NMessages = $IMAP->get_sub_result('exists');
  my $PermanentFlags = $IMAP->get_sub_result('permanentflags');
  my $UidNext = $IMAP->get_sub_result('uidnext');

Clears any response code information. Response code information is not normally cleared between calls.
parse_mode(ParseOption => $ParseMode)
Changes how results of fetch commands are parsed. Available options are:
Parse bodystructure into more Perl-friendly structure See the FETCH RESULTS section.
Parse envelopes into more Perl-friendly structure See the FETCH RESULTS section.
If parsing envelopes, create To/Cc/Bcc and Raw-To/Raw-Cc/Raw-Bcc entries which are array refs of 4 entries each as returned by the IMAP server.
If parsing envelopes, decode any MIME encoded headers into Perl UTF-8 strings.

For this to work, you must have 'used' Mail::IMAPTalk with:

use Mail::IMAPTalk qw(:utf8support ...)

set_tracing($Tracer, $ClearEachCmd)
Allows you to trace both IMAP input and output sent to the server and returned from the server. This is useful for debugging. Returns the previous value of the tracer and then sets it to the passed value. Possible values for $Tracer are:
Disable all tracing.
Print to STDERR.
Code ref
Call code ref for each line input and output. Pass line as parameter.
Glob ref
Print to glob.
Scalar ref
Appends to the referenced scalar.

Note: literals are never passed to the tracer.

If $ClearEachCmd is set, and a scalar ref is used, then the scalar ref value is cleared to '' at the start of each command. This allows you to trace, but only keep details for the last issued command in the trace variable

set_callbacks(Callback => sub { }, [ ... Callback => sub { } ], ... )
Allows you to set callbacks when certain functions are called. This can be useful for keep track of certain actions so you can work out if a folder's message count or size is invalid.
Called if a message is added to/deleted from a folder.


Note: In all cases where a folder name is used, the folder name is first manipulated according to the current root folder prefix as described in "set_root_folder()".
select($FolderName, $ReadOnly)
Perform the standard IMAP 'select' command to select a folder for retrieving/moving/adding messages. If $ReadOnly is defined, the IMAP EXAMINE verb is used instead of SELECT.
Performs the standard IMAP unselect command.
Perform the standard IMAP 'examine' command to select a folder in read only mode for retrieving messages. This is the same as "select($FolderName, 1)". See "select()" for more details.
Perform the standard IMAP 'create' command to create a new folder.
Perform the standard IMAP 'delete' command to delete a folder.
rename($OldFolderName, $NewFolderName)
Perform the standard IMAP 'rename' command to rename a folder.
list($Reference, $Name)
Perform the standard IMAP 'list' command to return a list of available folders.
lsub($Reference, $Name)
Perform the standard IMAP 'lsub' command to return a list of subscribed folders
Perform the standard IMAP 'subscribe' command to subscribe to a folder.
Perform the standard IMAP 'unsubscribe' command to unsubscribe from a folder.
Perform the standard IMAP 'check' command to checkpoint the current folder.
setacl($FolderName, $User, $Rights)
Perform the IMAP 'setacl' command to set the access control list details of a folder/mailbox. See RFC2086 for more details on the IMAP ACL extension. $User is the user name to set the access rights for. $Rights is either a list of absolute rights to set, or a list prefixed by a - to remove those rights, or a + to add those rights.
l - lookup (mailbox is visible to LIST/LSUB commands)
r - read (SELECT the mailbox, perform CHECK, FETCH, PARTIAL, SEARCH, COPY from mailbox)
s - keep seen/unseen information across sessions (STORE SEEN flag)
w - write (STORE flags other than SEEN and DELETED)
i - insert (perform APPEND, COPY into mailbox)
p - post (send mail to submission address for mailbox, not enforced by IMAP4 itself)
c - create (CREATE new sub-mailboxes in any implementation-defined hierarchy)
d - delete (STORE DELETED flag, perform EXPUNGE)
a - administer (perform SETACL)

The standard access control configurations for cyrus are

read = lrs
post = lrsp
append = lrsip
write = lrswipcd
all = lrswipcda


  # Get full access for user 'joe' on his own folder
  $IMAP->setacl('user.joe', 'joe', 'lrswipcda') || die "IMAP error: $@";
  # Remove write, insert, post, create, delete access for user 'andrew'
  $IMAP->setacl('user.joe', 'andrew', '-wipcd') || die "IMAP error: $@";
  # Add lookup, read, keep unseen information for user 'paul'
  $IMAP->setacl('user.joe', 'paul', '+lrs') || die "IMAP error: $@";

Perform the IMAP 'getacl' command to get the access control list details of a folder/mailbox. See RFC2086 for more details on the IMAP ACL extension. Returns an array of pairs. Each pair is a username followed by the access rights for that user. See setacl for more information on access rights.


  my $Rights = $IMAP->getacl('user.joe') || die "IMAP error : $@";
  $Rights = [
    'joe', 'lrs',
    'andrew', 'lrswipcda'

  $IMAP->setacl('user.joe', 'joe', 'lrswipcda') || die "IMAP error : $@";
  $IMAP->setacl('user.joe', 'andrew', '-wipcd') || die "IMAP error : $@";
  $IMAP->setacl('user.joe', 'paul', '+lrs') || die "IMAP error : $@";

  $Rights = $IMAP->getacl('user.joe') || die "IMAP error : $@";
  $Rights = [
    'joe', 'lrswipcd',
    'andrew', 'lrs',
    'paul', 'lrs'

deleteacl($FolderName, $Username)
Perform the IMAP 'deleteacl' command to delete all access control information for the given user on the given folder. See setacl for more information on access rights.


  my $Rights = $IMAP->getacl('user.joe') || die "IMAP error : $@";
  $Rights = [
    'joe', 'lrswipcd',
    'andrew', 'lrs',
    'paul', 'lrs'

  # Delete access information for user 'andrew'
  $IMAP->deleteacl('user.joe', 'andrew') || die "IMAP error : $@";

  $Rights = $IMAP->getacl('user.joe') || die "IMAP error : $@";
  $Rights = [
    'joe', 'lrswipcd',
    'paul', 'lrs'

setquota($FolderName, $QuotaDetails)
Perform the IMAP 'setquota' command to set the usage quota details of a folder/mailbox. See RFC2087 for details of the IMAP quota extension. $QuotaDetails is a bracketed list of limit item/value pairs which represent a particular type of limit and the value to set it to. Current limits are:
STORAGE - Sum of messages' RFC822.SIZE, in units of 1024 octets
MESSAGE - Number of messages


  # Set maximum size of folder to 50M and 1000 messages
  $IMAP->setquota('user.joe', '(storage 50000)') || die "IMAP error: $@";
  $IMAP->setquota('user.john', '(messages 1000)') || die "IMAP error: $@";
  # Remove quotas
  $IMAP->setquota('user.joe', '()') || die "IMAP error: $@";

Perform the standard IMAP 'getquota' command to get the quota details of a folder/mailbox. See RFC2087 for details of the IMAP quota extension. Returns an array reference to quota limit triplets. Each triplet is made of: limit item, current value, maximum value.

Note that this only returns the quota for a folder if it actually has had a quota set on it. It's possible that a parent folder might have a quota as well which affects sub-folders. Use the getquotaroot to find out if this is true.


  my $Result = $IMAP->getquota('user.joe') || die "IMAP error: $@";
  $Result = [
    'STORAGE', 31, 50000,
    'MESSAGE', 5, 1000

Perform the IMAP 'getquotaroot' command to get the quota details of a folder/mailbox and possible root quota as well. See RFC2087 for details of the IMAP quota extension. The result of this command is a little complex. Unfortunately it doesn't map really easily into any structure since there are several different responses.

Basically it's a hash reference. The 'quotaroot' item is the response which lists the root quotas that apply to the given folder. The first item is the folder name, and the remaining items are the quota root items. There is then a hash item for each quota root item. It's probably easiest to look at the example below.


  my $Result = $IMAP->getquotaroot('user.joe.blah') || die "IMAP error: $@";
  $Result = {
    'quotaroot' => [
      'user.joe.blah', 'user.joe', ''
    'user.joe' => [
      'STORAGE', 31, 50000,
      'MESSAGES', 5, 1000
    '' => [
      'MESSAGES', 3498, 100000

Return the number of messages in a folder. See also "status()" for getting more information about messages in a folder.
status($FolderName, $StatusList)
Perform the standard IMAP 'status' command to retrieve status information about a folder/mailbox.

The $StatusList is a bracketed list of folder items to obtain the status of. Can contain: messages, recent, uidnext, uidvalidity, unseen.

The return value is a hash reference of lc(status-item) => value.


  my $Res = $IMAP->status('inbox', '(MESSAGES UNSEEN)');

  $Res = {
    'messages' => 8,
    'unseen' => 2

multistatus($StatusList, @FolderNames)
Performs many IMAP 'status' commands on a list of folders. Sends all the commands at once and wait for responses. This speeds up latency issues.

Returns a hash ref of folder name => status results.

getannotation($FolderName, $Entry, $Attribute)
Perform the IMAP 'getannotation' command to get the annotation(s) for a mailbox. See imap-annotatemore extension for details.


  my $Result = $IMAP->getannotation('user.joe.blah', '/*' '*') || die "IMAP error: $@";
  $Result = {
    'user.joe.blah' => {
      '/vendor/cmu/cyrus-imapd/size' => {
        'size.shared' => '5',
        'content-type.shared' => 'text/plain',
        'value.shared' => '19261'
      '/vendor/cmu/cyrus-imapd/lastupdate' => {
        'size.shared' => '26',
        'content-type.shared' => 'text/plain',
        'value.shared' => '26-Mar-2004 13:31:56 -0800'
      '/vendor/cmu/cyrus-imapd/partition' => {
        'size.shared' => '7',
        'content-type.shared' => 'text/plain',
        'value.shared' => 'default'

setannotation($FolderName, $Entry, $Attribute, [ $Entry, $Attribute ], ... )
Perform the IMAP 'setannotation' command to get the annotation(s) for a mailbox. See imap-annotatemore extension for details.


  my $Result = $IMAP->setannotation('user.joe.blah', '/comment', [ 'value.priv' 'A comment' ])
    || die "IMAP error: $@";

Perform the standard IMAP 'close' command to expunge deleted messages from the current folder and return to the Authenticated state.


fetch($MessageIds, $MessageItems)
Perform the standard IMAP 'fetch' command to retrieve the specified message items from the specified message IDs.

$MessageIds can be one of two forms:

A text string with a comma separated list of message ID's or message ranges separated by colons. A '*' represents the highest message number.


* '1' - first message
* '1,2,5'
* '1:*' - all messages
* '1,3:*' - all but message 2

Note that , separated lists and : separated ranges can be mixed, but to make sure a certain hack works, if a '*' is used, it must be the last character in the string.

An array reference with a list of message ID's or ranges. The array contents are "join(',', ...)"ed together.

Note: If the "uid()" state has been set to true, then all message ID's must be message UIDs.

$MessageItems can be one of, or a bracketed list of:

* uid
* flags
* internaldate
* envelope
* bodystructure
* body
* body[section]<partial>
* body.peek[section]<partial>
* rfc822
* rfc822.header
* rfc822.size
* rfc822.text
* fast
* all
* full

It would be a good idea to see RFC2060 for what all these means.


  my $Res = $IMAP->fetch('1:*', 'rfc822.size');
  my $Res = $IMAP->fetch([1,2,3], '(bodystructure envelope)');

Return results:

The results returned by the IMAP server are parsed into a Perl structure. See the section FETCH RESULTS for all the interesting details.

For some servers (cyrus at least), if you do a fetch on a message id which doesn't exist, you still get an OK response. I didn't feel this was really very useful so if no data was retrieved, undef is returned.

copy($MsgIds, $ToFolder)
Perform standard IMAP copy command to copy a set of messages from one folder to another.
append($FolderName, optional $MsgFlags, optional $MsgDate, $MessageData)
Perform standard IMAP append command to append a new message into a folder.

The $MessageData to append can either be a Perl scalar containing the data, or a file handle to read the data from. In each case, the data must be in proper RFC822 format with \r\n line terminators.

Any optional fields not needed should be removed, not left blank.


  # msg.txt should have \r\n line terminators
  open(F, "msg.txt");
  $IMAP->append('inbox', \*F);

  my $MsgTxt =<<MSG;
  From: blah\
  To: whoever\

  $MsgTxt =~ s/\n/\015\012/g;
  $IMAP->append('inbox', [ 'Literal', $MsgTxt ]);

search($MsgIdSet, @SearchCriteria)
Perform standard IMAP search command. The result is an array reference to a list of message IDs (or UIDs if in Uid mode) of messages that are in the $MsgIdSet and also meet the search criteria.

@SearchCriteria is a list of search specifications, for example to look for ASCII messages bigger than 2000 bytes you would set the list to be:

  my @SearchCriteria = ('CHARSET', 'US-ASCII', 'LARGER', '2000');


  my $Res = $IMAP->search('1:*', 'NOT', 'DELETED');
  $Res = [ 1, 2, 5 ];

store($MsgIdSet, $FlagOperation, $Flags)
Perform standard IMAP store command. Changes the flags associated with a set of messages.


  $IMAP->store('1:*', '+flags', '(\\deleted)');
  $IMAP->store('1:*', '-flags.silent', '(\\read)');

Perform standard IMAP expunge command. This actually deletes any messages marked as deleted.
Perform IMAP uid expunge command as per RFC 2359.
sort($SortField, $CharSet, @SearchCriteria)
Perform extension IMAP sort command. The result is an array reference to a list of message IDs (or UIDs if in Uid mode) in sorted order.

It would probably be a good idea to look at the sort extension details at somewhere like :


  my $Res = $IMAP->sort('(subject)', 'US-ASCII', 'NOT', 'DELETED');
  $Res = [ 5, 2, 3, 1, 4 ];

thread($ThreadType, $CharSet, @SearchCriteria)
Perform extension IMAP thread command. The $ThreadType should be one of 'REFERENCES' or 'ORDEREDSUBJECT'. You should check the "capability()" of the server to see if it supports one or both of these.


  my $Res = $IMAP->thread('REFERENCES', 'US-ASCII', 'NOT', 'DELETED');
  $Res = [ [10, 15, 20], [11], [ [ 12, 16 ], [13, 17] ];

Perform an IMAP 'fetch flags' command to retrieve the specified flags for the specified messages.

This is just a special fast path version of "fetch".



get_body_part($BodyStruct, $PartNum)
This is a helper function that can be used to further parse the results of a fetched bodystructure. Given a top level body structure, and a part number, it returns the reference to the bodystructure sub part which that part number refers to.


  # Fetch body structure
  my $FR = $IMAP->fetch(1, 'bodystructure');
  my $BS = $FR->{1}->{bodystructure};

  # Parse further to find particular sub part
  my $P12 = $IMAP->get_body_part($BS, '1.2');
  $P12->{'IMAP->Partnum'} eq '1.2' || die "Unexpected IMAP part number";

This is a helper function that can be used to further parse the results of a fetched bodystructure. It returns a hash reference which always contains a 'text' item, and possibly an 'html' item. In each case, the values of each hash item are references into the body structure of the corresponding message part.


  # Fetch body structure
  my $FR = $IMAP->fetch(1, 'bodystructure');
  my $BS = $FR->{1}->{bodystructure};

  # Parse further to find message components
  my $MC = $IMAP->find_message($BS);
  $MC = { 'plain' => ... text body struct ref part ...,
          'html' => ... html body struct ref part (if present) ... };

  # Now get the text part of the message
  my $MT = $IMAP->fetch(1, 'body[' . $MC->{plain}->{'IMAP-Part'} . ']');

This is a helper function that can be used to further parse the results of a fetched bodystructure. It recursively parses the bodystructure and returns a hash of Content-ID to bodystruct part references. This is useful when trying to determine CID links from an HTML message.


  # Fetch body structure
  my $FR = $IMAP->fetch(1, 'bodystructure');
  my $BS = $FR->{1}->{bodystructure};

  # Parse further to get CID links
  my $CL = $IMAP->build_cid_map($BS);
  $CL = { '2958293123' => ... ref to body part ..., ... };



The 'fetch' operation is probably the most common thing you'll do with an IMAP connection. This operation allows you to retrieve information about a message or set of messages, including header fields, flags or parts of the message body.

"Mail::IMAPTalk" will always parse the results of a fetch call into a Perl like structure, though 'bodystructure', 'envelope' and 'uid' responses may have additional parsing depending on the "parse_mode" state and the "uid" state (see below).

For an example case, consider the following IMAP commands and responses (C is what the client sends, S is the server response).

  C: a100 fetch 5,6 (flags rfc822.size uid)
  S: * 1 fetch (UID 1952 FLAGS (\recent \seen) RFC822.SIZE 1150)
  S: * 2 fetch (UID 1958 FLAGS (\recent) RFC822.SIZE 110)
  S: a100 OK Completed

The fetch command can be sent by calling:

  my $Res = $IMAP->fetch('1:*', '(flags rfc822.size uid)');

The result in response will look like this:

  $Res = {
    1 => {
      'uid' => 1952,
      'flags' => [ '\\recent', '\\seen' ],
      'rfc822.size' => 1150
    2 => {
      'uid' => 1958,
      'flags' => [ '\\recent' ],
      'rfc822.size' => 110

A couple of points to note:

The message IDs have been turned into a hash from message ID to fetch response result.
The response items (e.g. uid, flags, etc) have been turned into a hash for each message, and also changed to lower case values.
Other bracketed (...) lists have become array references.

In general, this is how all fetch responses are parsed when the "parse_mode" is set to 0. There is one major difference however when the IMAP connection is in 'uid' mode. In this case, the message IDs in the main hash are changed to message UIDs, and the 'uid' entry in the inner hash is removed. So the above example would become:

  my $Res = $IMAP->fetch('1:*', '(flags rfc822.size)');

  $Res = {
    1952 => {
      'flags' => [ '\\recent', '\\seen' ],
      'rfc822.size' => 1150
    1958 => {
      'flags' => [ '\\recent' ],
      'rfc822.size' => 110



When dealing with messages, we need to understand the MIME structure of the message, so we can work out what is the text body, what is attachments, etc. This is where the 'bodystructure' item from an IMAP server comes in.

  C: a101 fetch 1 (bodystructure)
  S: a101 OK Completed

The fetch command can be sent by calling:

  my $Res = $IMAP->fetch(1, 'bodystructure');

As expected, the resultant response would look like this:

  $Res = {
    1 => {
      'bodystructure' => [
        'TEXT', 'PLAIN', undef, undef, undef, 'QUOTED-PRINTABLE',
          255, 11, UNDEF, [ 'INLINE', undef ], undef

However, if you set the "parse_mode" state to 1, then the result would be:

  $Res = {
    '1' => {
      'bodystructure' => {
        'MIME-Type' => 'text',
        'MIME-Subtype' => 'plain',
        'MIME-TxtType' => 'text/plain',
        'Content-Type' => {},
        'Content-ID' => undef,
        'Content-Description' => undef,
        'Content-Transfer-Encoding' => 'QUOTED-PRINTABLE',
        'Size' => '3569',
        'Lines' => '94',
        'Content-MD5' => undef,
        'Content-Disposition' => [
        'Content-Language' => undef,
        'Remainder' => [],
        'IMAP-Partnum' => ''

A couple of points to note here:

All the fields have been turned into nicely named hash items.
The MIME-Type and MIME-Subtype fields have been made lower case.
An IMAP-Partnum item has been added. The value in this field can be passed as the 'section' number of an IMAP body fetch call to retrieve the text of that IMAP section.

In general, the following items are defined for all body structures:

* MIME-Type
* MIME-Subtype
* Content-Type
* Content-Disposition
* Content-Language

For all items EXCEPT those that have a MIME-Type of 'multipart', the following are defined:

* Content-ID
* Content-Description
* Content-Transfer-Encoding
* Size
* Content-MD5
* Remainder
* IMAP-Partnum

For items where MIME-Type is 'text', an extra field 'Lines' is defined.

For items where MIME-Type is 'message' and MIME-Subtype is 'rfc822', the extra fields 'Message-Envelope', 'Message-Bodystructure' and 'Message-Lines' are defined. The 'Message-Bodystructure' field is itself a hash references to an entire bodystructure hash with all the format information of the contained message. The 'Message-Envelope' field is a hash structure with the message header information. See the Envelope entry below.

For items where MIME-Type is 'multipart', an extra field 'MIME-Subparts' is defined. The 'MIME-Subparts' field is an array reference, with each item being a hash reference to an entire bodystructure hash with all the format information of each MIME sub-part.

For further processing, you can use the find_message() function. This will analyse the body structure and find which part corresponds to the main text/html message parts to display. You can also use the find_cid_parts() function to find CID links in an html message.  


The envelope structure contains most of the addressing header fields from an email message. The following shows an example envelope fetch (the response from the IMAP server has been neatened up here)

  C: a102 fetch 1 (envelope)
      ("Tue, 7 Nov 2000 08:31:21 UT"      # Date
       "FW: another question"             # Subject
       (("John B" NIL "jb" ""))    # From
       (("John B" NIL "jb" ""))    # Sender
       (("John B" NIL "jb" ""))    # Reply-To
       (("Bob H" NIL "bh" "")      # To
        ("K Jones" NIL "kj" ""))
       NIL                                # Cc
       NIL                                # Bcc
       NIL                                # In-Reply-To
       NIL)                               # Message-ID
  S: a102 OK Completed

The fetch command can be sent by calling:

  my $Res = $IMAP->fetch(1, 'envelope');

And you get the idea of what the resultant response would be. Again if you change "parse_mode" to 1, you get a neat structure as follows:

  $Res = {
    '1' => {
      'envelope' => {
        'Date' => 'Tue, 7 Nov 2000 08:31:21 UT',
        'Subject' => 'FW: another question',
        'From' => '"John B" <>',
        'Sender' => '"John B" <>',
        'Reply-To' => '"John B" <>',
        'To' => '"Bob H" <>, "K Jones" <>',
        'Cc' => '',
        'Bcc' => '',
        'In-Reply-To' => undef,
        'Message-ID' => undef,

        'From-Raw' => [ [ 'John B', undef, 'jb', '' ] ],
        'Sender-Raw' => [ [ 'John B', undef, 'jb', '' ] ],
        'Reply-To-Raw' => [ [ 'John B', undef, 'jb', '' ] ],
        'To-Raw' => [
          [ 'Bob H', undef, 'bh', '' ],
          [ 'K Jones', undef, 'kj', '' ],
        'Cc-Raw' => [],
        'Bcc-Raw' => [],

All the fields here are from straight from the email headers. See RFC822 for more details.  


_imap_cmd($Command, $IsUidCmd, $RespItems, @Args)
Executes a standard IMAP command.
Method arguments
Text string of command to call IMAP server with (e.g. 'select', 'search', etc).
1 if command involved message ids and can be prefixed with UID, 0 otherwise.
Responses to look for from command (eg 'list', 'fetch', etc). Commands which return results usually return them untagged. The following is an example of fetching flags from a number of messages.

  C123 uid fetch 1:* (flags)
  * 1 FETCH (FLAGS (\Seen) UID 1)
  * 2 FETCH (FLAGS (\Seen) UID 2)
  C123 OK Completed

Between the sending of the command and the 'OK Completed' response, we have to pick up all the untagged 'FETCH' response items so we would pass 'fetch' (always use lower case) as the $RespItems to extract.

Any extra arguments to pass to command.
_send_cmd($Self, $Cmd, @InArgs)
Helper method used by the _imap_cmd method to actually build (and quote where necessary) the command arguments and then send the actual command.
_parse_response($Self, $RespItems)
Helper method called by _imap_cmd after sending the command. This methods retrieves data from the IMAP socket and parses it into Perl structures and returns the results.
_require_capability($Self, $Capability)
Helper method which checks that the server has a certain capability. If not, it sets the internal last error, $@ and returns undef.
_trace($Self, $Line)
Helper method which outputs any tracing data.
_signal($Self, $Type, @Items)
Send a signal to a callback.


Returns the next atom from the current line. Uses $Self->{ReadLine} for line data, or if undef, fills it with a new line of data from the IMAP connection socket and then begins processing.

If the next atom is:

An unquoted string, simply returns the string.
A quoted string, unquotes the string, changes any occurances of \`` to '' and returns the string.
A literal (e.g. {NBytes}\r\n), reads the number of bytes of data in the literal into a scalar or file (depending on "literal_handle_control").
A bracketed structure, reads all the sub-atoms within the structure and returns an array reference with all the sub-atoms.

In each case, after parsing the atom, it removes any trailing space separator, and then returns the remainder of the line to $Self->{ReadLine} ready for the next call to "_next_atom()".

Returns all the remaining atoms for the current line in the read line buffer as an array reference. Leaves $Self->{ReadLine} eq ''. See "_next_atom()"
Returns the remaining data in the read line buffer ($Self->{ReadLine}) as a scalar string/data value.
Wait until data is available on the IMAP connection socket (or a timeout occurs). Read the data into the internal buffer $Self->{ReadBuf}. You can then use "_imap_socket_read_line()", "_imap_socket_read_bytes()" or "_copy_imap_socket_to_handle()" to read data from the buffer in lines or bytes at a time.
Read a \r\n terminated list from the buffered IMAP connection socket.
_imap_socket_read_bytes($Self, $NBytes)
Read a certain number of bytes from the buffered IMAP connection socket.
_imap_socket_out($Self, $Data)
Write the data in $Data to the IMAP connection socket.
_copy_handle_to_handle($Self, $InHandle $OutHandle, $NBytes)
Copy a given number of bytes from one handle to another.

The number of bytes specified ($NBytes) must be available on the IMAP socket, otherwise the function will 'die' with an error if it runs out of data.

If $NBytes is not specified (undef), the function will attempt to seek to the end of the file to find the size of the file.

_copy_imap_socket_to_handle($Self, $OutHandle, $NBytes)
Copies data from the IMAP socket to a file handle. This is different to _copy_handle_to_handle() because we internally buffer the IMAP socket so we can't just use it to copy from the socket handle, we have to copy the contents of our buffer first.

The number of bytes specified must be available on the IMAP socket, if the function runs out of data it will 'die' with an error.

Returns an IMAP quoted version of a string. This place ``...'' around the string, and replaces any internal `` with \''.
For each item in @Items: 1. If it's a string, quote as ``...'' 2. If it's an array ref, place in (...) and quote each item.

Returns a list as long as @Items.



_parse_list_to_hash($ListRef, $Recursive)
Parses an array reference list of ($Key, $Value) pairs into a hash. Makes sure that all the keys are lower cased (lc) first.
_fix_folder_name($FolderName, $WildCard)
Changes a folder name based on the current root folder prefix as set with the "set_root_prefix()" call.

If $WildCard is true, then a folder name with % or * is left alone.

Used by IMAP commands to handle a number of different ways that message IDs can be specified.
Method arguments
String or array ref which specified the message IDs or UIDs.

The $MessageIds parameter may take the following forms:

array ref
Array is turned into a string of comma separated ID numbers.
Normally a * would result in the message ID string being quoted. This ensure that such a range string is not quoted because some servers (e.g. cyrus) don't like.
Converts a list of IMAP email address structures as parsed and returned from an IMAP fetch (envelope) call into a single RFC822 email string (e.g. ``Person 1 Name'' <>, ``Person 2 Name'' <...>, etc) to finally return to the user.

This is used to parse an envelope structure returned from a fetch call.

See the documentation section 'FETCH RESULTS' for more information.

_parse_envelope($Envelope, $IncludeRaw, $DecodeUTF8)
Converts an IMAP envelope structure as parsed and returned from an IMAP fetch (envelope) call into a convenient hash structure.

If $IncludeRaw is true, includes the XXX-Raw fields, otherwise these are left out.

If $DecodeUTF8 is true, then checks if the fields contain any quoted-printable chars, and decodes them to a Perl UTF8 string if they do.

See the documentation section 'FETCH RESULTS' from more information.

_parse_bodystructure($BodyStructure, $IncludeRaw, $DecodeUTF8, $PartNum)
Parses a standard IMAP body structure and turns it into a Perl friendly nested hash structure. This routine is recursive and you should not pass a value for $PartNum when called for the top level bodystructure item. Note that this routine destroys the array reference structure passed in as $BodyStructure.

See the documentation section 'FETCH RESULTS' from more information

Takes the result from a single IMAP fetch response line and parses it into a Perl friendly structure.

See the documentation section 'FETCH RESULTS' from more information.

_parse_header_result($HeaderResults, $Value, $FetchResult)
Take a body[header.fields (xyz)] fetch response and parse out the header fields and values
Decodes the passed quoted printable value to a Perl UTF8 string.


Called by Perl when this object is destroyed. Logs out of the IMAP server if still connected.


Net::IMAP, Mail::IMAPClient, IMAP::Admin, RFC2060

Latest news/details can also be found at:  


Rob Mueller <>. Thanks to Jeremy Howard <> for socket code, support and documentation setup.  


Copyright (C) 2003-2005 by FastMail IP Partners

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.



Method results
Method parameters

This document was created by man2html, using the manual pages.
Time: 07:00:07 GMT, September 14, 2007