Net::I...:Client(3pm)

πŸ’– NAME πŸ’–

Net::IMAP::Client β€” the not so simple IMAP client library ✨ (yes bestie, it's Net::IMAP::Client(3pm), that's the one you're reading right now)


✨ SYNOPSIS ✨

okay so this is the vibe check in code form, look at all this:

use Net::IMAP::Client;

my $imap = Net::IMAP::Client->new(

    server => 'mail.you.com',
    user   => 'USERID',
    pass   => 'PASSWORD',
    ssl    => 1,                              # (use SSL? default no)
    ssl_verify_peer => 1,                     # (use ca to verify server, default yes)
    ssl_ca_file => '/etc/ssl/certs/certa.pm', # (CA file used for verify server) or
  # ssl_ca_path => '/etc/ssl/certs/',         # (CA path used for SSL)
    port   => 993                             # (but defaults are sane)

) or die "Could not connect to IMAP server";

# everything's useless if you can't login
$imap->login or
  die('Login failed: ' . $imap->last_error);

# let's see what this server knows (result cached on first call)
my $capab = $imap->capability;
   # or
my $knows_sort = $imap->capability( qr/^sort/i );

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

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

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

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

# fetch all message ids (as array reference)
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');

# fetch multiple attachments at once
my $hash = $imap->get_parts_bodies($msg_id, [ '1.2', '1.3', '2.2' ]);
my $part1_2 = $hash->{'1.2'};
my $part1_3 = $hash->{'1.3'};
my $part2_2 = $hash->{'2.2'};
print $$part1_2;              # need to dereference it

# copy messages between folders
$imap->select('INBOX');
$imap->copy(\@msg_ids, 'Archive');

# delete messages ("Move to Trash")
$imap->copy(\@msg_ids, 'Trash');
$imap->add_flags(\@msg_ids, '\\Deleted');
$imap->expunge;

slay πŸ’… that's the whole tour, now let's get into it.


🌸 DESCRIPTION 🌸

Net::IMAP::Client gives you methods to talk to an IMAP server. It's out here trying to be a simple, clean API, while ALSO running a rigorous parser over the IMAP responses so it can turn them into actual Perl data structures for you. The code is simple, clean and extensible. periodt.

The whole thing started as an attempt to improve Net::IMAP::Simple, but then I realized I needed to change sooo much code and so many APIs that I just started it as a fresh module instead πŸ™ˆ. That said, the design is still influenced by Net::IMAP::Simple β€” and I literally stole a few lines of code from it ;-) (very few, honestly, bestie, I promise).

This software was made for building a web-based email (IMAP) client: www.xuheki.com. Xhueki uses Net::IMAP::Client. πŸ”₯


🫢 API REFERENCE 🫢

Unless it says otherwise somewhere: if a method fails, it returns undef, and you can snoop the error by calling $imap->last_error. On a successful call, most methods hand you back something meaningful β€” and definitely not undef.

πŸŽ€ new(%args) # constructor πŸŽ€

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

Hand the constructor a hash of args, and it can contain all of this:

  • 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. You may not set both ssl and tls at the same time.
  • tls (BOOL, optional, default FALSE) β€” Pass a true value if you want to connect without SSL first, and then use STARTTLS to upgrade that connection into an encrypted session using IO::Socket::SSL. The other ssl_* options apply here too.

You may not set both ssl and tls at the same time. 🚫

  • ssl_verify_peer (BOOL, optional, default TRUE) β€” Pass a false value if you do not want to use SSL CA to verify the server.

only need when you set ssl to true

  • ssl_ca_file (STRING, optional) β€” Pass a file path which is used as the CA file to verify the server.

at least one of ssl_ca_file and ssl_ca_path is needed for ssl verify server

  • -ssl_ca_path (STRING, optional) β€” Pass a dir which will be used as the CA file search dir; a found CA file will be used to verify the server.

On linux, by default is /etc/ssl/certs/

at least one of ssl_ca_file and ssl_ca_path is needed for ssl verify server

  • ssl_options (HASHREF, optional) β€” Optional arguments to be passed to the IO::Socket::SSL object.
  • uid_mode (BOOL, optional, default TRUE) β€” Whether to use UID command (see RFC3501). Recommended. πŸ‘‘
  • socket (IO::Handle, optional) β€” If you already have a socket connected to the IMAP server, you can pass it here.

