The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

Net::IMAP::Client - Not so simple IMAP client library

SYNOPSIS

    use Net::IMAP::Client;

    my $imap = Net::IMAP::Client->new(
        server => 'mail.you.com',
        user   => 'USERID',
        pass   => 'PASSWORD',
        ssl    => 1,          # (use SSL? default no)
        port   => 993         # (but defaults are sane)
    );

    $imap->login or
      die('Login failed: ' . $imap->last_error);

    # get list of folders
    my @folders = $imap->folders;

    # get total # of messages, # of unseen messages etc. (fast!)
    my @status = $imap->status(@folders);

    # select folder
    $imap->select('INBOX');

    # get folder hierarchy separator (cached at first call)
    my $sep = $imap->separator;

    # fetch all message ids
    my @messages = $imap->search('ALL');

    # fetch all ID-s sorted by subject
    my $messages = $imap->search('ALL', 'SUBJECT');
       or
    my @messages = $imap->search('ALL', [ 'SUBJECT' ]);

    # fetch ID-s that match criteria, sorted by subject and reverse date
    my $messages = $imap->search({
        FROM    => 'foo',
        SUBJECT => 'bar',
    }, [ 'SUBJECT', '^DATE' ]);

    # fetch message summaries (actually, a lot more)
    my @summaries = $imap->get_summaries([ @msg_ids ]);

    foreach (@summaries) {
        print $_->uid, $_->subject, $_->date, $_->rfc822_size;
        print join(', ', @{$_->from}); # etc.
    }

    # fetch full message
    my $data = $imap->get_rfc822_body($msg_id);
    print $$data; # it's reference to a scalar

    # fetch full messageS
    my @msgs = $imap->get_rfc822_body([ @msg_ids ]);
    print $$_ for (@msgs);

    # fetch single attachment (message part)
    my $data = $imap->get_part_body($msg_id, '1.2');

DESCRIPTION

Net::IMAP::Client provides methods to access an IMAP server. It aims to provide a simple and clean API, while employing a rigorous parser for IMAP responses in order to create Perl data structures from them. The code is simple, clean and extensible.

It started as an effort to improve Net::IMAP::Simple but then I realized that I needed to change a lot of code and API so I started it as a fresh module. Nevertheless, the design is influenced by Net::IMAP::Simple and I even stole a few lines of code from it ;-) (very few, honestly).

API REFERENCE

Unless otherwise specified, if a method fails it returns undef and you can inspect the error by calling $imap->last_error. For a successful call most methods will return a meaningful value but definitely not undef.

new( %args ) # constructor

    my $imap = Net::IMAP::Client->new(%args);

Pass to the constructor a hash of arguments that can contain:

- server (STRING)

Host name or IP of the IMAP server.

- user (STRING)

User ID (only "clear" login is supported for now!)

- pass (STRING)

Password

- ssl (BOOL, optional, default FALSE)

Pass a true value if you want to use IO::Socket::SSL

- uid_mode (BOOL, optional, default TRUE)

Wether to use UID command (see RFC2060). Recommended.

- socket (IO::Handle, optional)

If you already have a socket connected to the IMAP server, you can pass it here.

The constructor doesn't login to the IMAP server -- you need to call $imap->login for that.

last_error

Returns the last error from the IMAP server.

login( $user, $pass )

Login to the IMAP server. You can pass $user and $pass here if you wish; if not passed, the values used in constructor will be used.

Returns undef if login failed.

logout / quit

Send EXPUNGE and LOGOUT then close connection. quit is an alias for logout.

select( $folder )

Selects the current IMAP folder. On success this method also records some information about the selected folder in a hash stored in $self->{FOLDERS}{$folder}. You might want to use Data::Dumper to find out exactly what, but at the time of this writing this is:

- messages

Total number of messages in this folder

- flags

Flags available for this folder (as array ref)

- recent

Total number of recent messages in this folder

- sflags, oflags

Various other flags here, such as PERMANENTFLAGS of UIDVALIDITY. You might want to take a look at RFC2060 at this point. :-p

This method is basically stolen from Net::IMAP::Simple.

status( $folder ), status( @folders ), status( \@folders )

Returns the status of the given folder(s).