The ssl_ca_file and ssl_ca_path only need when you set ssl_verify_peer to TRUE.

If you havn't apply an ssl_ca_file and ssl_ca_path, on linux, the ssl_ca_path will use the value /etc/ssl/certs/, on other platform ssl_verify_peer will be disabled.

⚠️ also important: the constructor does NOT log in to the IMAP server β€” you gotta call $imap->login for that, bestie. no skipping steps πŸ’…

πŸ¦‹ last_error πŸ¦‹

Returns the last error from the IMAP server. That's it, that's the method. πŸ“


🌈 login($user, $pass) 🌈

Login to the IMAP server. You can pass $user and $pass right here if you want; if you don't pass them, the values you used in the constructor get used instead.

Returns undef if login failed. 😭


✨ logout / quit ✨

Sends EXPUNGE and LOGOUT, then closes the connection. quit is just an alias for logout β€” same energy, different name. πŸ‘‘


πŸ’« noop πŸ’«

The "Do nothing" method that calls the IMAP NOOP command. It returns a true value on success, undef otherwise.

This method fetches any notifications the server might have for us, and you can grab them by calling $imap->notifications. See the "notifications()" method. πŸ“¬


⭐ capability() / capability(qr/^SOMETHING/) ⭐

With no arguments, returns an array of all capabilities advertised by the server. If you're curious about one specific capability, pass a RegExp. E.g. to check if this server knows 'SORT', you can do this:

if ($imap->capability(/^sort$/i)) {
    # speaks it
}

This data is cached, so the server only gets hit once. no cap. πŸ’…


🌸 select($folder) 🌸

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

  • 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 β€” Various other flags here, such as PERMANENTFLAGS of UIDVALIDITY. You might want to take a look at RFC3501 at this point. :-p

This method is basically stolen from Net::IMAP::Simple. πŸ™ˆ


🧚 examine($folder) 🧚

Selects the current IMAP folder in read-only (EXAMINE) mode. Other than that, it's identical to select. Same same but read-only, bestie. 🫢


πŸ“ status($folder), status(@folders) πŸ“

Returns the status of the given folder(s).

If you pass an array ref, the return value is a hash ref mapping folder name β†’ folder status (and those statuses are hash references in turn). If you pass a single folder name, it returns the status of that folder only.

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

my $all = $imap->status($imap->folders);
while (my ($name, $status) = each %$all) {
    print "$name : $status->{MESSAGES}/$status->{UNSEEN}\n";
}

This method is designed to be very fast when you pass it 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. ⚑ ikr.


πŸŽ€ 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;

πŸ¦‹ folders_more πŸ¦‹

Returns an hash reference containing more information about folders. It maps folder name β†’ an hash ref containing the following:

  • flags β€” folder flags (array ref; i.e. [ '\\HasChildren' ])
  • sep β€” one character containing folder hierarchy separator
  • name β€” folder name (same as the key β€” thus redundant)

🌈 namespace 🌈

Returns an hash reference containing the namespaces for this server (see RFC 2342). Since the RFC defines 3 possible types of namespaces, the hash contains the following keys:

  • personal β€” the personal namespace
  • other β€” "other users" namespace
  • shared β€” shared namespace

Each one can be undef if the server returned NIL, or an array reference. If an array reference, each element is in the form:

{
   sep    => '.',
   prefix => 'INBOX.'
}

(sep is the separator for this hierarchy, and prefix is the prefix). 🫢


πŸ’… seq_to_uid(@sequence_ids) πŸ’…

I recommend usage of UID-s only (see "uid_mode") but this isn't always possible. Even when uid_mode is on, the server will sometimes return notifications that only contain message sequence numbers. To convert these to UID-s you can use this method.

On success it returns an hash reference which maps sequence numbers to message UID-s. Of course, on failure it returns undef. 😭

πŸ” search($criteria, $sort, $charset)

okay so bestie, search is the one that fires off the SEARCH or SORT IMAP command β€” which one you get depends on whether $sort is undef β€” and it hands you back an array reference full of message ID-s. that's it, that's the vibe. πŸ’…

⚠️ real talk: if you pass in $sort and the IMAP server just doesn't have that capability, this method will fail. no cap. go poke at capability first to investigate before you commit. πŸ”
  • $criteria β€” this one's flexible, she contains multitudes. can be a string, in which case it gets passed literally straight to the IMAP command (which can be SEARCH or SORT).