In scalar context it returns an array ref if multiple folders were queried, or the status for a single folder otherwise. In list context it returns an array with the requested data.

    my $inbox = $imap->status('INBOX');
    print $inbox->{UNSEEN}, $inbox->{MESSAGES};
    print Data::Dumper::Dumper($inbox);

    my @all = $imap->status($imap->folders);
    foreach (@all) {
        print "$_->{name} : $_->{MESSAGES}/$_->{UNSEEN}\n";
    }

This method is designed to be very fast when passed multiple folders. It's a lot faster to call:

    $imap->status(@folders);

than:

    $imap->status($_) foreach (@folders);

because it sends all the STATUS requests to the IMAP server before it starts receiving the answers. In my tests with my remote IMAP server, for 40 folders this method takes 0.6 seconds, compared to 6+ seconds when called individually for each folder alone.

separator

Returns the folder hierarchy separator. This is provided as a result of the following IMAP command:

    FETCH "" "*"

I don't know of any way to change this value on a server so I have to assume it's a constant. Therefore, this method caches the result and it won't hit the server a second time on subsequent calls.

folders

Returns a list of all folders available on the server. In scalar context it returns a reference to an array, i.e.:

    my @a = $imap->folders;
    my $b = $imap->folders;
    # now @a == @$b;

search( $criteria, $sort, $charset )

Executes the "SEARCH" or "SORT" IMAP commands (depending on wether $sort is undef) and returns the results as a list (or array ref in scalar context) containing message ID-s.

- $criteria

Can be a string, in which case it is passed literally to the IMAP command (which can be "SEARCH" or "SORT").

It can also be an hash reference, in which case keys => values are collected into a string and values are properly quotes, i.e.:

   { subject => 'foo',
     from    => 'bar' }

will translate to:

   'SUBJECT "foo" FROM "bar"'

which is a valid IMAP SEARCH query.

If you want to retrieve all messages (no search criteria) then pass 'ALL' here.

- $sort

Can be a string or an array reference. If it's an array, it will simply be joined with a space, so for instance passing the following is equivalent:

    'SUBJECT DATE'
    [ 'SUBJECT', 'DATE' ]

The SORT command in IMAP allows you to prefix a sort criteria with 'REVERSE' which would mean descending sorting; this module will allow you to prefix it with '^', so again, here are some equivalent constructs:

    'SUBJECT REVERSE DATE'
    'SUBJECT ^DATE'
    [ 'SUBJECT', 'REVERSE', 'DATE' ]
    [ 'subject', 'reverse date' ]
    [ 'SUBJECT', '^DATE' ]

It'll also uppercase whatever you passed here.

If you omit $sort (or pass undef) then this method will use the SEARCH command. Otherwise it uses the SORT command.

- $charset

The IMAP SORT recommendation [2] requires a charset declaration for SORT, but not for SEARCH. Interesting, huh?

Our module is a bit more paranoid and it will actually add charset for both SORT and SEARCH. If $charset is omitted (or undef) the it will default to "UTF-8", which, supposedly, is supported by all IMAP servers.

This method returns a list (or an array reference, in scalar context) of message ID-s that match the search criteria.

get_rfc822_body( $msg_id )

Fetch and return the full RFC822 body of the message. $msg_id can be a scalar but also an array of ID-s. If it's an array, then all bodies of those messages will be fetched and the return value will be a list or an array reference (depending how you call it).

Note that the actual data is returned as a reference to a scalar, to speed things up.

Examples:

    my $data = $imap->get_rfc822_body(10);
    print $$data;   # need to dereference it

    my @more = $imap->get_rfc822_body([ 11, 12, 13 ]);
    print $$_ foreach @more;

        or

    my $more = $imap->get_rfc822_body([ 11, 12, 13 ]);
    print $$_ foreach @$more;

get_part_body( $msg_id, $part_id )

Fetches and returns the body of a certain part of the message. Part ID-s look like '1' or '1.1' or '2.3.1' etc. (see RFC2060 [1], "FETCH Command").

Scalar reference

Note that again, this data is returned as a reference to a scalar rather than the scalar itself. This decision was taken purely to save some time passing around potentially large data from Perl subroutines.

Undecoded