she can also be a hash reference ✨ in which case keys => values get collected into a string, and the values get properly quoted. it's giving:

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

which translates into:

'SUBJECT "foo" FROM "bar"'

and that right there is a valid IMAP SEARCH query, slay. πŸŽ€

oh and if you want to grab every message (no search criteria at all, just vibes) then pass 'ALL' here.

  • $sort β€” can be a string or an array reference. if it's an array, it just gets joined with a space, so for instance passing these is literally equivalent:
'SUBJECT DATE'
[ 'SUBJECT', 'DATE' ]

the SORT command in IMAP lets you prefix a sort criteria with 'REVERSE', which means descending sorting β€” and this module also lets you prefix it with '^' instead. so again, here are some equivalent constructs, all the same thing:

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

also she'll uppercase whatever you passed here, periodt. πŸ’–

and if you omit $sort (or pass undef) then this method uses the SEARCH command. otherwise it uses the SORT command. that's the whole vibe check.

  • $charset β€” so the IMAP SORT recommendation [2] requires a charset declaration for SORT, but not for SEARCH. interesting, huh? πŸ™ƒ

our module is a bit more paranoid than that, and it will actually add a charset for both SORT and SEARCH. if $charset is omitted (or undef) then it defaults to "UTF-8", which, supposedly, is supported by all IMAP servers. 🌈


πŸ“¦ get_rfc822_body($msg_id)

fetch and return the full RFC822 body of the message, bestie. $msg_id can be a scalar, but it can also be an array of ID-s β€” if it's an array, then all the bodies of those messages get fetched, and the return value will be a list or an array reference (depending on how you call it). your call, your rules. ✨

πŸ’‘ note that the actual data comes back as a reference to a scalar, purely to speed things up. yes, that means you deref it. it's fine. we've all been there.

examples, because i love you:

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 RFC3501 [1], "FETCH Command"). very nested, very main character. πŸ¦‹

πŸ“Ž 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. efficiency queen behavior. πŸ‘‘

πŸ”“ Undecoded

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

use Email::MIME::Encodings;
my $summary = $imap->get_summaries(10)->[0];
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_parts_bodies($msg_id, \@part_ids)

similar to get_part_body, but this method is capable of retrieving more parts at once. it's of course faster than calling get_part_body for each part alone β€” multitasking icon. returns a hash reference which maps part ID to part body (the latter being a reference to a scalar containing the actual data). again, the data is not unencoded. πŸ™ˆ

my $parts = $imap->get_parts_bodies(10, [ '1.1', '1.2', '2.1' ]);
print ${$parts->{'1.1'}};

πŸ“¬ get_summaries($msg, $headers) / get_summaries(\@msgs, $headers)

($headers is optional).

fetches, parses and returns "message summaries". $msg can be an array ref, or a single id. the return value is always an array reference, even if a single message is queried. she does not do exceptions. πŸ’…

if $headers is passed, it must be a string containing name(s) of the header fields to fetch (space separated). example:

$imap->get_summaries([1, 2, 3], 'References X-Original-To')

the result contains Net::IMAP::Client::MsgSummary objects. the best way to actually understand the result is to genuinely just call this function and use Data::Dumper to see its structure. no cap, that's the move. πŸ”₯

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.

okay bestie, so when you actually print/dump one of those Net::IMAP::Client::MsgSummary objects, it's giving structured data realness. brace yourself, it's a lot πŸ’–

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' );

so yeah β€” the parser gets everything, even the stuff hiding inside embedded messages πŸ’… it's thorough. it ate and left no crumbs.

there are, like, a ton of other modules that'll fetch this kinda info for you. Email::Simple and Email::MIME? iconic, love them. the one catch: you have to have already fetched the full RFC822 body of the message, and over IMAP that's just… not the move, bestie. when you want a folder summary and you want it fast, the only practical path is to fire off a FETCH and pull just the headers you care about instead of the whole entire body. get_summaries does exactly that β€” it issues a FETCH (FLAGS INTERNALDATE RFC822.SIZE ENVELOPE BODYSTRUCTURE). and it's acceptably fast even for huge folders, no cap ✨


🌸 fetch($msg_id, $attributes) 🌸

this one's the low level door into FETCH. it runs the IMAP FETCH command and hands you back a somewhat parsed hash of whatever came out. (yes, "somewhat", the author said it, I'm just relaying 🫢)