One other thing to note is that the data is not undecoded. One simple way to decode it is use Email::MIME::Encodings, i.e.:

    use Email::MIME::Encodings;
    my $summary = $imap->get_summaries(10);
    my $part = $summary->get_subpart('1.1');
    my $body = $imap->get_part_body('1.1');
    my $cte = $part->transfer_encoding;  # Content-Transfer-Encoding
    $body = Email::MIME::Encodings::decode($cte, $$body);

    # and now you should have the undecoded (perhaps binary) data.

See get_summaries below.

get_summaries( $msg )

Fetches, parses and returns "message summaries". $msg can be an array ref, or a single id. The return value is an array reference (in scalar context) or a list. If a single message was passed, then in scalar context it returns only that message (not an array ref).

The result contains one or more Net::IMAP::Client::MsgSummary objects. The best way to understand the result is to actually call this function and use Data::Dumper to see its structure.

Following is the output for a pretty complicated message, which contains an HTML part with an embedded image and an attached message. The attached message in turn contains an HTML part and an embedded message.

  bless( {
    'message_id' => '<48A71D17.1000109@foobar.com>',
    'date' => 'Sat, 16 Aug 2008 21:31:51 +0300',
    'to' => [
        bless( {
            'at_domain_list' => undef,
            'name' => undef,
            'mailbox' => 'kwlookup',
            'host' => 'foobar.com'
        }, 'Net::IMAP::Client::MsgAddress' )
    ],
    'cc' => undef,
    'from' => [
        bless( {
            'at_domain_list' => undef,
            'name' => 'Mihai Bazon',
            'mailbox' => 'justme',
            'host' => 'foobar.com'
        }, 'Net::IMAP::Client::MsgAddress' )
    ],
    'flags' => [
        '\\Seen',
        'NonJunk',
        'foo_bara'
    ],
    'uid' => '11',
    'subject' => 'test with message attachment',
    'rfc822_size' => '12550',
    'in_reply_to' => undef,
    'bcc' => undef,
    'internaldate' => '16-Aug-2008 21:29:23 +0300',
    'reply_to' => [
        bless( {
            'at_domain_list' => undef,
            'name' => 'Mihai Bazon',
            'mailbox' => 'justme',
            'host' => 'foobar.com'
        }, 'Net::IMAP::Client::MsgAddress' )
    ],
    'sender' => [
        bless( {
            'at_domain_list' => undef,
            'name' => 'Mihai Bazon',
            'mailbox' => 'justme',
            'host' => 'foobar.com'
        }, 'Net::IMAP::Client::MsgAddress' )
    ],
    'parts' => [
        bless( {
            'part_id' => '1',
            'parts' => [
                bless( {
                    'parameters' => {
                        'charset' => 'UTF-8'
                    },
                    'subtype' => 'html',
                    'part_id' => '1.1',
                    'encoded_size' => '365',
                    'cid' => undef,
                    'type' => 'text',
                    'description' => undef,
                    'transfer_encoding' => '7bit'
                }, 'Net::IMAP::Client::MsgSummary' ),
                bless( {
                    'disposition' => {
                        'inline' => {
                            'filename' => 'someimage.png'
                        }
                    },
                    'language' => undef,
                    'encoded_size' => '4168',
                    'description' => undef,
                    'transfer_encoding' => 'base64',
                    'parameters' => {
                        'name' => 'someimage.png'
                    },
                    'subtype' => 'png',
                    'part_id' => '1.2',
                    'type' => 'image',
                    'cid' => '<part1.02030404.05090202@foobar.com>',
                    'md5' => undef
                }, 'Net::IMAP::Client::MsgSummary' )
            ],
            'multipart_type' => 'related'
        }, 'Net::IMAP::Client::MsgSummary' ),
        bless( {
            'message_id' => '<48A530CE.3050807@foobar.com>',
            'date' => 'Fri, 15 Aug 2008 10:31:26 +0300',
            'encoded_size' => '6283',
            'to' => [
                bless( {
                    'at_domain_list' => undef,
                    'name' => undef,
                    'mailbox' => 'kwlookup',
                    'host' => 'foobar.com'
                }, 'Net::IMAP::Client::MsgAddress' )
            ],
            'subtype' => 'rfc822',
            'cc' => undef,
            'from' => [
                bless( {
                    'at_domain_list' => undef,
                    'name' => 'Mihai Bazon',
                    'mailbox' => 'justme',
                    'host' => 'foobar.com'
                }, 'Net::IMAP::Client::MsgAddress' )
            ],
            'subject' => 'Test with images',
            'in_reply_to' => undef,
            'description' => undef,
            'transfer_encoding' => '7bit',
            'parameters' => {
                'name' => 'Attached Message'
            },
            'bcc' => undef,
            'part_id' => '2',
            'sender' => [
                bless( {
                    'at_domain_list' => undef,
                    'name' => 'Mihai Bazon',
                    'mailbox' => 'justme',
                    'host' => 'foobar.com'
                }, 'Net::IMAP::Client::MsgAddress' )
            ],
            'reply_to' => [
                bless( {
                    'at_domain_list' => undef,
                    'name' => 'Mihai Bazon',
                    'mailbox' => 'justme',
                    'host' => 'foobar.com'
                }, 'Net::IMAP::Client::MsgAddress' )
            ],
            'parts' => [
                bless( {
                    'parameters' => {
                        'charset' => 'UTF-8'
                    },
                    'subtype' => 'html',
                    'part_id' => '2.1',
                    'encoded_size' => '344',
                    'cid' => undef,
                    'type' => 'text',
                    'description' => undef,
                    'transfer_encoding' => '7bit'
                }, 'Net::IMAP::Client::MsgSummary' ),
                bless( {
                    'disposition' => {
                        'inline' => {
                            'filename' => 'logo.png'
                        }
                    },
                    'language' => undef,
                    'encoded_size' => '4578',
                    'description' => undef,
                    'transfer_encoding' => 'base64',
                    'parameters' => {
                        'name' => 'logo.png'
                    },
                    'subtype' => 'png',
                    'part_id' => '2.2',
                    'type' => 'image',
                    'cid' => '<part1.02060209.09080406@foobar.com>',
                    'md5' => undef
                }, 'Net::IMAP::Client::MsgSummary' )
            ],
            'cid' => undef,
            'type' => 'message',
            'multipart_type' => 'related'
        }, 'Net::IMAP::Client::MsgSummary' )
    ],
    'multipart_type' => 'mixed'
  }, 'Net::IMAP::Client::MsgSummary' );