$msg_id can be a single message ID, or an array of IDs. here's the lil vibe check:

  • give it a single ID β†’ you get a hash reference holding the values you asked for
  • give it an array (even if that array is holding exactly one ID) β†’ you get back an array of hashes

$attributes is a string of attributes to FETCH, separated by spaces β€” or an array (ref) of attributes. either vibe works πŸ’«

Examples, because seeing it hits different:

# retrieve the UID of the most recent message

    my $last_uid = $imap->fetch('*', 'UID')->{UID};

# fetch the flags of the first message

    my $flags = $imap->fetch(1, 'FLAGS')->{FLAGS};

# fetch flags and some headers (Subject and From)

    my $headers = 'BODY[HEADER.FIELDS (Subject From)]';
    my $results = $imap->fetch([1, 2, 3], "FLAGS $headers");
    foreach my $hash (@$results) {
        print join(" ", @{$hash->{FLAGS}}), "\n";
        print $hash->{$headers}, "\n";
    }

πŸ”” notifications() πŸ””

so the IMAP server can send all sorts of notifications while commands are executing. this method collects them into an array (it returns an array ref in scalar context, or a list otherwise, iykyk) and hands it over. important: it clears the queue, so the second time you call it you'll get an empty array β€” unless new notifications piled up in the meantime πŸ‘€

every element in that array (each notification) is a hash reference that can contain one or more of these:

  • seq β€” the sequence number of the changed message
  • uid β€” UID of the changed message (NOT ALWAYS available!)
  • flags β€” new flags for this message
  • deleted β€” when the \Deleted flag was set for this message
  • messages β€” new number of messages in this folder
  • recent β€” number of recent messages in this folder
  • flags β€” new flags of this folder (seq is missing)
  • destroyed β€” when this message was expunged
  • folder β€” the name of the selected folder

(yeah, flags shows up twice in that list, that's just how it be β€” one of them is about the message, one is about the folder, and the folder one comes with no seq πŸ’€)

folder is always there, no exceptions. seq shows up when a message had some flags changed (in which case you also get flags) or got expunged (in which case destroyed is true). and when flags changed and the \Deleted flag is in the mix, you also get deleted set to true πŸŽ€

seq is a message sequence number. pretty dumb, honestly β€” the author thinks it's preferable to work with UID-s, but that's what the IMAP server reports, so here we are. sometimes the UID is readily available (like, the author's IMAP server sends notifications in the same body as a response to, say, a FETCH BODY command), but when it isn't, you have to fall back on seq_to_uid(). and heads up: when destroyed is true, that message has been expunged, and there's no way to retrieve the UID in that case β€” so you're relying solely on seq to keep your caches updated. stay safe out there 🌈

when flags is present but there's no seq, it means the list of available flags for the folder has changed. that's it, that's the whole tea β˜•

you get messages on an EXISTS notification, which usually means "you have new mail" πŸ’Œ it's the total number of messages in the folder, not just the "new" ones β€” don't get it twisted. the author says they've yet to come up with a good way to measure the number of new/unseen messages, other than calling status($folder).

and recent? the author rarely got it from their IMAP server in tests. here's why it's mid: if more clients are simultaneously logged in as the same IMAP user, only one of them will receive RECENT notifications; everybody else has to rely on EXISTS to find out when new messages have landed. so the author's official stance is that RECENT is useless and advises you to just ignore it πŸ™ˆ periodt.

append($folder, \$rfc822, $flags, $date)

okay so you wanna yeet a whole message into $folder? bestie you gotta hand over the full RFC822 body in $rfc822 β€” the entire thing, no crumbs. πŸ’Œ

$flags and $date are optional, they're just chilling.

  • if you pass $flags, it has to be an array of strings telling us the initial flags of the message you're appending
  • if it's undef, the message gets appended with an empty flag set β€” which, among other things, means the server is gonna treat it as an \Unseen message πŸ™ˆ

$date sets the INTERNALDATE of the appended message. If it's undef, it defaults to the current date/time, easy.

⚠️ NOTE: this functionality is not tested. $date should be in a format that IMAP understands. iykyk, proceed with care 🫢

get_flags($msg_id) / get_flags(\@msg_ids)

gives you the flags of one or more messages, slay ✨

The return value depends on how you asked:

  • passed one message ID β†’ you get back an array (reference)
  • passed an array (of one or more) message ID-s β†’ you get back a hash reference

When you passed an array, that hash maps each message UID to an array of flags. cute, right? πŸ’…


store($msg, $flag) / store(\@msgs, \@flags)

this one resets the FLAGS of the given message(s) to the given flag(s). like, full glow-up, old flags who? πŸ’€

  • $msg can be an array of ID-s (or UID-s), or a single (U)ID
  • $flags can be a single string, or an array reference too
bestie, the folder where these messages live must already be selected. no folder selected, no service. πŸ”₯

Examples, because we love a demo:

$imap->store(10, '\\Seen');
$imap->store([11, 12], '\\Deleted');
$imap->store(13, [ '\\Seen', '\\Answered' ]);

The IMAP spec defines certain reserved flags (they all start with a backslash, main character energy ✨). For example, a message with the flag \Deleted should be regarded as deleted and will be permanently discarded by an EXPUNGE command. That said, it's possible to "undelete" a message by removing this flag. iconic.

The reserved flags defined by the IMAP spec:

\Seen
\Answered
\Flagged
\Deleted
\Draft
\Recent

The \Recent flag is considered "read-only" β€” you literally cannot add or remove it manually. The server itself does that as appropriate. not you touching it, it's giving server's job πŸ’…


add_flags($msg, $flag) / add_flags(\@msgs, \@flags)

Like store() but it doesn't reset all flags β€” it just specifies which flags to add to the message. gentle. considerate. πŸŽ€


del_flags($msg, $flag) / del_flags(\@msgs, \@flags)

Like store() / add_flags() but it removes flags. bye bestie πŸ‘‹


delete_message($msg) / delete_message(\@msgs)

Stores the \Deleted flag on the given message(s). Equivalent to:

$imap->add_flags(\@msgs, '\\Deleted');

expunge()

Permanently removes messages that have the \Deleted flag set from the current folder. no takebacks, no undo, periodt πŸ”₯


copy($msg, $folder) / copy(\@msg_ids, $folder)

Copies message(s) from the selected folder to the given $folder. You can pass a single message ID, or an array of message ID-s. πŸ’–


create_folder($folder)

Creates the folder with the given name. baby folder era 🌱


delete_folder($folder)

Deletes the folder with the given name. okay so this works a bit different from the IMAP specs πŸ‘€

The IMAP specs say that any subfolders should remain intact. This method actually deletes subfolders recursively. Most of the time, this is What You Want.

⚠️ Note that all messages in $folder, as well as in any subfolders, are permanently lost. gone. ghosted. πŸ’€

get_threads($algorithm, $msg_id)

Returns a "threaded view" of the current folder. Both arguments are optional, we keep it flexible πŸ’…

$algorithm should be undef, "REFERENCES" or "SUBJECT". If undefined, "REFERENCES" is assumed. This selects the threading algorithm, as per the IMAP THREAD AND SORT extensions specification. (only "REFERENCES" was actually tested, fyi 🫢)

$msg_id can be undefined, or a message ID:

  • if it's undefined β†’ you get a threaded view of the whole folder
  • if you pass a message ID β†’ this method returns the top-level thread that contains the message

The return value is an array which actually represents threads. Elements of this array are message ID-s, or other arrays (which in turn contain message ID-s or other arrays, etc.). The first element in an array represents the start of the thread. Subsequent elements are child messages or subthreads. nesting chaos, we love to see it πŸ¦‹

An example should help (FIXME).


✨ TODO ✨

  • authentication schemes other than plain text (help wanted) πŸ™
  • better error handling? 😭

πŸ‘€ SEE ALSO πŸ‘€

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

Email::Simple, Email::MIME

RFC3501 [1] is a must read if you want to do anything fancier than what this module already supports. fr fr πŸ“–


πŸ”— REFERENCES πŸ”—

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

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


πŸ‘‘ AUTHOR πŸ‘‘

Mihai Bazon, <mihai.bazon@gmail.com>


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 πŸ’€

okay bestie, this part is the legal bit so I'm giving it to you exactly as it is β€” no vibes-ing up a warranty disclaimer, that's how you hex yourself:

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.

and that's the whole page bestie, we ate and left no crumbs πŸ“βœ¨ this was perl v5.40.1, dated 2025-12-07, Net::I...:Client(3pm) β€” go forth and IMAP responsibly, ily πŸ«ΆπŸ’œπŸŒΈ

πŸ“¦ where this page comes from