As you can see, the parser retrieves all data, including from the embedded messages.

Note that textual values are "MIME word"-encoded. You need to call i.e. Encode::decode('MIME-Header', $summary->subject) to make sure it's decoded. See Net::IMAP::Client::MsgSummary for more information on this.

There are many other modules you can use to fetch such information. Email::Simple and Email::MIME are great. The only problem is that you have to have fetched already the full (RFC822) body of the message, which is impractical over IMAP. When you want to quickly display a folder summary, the only practical way is to issue a FETCH command and retrieve only those headers that you are interested in (instead of full body). get_summaries does exactly that (issues a FETCH (FLAGS INTERNALDATE RFC822.SIZE ENVELOPE BODYSTRUCTURE)). It's acceptably fast even for huge folders.

TODO

There's a bunch of missing functionality which should be quite easy to add but I didn't get to it yet. Such as create/delete folders. If you need it urgently, feel free to add it and send me a patch, otherwise wait until I need it. :-)

- authentication schemes other than plain text (help wanted)
- append/delete messages
- create/remove mailboxes
- expunge folder
- support THREAD operation
- reconnect/relogin when connection lost
- better error handling?

SEE ALSO

Net::IMAP::Simple, Mail::IMAPClient, Mail::IMAPTalk

Email::Simple, Email::MIME

RFC2060 [1] is a must read if you want to do anything fancier than what this module already supports.

REFERENCES

[1] http://ietfreport.isoc.org/rfc/rfc2060.txt

[2] http://ietfreport.isoc.org/all-ids/draft-ietf-imapext-sort-20.txt

AUTHOR

Mihai Bazon, <mihai.bazon@gmail.com> http://www.dynarchlib.com/ http://www.bazon.net/mishoo/

COPYRIGHT

Copyright (c) Mihai Bazon 2008. All rights reserved.

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

DISCLAIMER OF WARRANTY

BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION.

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.