Mail::IMAPClient(3)

🌸 NAME 🌸

Mail::IMAPClient — An IMAP Client API (yes bestie, this is the Mail::IMAPClient(3) manual page 💖).

✨ SYNOPSIS ✨

use Mail::IMAPClient;

my $imap = Mail::IMAPClient->new(
  Server   => 'localhost',
  User     => 'username',
  Password => 'password',
  Ssl      => 1,
  Uid      => 1,
);

my $folders = $imap->folders
  or die "List folders error: ", $imap->LastError, "\n";
print "Folders: @$folders\n";

$imap->select( $Opt{folder} )
  or die "Select '$Opt{folder}' error: ", $imap->LastError, "\n";

$imap->fetch_hash("FLAGS", "INTERNALDATE", "RFC822.SIZE")
  or die "Fetch hash '$Opt{folder}' error: ", $imap->LastError, "\n";

$imap->logout
  or die "Logout error: ", $imap->LastError, "\n";

💖 DESCRIPTION 💖

Okay so this module gives you methods that implement the IMAP protocol, so you can vibe with IMAP message stores. Slay.

You use it by constructing or instantiating a new IMAPClient object via the new constructor method. Once the object has been instantiated, the connect method is either implicitly or explicitly called. At that point, methods are available that implement the IMAP client commands as specified in RFC3501. When processing is complete, the logout object method should be called.

This documentation is not meant to be a replacement for RFC3501 nor any other IMAP related RFCs. Like, it's giving helpful notes, not a full RFC remix.

Note that this documentation uses the term folder in place of RFC3501's use of mailbox. This documentation reserves the use of the term mailbox to refer to the set of folders owned by a specific IMAP id. Iykyk.

🦋 Connection State 🦋

RFC3501 defines four possible states for an IMAP connection: not authenticated, authenticated, selected, and logged out. These correspond to the IMAPClient constants Connected, Authenticated, Selected, and Unconnected, respectively. These constants can be used in conjunction with the Status method to determine the status of an IMAPClient object and its underlying IMAP session. Cute, right? 💅

Note that an IMAPClient object can be in the Unconnected state both before a server connection is made and after it has ended. This differs slightly from RFC3501, which does not define a pre-connection status. For a discussion of the methods available for examining the IMAPClient object's status, see the section labeled Status Methods, below.

🔐 Advanced Authentication Mechanisms 🔐

RFC3501 defines two commands for authenticating to an IMAP server:

  • LOGIN — LOGIN is for plain text authentication.
  • AUTHENTICATE — AUTHENTICATE for more advanced and/or secure authentication mechanisms.

Mail::IMAPClient supports the following AUTHENTICATE mechanisms:

  • DIGEST-MD5 — DIGEST-MD5 authentication requires the Authen::SASL and Digest::MD5 modules. See also Authuser.
  • CRAM-MD5 — CRAM-MD5 requires the Digest::HMAC_MD5 module.
  • PLAIN (SASL) — PLAIN (SASL) authentication allows the optional use of the Proxy parameter. RFC 4616 documents this syntax for SASL PLAIN:
message = [authzid] UTF8NUL authcid UTF8NUL passwd

When Proxy is defined, User is used as 'authzid' and Proxy is used as 'authcid'. Otherwise, User is used as 'authcid'.

  • NTLM — NTLM authentication requires the Authen::NTLM module. See also Domain.

😭 Errors 😭

If you attempt an operation that results in an error, then you can retrieve the text of the error message by using the LastError method. However, the LastError method is an object method (not a class method) and can only be used once an object is successfully created. In cases where an object is not successfully created the $@ variable is set with an error message. Not me checking $@ like it's a group chat notification 💀.

Mail::IMAPClient resets $@ and LastError to undef before most IMAP requests, so the values only have a short lifespan. LastError will always contain error info from the last error, until another error is encountered, another IMAP command is issued or it is explicitly cleared.

Please note that the use of $@ is subject to change in the future release so it is best to use LastError for error checking once a Mail::IMAPClient object has been created. Periodt.

Errors in the new method can prevent your object from ever being created. If the Server, User, and Password parameters are supplied to new, it will attempt to call connect and login. Any of these methods could fail and cause the new method call to return undef and leave the variable $@ set to an error message.

WARNING: (due to historical API behavior) on errors, many methods may return undef regardless of LIST/SCALAR context. Therefore, it may be wise to use most methods in a scalar context. Regardless, check LastError for details on errors. Bestie, please check LastError, I'm begging 🫶.

🎀 Transactions 🎀

RFC3501 requires that each line in an IMAP conversation be prefixed with a tag. A typical conversation consists of the client issuing a tag-prefixed command string, and the server replying with one or more lines of output. Those lines of output will include a command completion status code prefixed by the same tag as the original command string. It's giving very structured chat thread energy.

The IMAPClient module uses a simple counter to ensure that each client command is issued with a unique tag value. This tag value is referred to by the IMAPClient module as the transaction number. A history is maintained by the IMAPClient object documenting each transaction. The Transaction method returns the number of the last transaction, and can be used to retrieve lines of text from the object's history.

The Clear parameter is used to control the size of the session history so that long-running sessions do not eat up unreasonable amounts of memory. See the discussion of Clear parameter for more information.

The Report transaction returns the history of the entire IMAP session since the initial connection or for the last Clear transactions. This provides a record of the entire conversation, including client command strings and server responses, and is a wonderful debugging tool as well as a useful source of raw data for custom parsing. Literally iconic for debugging, no cap 🔥.

🎀 CLASS METHODS 🎀

okay so bestie, plot twist: there are a couple of methods that can be invoked as class methods. Generally? They can be invoked as an object method too, no drama. But heads up — if new gets called as an object method, the object you get back is identical to what would have been returned if new had been called as a class method. It does not hand you a copy of the original object. Same object, same vibe, no clones. 💅


✨ new ✨

Example first, because we love a preview:

my $imap = Mail::IMAPClient->new(%args)
  or die "new failed: $@\n";

The new method creates a shiny brand new instance of an IMAPClient object. Main character energy from the very first line. 🌟

If the Server parameter is passed as an argument to new, then new will implicitly call the connect method, which drops the new object into the Connected state. And if User and Password values are also provided? Then connect will in turn call login, and the resulting object gets returned from new in the Authenticated state. slay, one call and you're logged in. ✨

If the Server parameter is not supplied, then the IMAPClient object is created in the Unconnected state. Chill. No connection yet. Couch mode. 🛋️

If the new method is passed arguments, then those arguments are treated as a list of key=>value pairs. The key should be one of the parameters as documented under Parameters below. 👇

Here are some examples:

use Mail::IMAPClient;

# returns an unconnected Mail::IMAPClient object:
my $imap = Mail::IMAPClient->new;
# ...
# intervening code using the 1st object, then:
# (returns a new, authenticated Mail::IMAPClient object)
$imap = Mail::IMAPClient->new(
    Server   => $host,
    User     => $id,
    Password => $pass,
    Clear    => 5,   # Unnecessary since '5' is the default
    # ...            # Other key=>value pairs go here
) or die "Cannot connect to $host as $id: $@";

See also Parameters, connect and login for more info on how to manually connect and login after new. iykyk, sometimes you want to do it in two steps instead of one. 🫶


✨ Quote ✨

Example:

$imap->search( HEADER => 'Message-id' => \$imap->Quote($msg_id) );

The Quote method accepts a value as an argument and returns its argument as a correctly quoted string or a literal string. Since version 3.17 Mail::IMAPClient automatically quotes search arguments — which is why we use a SCALARREF here, so that search will not modify or re-quote the value returned by Quote. Little handoff, no double-processing. 🎀

💡 Note: this method should not be used on folder names for Mail::IMAPClient methods, since methods that accept folder names as an argument will quote the folder name arguments automatically. Let the folder methods do their own thing, bestie.

If you are getting unexpected results when running methods with values that have (or might have) embedded spaces, double quotes, braces, or parentheses, then calling Quote may be necessary. This method should not be used with arguments that are wrapped in quotes or parens if those quotes or parens are required by RFC3501. For example, if the RFC requires an argument in this format:

( argument )

and the argument is (or might be) "pennies (from heaven)", then one could use:

$argument = "(" . $imap->Quote($argument) . ")"

Of course, the fact that sometimes these characters are sometimes required delimiters is precisely the reason you must quote them when they are not delimiting. It's giving "context is everything". 💀

However — and this is the messy part — there are times when a method fails unexpectedly and may require the use of Quote to work. Should this happen, you can probably file a bug/enhancement request for Mail::IMAPClient to safeguard the particular call/case better. 🙈

An example is RFC822 Message-id's, which usually don't contain quotes or parens. When dealing with these it is usually best to take proactive, defensive measures from the very start and use Quote. Protect your peace. 🛡️


✨ Range ✨

Example:

my $parsed = $imap->parse_headers(
    $imap->Range( $imap->messages ), "Date", "Subject"
);

The Range method will condense a list of message sequence numbers or message UID's into the most compact format supported by RFC3501. It accepts one or more arguments, each of which can be:

  1. a message number,
  2. a comma-separated list of message numbers,
  3. a colon-separated range of message numbers (i.e. "$begin:$end"),
  4. a combination of messages and message ranges, separated by commas (i.e. 1,3,5:8,10), or
  5. a reference to an array whose elements are like a) through d).

The Range method returns a Mail::IMAPClient::MessageSet object. The object uses overload, and if treated as a string it will act like a string. This means you can literally ignore its objectivity and just treat it like a string whose value is your message set expressed in compact format. Bestie it's a string in a trench coat. 🧥✨

This method provides an easy way to add or remove messages from a message set. So convenient. Obsessed.

For more information see Mail::IMAPClient::MessageSet.


✨ Rfc3501_date ✨

Example:

$Rfc3501_date = $imap->Rfc3501_date($seconds);
# or:
$Rfc3501_date = Mail::IMAPClient->Rfc3501_date($seconds);

The Rfc3501_date method accepts one input argument: a number of seconds since the epoch date. It returns an RFC3501 compliant date string for that date (as required in date-related arguments to SEARCH, such as "since", "before", etc.). Timestamps, but make it formatted. ⏰💖


✨ Rfc3501_datetime ✨

Example:

$date = $imap->Rfc3501_datetime($seconds);
# or:
$date = Mail::IMAPClient->Rfc3501_datetime($seconds);

The Rfc3501_datetime method accepts one or two arguments: a obligatory timestamp and an optional zone. The zone shall be formatted as "[+-]\d{4}", and defaults to +0000. The timestamp follows the definition of the output of the platforms specific time, usually in seconds since Jan 1st 1970. However — important!! — you have to correct the number yourself for the zone. No magic timezone math happening here, that's on you. 🕰️😌


✨ Rfc822_date ✨

Example:

$Rfc822_date = $imap->Rfc822_date($seconds);
# or:
$Rfc822_date = Mail::IMAPClient->Rfc822_date($seconds);

The Rfc822_date method accepts one input argument: a number of seconds since the epoch date. It returns an RFC822 compliant date string for that date (without the Date: prefix). Useful for putting dates in message strings before calling append, search, etc. Drop it in and go. 🗓️🌸


✨ Strip_cr ✨

Examples, plural, we got options:

my $stripped = $imap->Strip_cr($string);
# or:
my @list = $imap->some_imap_method;
@list = $imap->Strip_cr(@list);
# or:
my $list = [ $imap->some_imap_method ];   # returns an array ref
$list = $imap->Strip_cr($list);

The Strip_cr method strips carriage returns from input and returns the new string to the caller. It accepts one or more lines of text as arguments, and returns those lines with all <CR><LF> sequences changed to <LF>. Any input argument with no carriage returns is returned unchanged — untouched, unbothered, thriving. ✨

If the first argument (not counting the class name or object reference) is an array reference, then members of that array are processed as above and subsequent arguments are ignored. And if the method is called in scalar context, then an array reference is returned instead of an array of results. Context matters bestie. 🎀

⚠️ NOTE: Strip_cr does not remove new line characters. Carriage returns only. Do not come for the newlines, they're innocent.

💖 OBJECT METHODS 💖

Object methods must be invoked against objects created via the new method and cannot be invoked as class methods. So make the object first, okay? 🫶

There object methods typically fall into one of two categories. There are mailbox methods which participate in the IMAP session's conversation (i.e. they issue IMAP client commands) and object control methods which do not result in IMAP commands but which may affect later commands or provide details of previous ones. So, talkative methods and behind-the-scenes methods. 🦋

These object control methods can be further broken down into two types: Parameter accessor methods, which affect the behavior of future mailbox methods, and Status Methods, which report on the affects of previous mailbox methods.

Methods that do not result in new IMAP client commands being issued (such as the Transaction, Status, and History methods) all begin with an uppercase letter, to distinguish them from methods that do correspond to IMAP client commands. Class methods and eponymous parameter methods likewise begin with an uppercase letter because they also do not correspond to an IMAP client command. Capital letter = no IMAP command being sent. Cute little naming system, honestly iconic. 👑

As a general rule, mailbox control methods return undef on failure and something besides undef when they succeed. This rule is modified in the case of methods that return search results. When called in a list context, searches that do not find matching results return an empty list. When called in a scalar context, searches with no hits return undef instead of an array reference. If you want to know why you received no hits, you should check LastError or $@, which will be empty if the search was successful but had no matching results, but populated with an error message if the search encountered a problem (such as invalid parameters). Empty error + zero hits = it genuinely just found nothing. Error message = something actually went wrong. Big difference!! 😭

A number of IMAP commands do not have corresponding Mail::IMAPClient methods. Patches are welcome. 🙏 In the pre-2.99 releases of this module, they were automatically created (AUTOLOAD), but that was very error-prone and stalled the progress of this module. So yeah, we retired the magic. It was giving chaos. 💀


📬 Mailbox Control Methods 📬

🍓 append 🍓

Example:

my $uid_or_true = $imap->append( $folder, $msgtext )
  or die "Could not append: ", $imap->LastError;
⚠️ WARNING: This method may be deprecated in the future, consider using append_string instead of this method. Not me warning you ahead of time, bestie. 🙈

The append method adds a message to the specified folder. See append_string for details as it is effectively an alias for that method.

DEPRECATED BEHAVIOR: Additional arguments are added to the message text, separated with <CR><LF>. Old behavior, still true, but deprecated. Don't get attached. 💅


🍓 append_string 🍓

Example:

# brackets indicate optional arguments (not array refs):
my $uidort = $imap->append_string( $folder, $msgtext [,$flags [,$date ] ] )
    or die "Could not append_string: ", $imap->LastError;

Arguments, let's go:

  • $folder — the name of the folder to append the message to 📁
  • $msgtext — the message text (including headers) of the message ✉️
  • $flags — An optional list of flags to set. The list must be specified as a space-separated list of flags, including any backslashes that may be necessary and optionally enclosed by parenthesis.
  • $date — An optional RFC3501 date argument to set as the internal date. It should be in the format described for date_time fields in RFC3501, i.e. "dd-Mon-yyyy hh:mm:ss +0000".

And a crucial little note about $date: if you want to specify a date/time but you don't want any flags, then specify undef as the third ($flags) argument. Gotta leave that slot open, bestie. 🕳️✨

Returns:

  • error: undef — On error, undef can be returned regardless of LIST/SCALAR context. Check LastError for details. 😭
  • success: UID or $imap — With UIDPLUS the UID of the new message is returned, otherwise a true value (currently $self) is returned. So you usually get a UID, but sometimes you just get the object back and it's still a win. 🎉

To protect against "bare newlines", append will insert a carriage return before any newline that is "bare". Protecting your message format, no cap. 🛡️


🍓 append_file 🍓

Example:

my $new_msg_uid = $imap->append_file(
    $folder,
    $file,
    [ undef, $flags, $date ] # optional
) or die "Could not append_file: ", $imap->LastError;

The append_file method adds a message to the specified folder. 💌 Heads up bestie: those brackets in the example mean optional arguments, they are not telling you to pass an array reference. iykyk.

Arguments:

  • $folder — the name of the folder you're appending the message to.
  • $file — a filename, filehandle or SCALAR reference which holds an RFC822-formatted message. so flexible, we love options ✨
  • undef — a deprecated argument used as a place holder for backwards compatibility. it's giving legacy, be nice to it 🫶
  • $flags — this optional argument is handled the same as append_string.
  • $date — also optional, also handled the same as append_string (RFC3501 date), except when $date is "1" (one) — in that case the modification time (mtime) of the file gets used. cute lil shortcut 🎀

Returns:

  • error: undef — on error, undef can be returned regardless of LIST/SCALAR context. Check LastError for the deets.
  • success: UID or $imap — with UIDPLUS the UID of the new message is returned; otherwise a true value (currently $self) is returned.

To protect against "bare newlines", append_file will insert a carriage return before any newline that is "bare". 🛡️ safety first, always.

The append_file method provides a mechanism for allowing large messages to be appended without holding the whole file in memory. main character efficiency honestly 💅

Version note: in 2.x an optional third argument to use for input_record_separator was allowed, however this argument is ignored/not supported as of 3.x. rip to that argument, she's retired 🌸

💌 authenticate

Example:

$imap->authenticate( $authentication_mechanism, $coderef )
  or die "Could not authenticate: ", $imap->LastError;

This method implements the AUTHENTICATE IMAP client command. It can be called directly, or it may get called by login if the Authmechanism parameter is set to anything except 'LOGIN'.

The authenticate method accepts two arguments: an authentication type to be used (ie CRAM-MD5) and a code or subroutine reference to execute to obtain a response. The method assumes that the authentication type you specified in the first argument follows a challenge-response flow. so it's like a whole conversation, very demure 💬

Here's the flow, bestie: authenticate issues the IMAP Client AUTHENTICATE command and receives a challenge from the server. That challenge (minus any tag prefix or enclosing '+' characters but still in the original base64 encoding) is passed as the only argument to the code or subroutine referenced in the second argument. The return value from the 2nd argument's code is written to the server as is, except that a <CR><LF> sequence is appended if necessary. periodt. ✨

If one or both of the arguments are not specified in the call to authenticate but their corresponding parameters have been set (Authmechanism and Authcallback, respectively) then the parameter values are used. Arguments provided to the method call however will override parameter settings. the call always wins, no cap 👑

If you do not specify a second argument and you have not set the Authcallback parameter, then the first argument must be one of the authentication mechanisms for which Mail::IMAPClient has built in support. don't try to freestyle it 🙈

See also the login method, which is the simplest form of authentication defined by RFC3501. 🍓


⏪ before

Example:

my @msgs = $imap->before($Rfc3501_date)
  or warn "No messages found before $Rfc3501_date.\n";

The before method works just like the since method, below, except it returns a list of messages whose internal system dates are before the date supplied as the argument to before. literally the same vibe, opposite direction 🦋


📜 body_string

Example:

my $string = $imap->body_string($msgId)
  or die "body_string failed: ", $imap->LastError;

The body_string method accepts a message sequence number (or a message UID, if the Uid parameter is set to true) as an argument and returns the message body as a string. The returned value contains the entire message in one scalar variable, without the message headers. just the body, no extra baggage, we stan 🎀


🧩 bodypart_string

Example:

my $string = $imap->bodypart_string(
    $msgid, $part_number, $length, $offset
) or die "Could not get bodypart string: ", $imap->LastError;

The bodypart_string method accepts a message sequence number (or a message UID, if the Uid parameter is set to true) and a body part as arguments and returns the message part as a string. The returned value contains the entire message part (or, optionally, a portion of the part) in one scalar variable. 💖

If an optional third argument is provided, that argument is the number of bytes to fetch. (The default is the whole message part.) If an optional fourth argument is provided then that fourth argument is the offset into the part at which the fetch should begin. The default is offset zero, or the beginning of the message part. so specific, love that for us ✨

If you specify an offset without specifying a length then the offset will be ignored and the entire part will be returned. ngl that one surprises people — offset alone does nothing, the whole part comes back. 🙈

bodypart_string will return "undef" if it encounters an error.


🛠️ capability

Example:

my $features = $imap->capability
  or die "Could not determine capability: ", $imap->LastError;

The capability method returns an array (or arrayref in scalar context) of capabilities as returned by the CAPABILITY IMAP client command. If the CAPABILITY IMAP client command fails for any reason then the capability method will return "undef". 💀

Supported capabilities are cached by the client, however, this cache is deleted after a connection is set to Authenticated and when starttls is called. so the cache gets a lil refresh — she's not stale, she's renewed ✨

See also has_capability.


🔒 close

Example:

$imap->close or die "Could not close: $@\n";

The close method is used to close the currently selected folder via the CLOSE IMAP client command. According to RFC3501, the CLOSE command performs an implicit EXPUNGE, which means that any messages that are flagged as \Deleted (i.e. with the delete_message method) will now be deleted. 🔥

So like — if you haven't deleted any messages then close can be thought of as an "unselect". but if you *have*… they're gone bestie, no takebacks 😭

Note: this closes the currently selected folder, not the IMAP session. two completely different things, don't get it twisted 💅

See also delete_message, expunge, and RFC3501.


🗜️ compress

Example:

$imap->compress or die "Could not enable RFC4978 compression: $@\n";

The compress method accepts no arguments. This method is used to instruct the server to use the DEFLATE (RFC1951) compression extension. See the Compress attribute for how to specify arguments for use during the initialization process. smol data, big vibes 🦋

Version note: method added in Mail::IMAPClient 3.30

🔌 connect

Example:

$imap->connect or die "Could not connect: $@\n";

The connect method connects an imap object to the server. It returns "undef" if it fails to connect for any reason.

If values are available for the User and Password parameters at the time that connect is invoked, then connect will call the login method after connecting and return the result of the login method to connect's caller. If either or both of the User and Password parameters are unavailable but the connection to the server succeeds then connect returns a pointer to the IMAPClient object. so it auto-logs-in if it can, otherwise you get the object and you handle it yourself 🫶

The Server parameter must be set (either during new method invocation or via the Server object method) before invoking connect. When the parameter is an absolute file path, an UNIX socket will get opened. 🔌 If the Server parameter is supplied to the new method then connect is implicitly called during object construction. sneaky but convenient ✨

The connect method sets the state of the object to "Connected" if it successfully connects to the server. It returns "undef" on failure.


📋 copy

Example:

# Here brackets indicate optional arguments:
my $uidList = $imap->copy($folder, $msg_1 [ , ... , $msg_n ])
  or die "Could not copy: $@\n";

Or:

# Now brackets indicate an array ref!
my $uidList = $imap->copy($folder, [ $msg_1, ... , $msg_n ])
  or die "Could not copy: $@\n";

The copy method requires a folder name as the first argument, and a list of one or more messages sequence numbers (or messages UID's, if the UID parameter is set to a true value). The message sequence numbers or UID's should refer to messages in the currently selected folder. Those messages will be copied into the folder named in the first argument. 💌

The copy method returns "undef" on failure and a true value if successful. If the server to which the current Mail::IMAPClient object is connected supports the UIDPLUS capability then the true value returned by copy will be a comma separated list of UID's, which are the UID's of the newly copied messages in the target folder. 👑


📁 create

Example:

$imap->create($new_folder)
  or die "Could not create $new_folder: $@\n";

The create method accepts one argument, the name of a folder (or what RFC3501 calls a "mailbox") to create. If you specify additional arguments to the create method and your server allows additional arguments to the CREATE IMAP client command then the extra argument(s) will be passed to your server. 🎀

If you specify additional arguments to the create method and your server does not allow additional arguments to the CREATE IMAP client command then the extra argument(s) will still be passed to your server and the create will fail. big yikes — it doesn't quietly drop them, it just fails 💀

create returns a true value on success and "undef" on failure.


📅 date

Example:

my $date = $imap->date($msg);

The date method accepts one argument, a message sequence number (or a message UID if the Uid parameter is set to a true value). It returns the date of message as specified in the message's RFC822 Date: header, without the Date: prefix. ✨

The date method is a short-cut for:

my $date = $imap->get_header($msg,"Date");

🗑️ delete

Example:

$imap->delete($folder) or die "Could not delete $folder: $@\n";

The delete method accepts a single argument, the name of a folder to delete. It returns a true value on success and "undef" on failure. bye bye folder, hope you had a good run 😭


🚫 deleteacl

Example:

$imap->deleteacl( $folder, $userid )
  or die "Could not delete acl: $@\n";

The deleteacl method accepts two input arguments, a folder name, a user id (or authentication identifier, to use the terminology of RFC2086). See RFC2086 for more information. (This is somewhat experimental and its implementation may change.) experimental means it might shift on us, so don't get too attached 🙈


🗑️✨ delete_message

Example:

my @msgs = $imap->seen;
scalar(@msgs) and $imap->delete_message(\@msgs)
  or die "Could not delete_message: $@\n";

The above could also be rewritten like this:

# scalar context returns array ref
my $msgs = scalar($imap->seen);

scalar(@$msgs) and $imap->delete_message($msgs)
  or die "Could not delete_message: $@\n";

Or, as a one-liner:

         $imap->delete_message( scalar($imap->seen) )
           or warn "Could not delete_message: $@\n";
         # just give warning in case failure is
         # due to having no 'seen' msgs in the 1st place!

Okay bestie, so delete_message takes a list of arguments. If the Uid parameter is not set to a true value, then each item in the list should be either:

  • a message sequence number,
  • a comma-separated list of message sequence numbers,
  • a reference to an array of message sequence numbers, or

If the Uid parameter is set to a true value, then each item in the list should be either:

  • a message UID,
  • a comma-separated list of UID’s, or
  • a reference to an array of message UID’s.

The messages identified by the sequence numbers or UID’s will be deleted. If it succeeds, delete_message returns the number of messages it was told to delete. But — and this is the lowkey important part — since the delete is done by issuing the +FLAGS.SILENT option of the STORE IMAP client command, there is no guarantee that the delete was successful for every message. In this manner, delete_message sacrifices accuracy for speed. Generally, though, if a single message in a list of messages fails to be deleted, it’s because it was already deleted, which is what you wanted anyway, so why worry about it? 😌 If there is a more severe error — i.e. the server replies "NO", "BAD", or, banish the thought, "BYE" — then delete_message will return undef.

If you absolutely must have guaranteed results, then use the IMAP STORE client command (via the default method) and use the +FLAGS (\Deleted) option, and then parse your results manually. Like:

         $imap->store( $msg_id, '+FLAGS (\Deleted)' );
         my @results = $imap->History( $imap->Transaction );
           ...           # code to parse output goes here

(Frankly I see no reason to bother with any of that; if a message doesn’t get deleted, it’s almost always because it’s already not there, which is what you want anyway. But 'your mileage may vary' and all that. 💅)

The IMAPClient object must be in "Selected" status to use the delete_message method.

NOTE: All the messages identified in the input argument(s) must be in the currently selected folder. Failure to comply with this requirement will almost certainly result in the wrong message(s) being deleted. 😭
ADDITIONAL NOTE: In the grand tradition of the IMAP protocol, deleting a message doesn’t actually delete the message. Really. If you want to make sure the message has been deleted, you need to expunge the folder (via the "expunge" method, which is implemented via the default method). Or at least "close" it. This is generally considered a feature, since after deleting a message, you can change your mind and undelete it at any time before your "expunge" or "close". ✨

See also: the "delete" method, to delete a folder, the "expunge" method, to expunge a folder, the "restore_message" method to undelete a message, and the "close" method (implemented here via the default method) to close a folder. Oh, and don’t forget about RFC3501. 🦋

deny_seeing 🫶

Example:

         # Reset all read msgs to unread
         # (produces error if there are no seen msgs):
         $imap->deny_seeing( scalar($imap->seen) )
           or die "Could not deny_seeing: $@\n";

The deny_seeing method accepts a list of one or more message sequence numbers, or a single reference to an array of one or more message sequence numbers, as its argument(s). It then unsets the "\Seen" flag for those messages (so that you can "deny" that you ever saw them 👀). Of course, if the Uid parameter is set to a true value, then those message sequence numbers should be unique message id’s.

Note that specifying "$imap->deny_seeing(@msgs)" is just a shortcut for specifying "$imap->unset_flag("Seen",@msgs)".

disconnect 💔

Example:

         $imap->disconnect or warn "Could not logout: $@\n";

This method calls "logout", see "logout" for details.

done ✅

Example:

         my $tag = $imap->idle or warn "idle failed: $@\n";
         doSomethingA();
         my $idlemsgs = $imap->idle_data() or warn "idle_data error: $@\n";
         doSomethingB();
         my $results = $imap->done($tag) or warn "Error from done: $@\n";

The done method tells the IMAP server to terminate the IDLE command. The only argument is the tag (identifier) received from the previous call to "idle". If tag is not specified, a default tag based on the Count attribute is assumed to be the tag to look for in the response from the server.

If an invalid tag is specified, or the default tag is wrong, then done will hang indefinitely or until a timeout occurs. 💀

If done is called when an "idle" command is not active, then the server will likely respond with an error like * BAD Invalid tag.

On failure, undef is returned and "LastError" is set.

See also "idle", "idle_data" and "Results".

examine 🔍

Example:

         $imap->examine($folder) or die "Could not examine: $@\n";

The examine method selects a folder in read-only mode and changes the object’s state to "Selected". The folder selected via the examine method can be examined, but no changes can be made unless it is first selected via the "select" method.

The examine method accepts one argument, which is the name of the folder to select.

exists 🌸

Example:

         $imap->exists($folder) or warn "$folder not found: $@\n";

Accepts one argument, a folder name. Returns true if the folder exists or false if it does not exist.

expunge 🧹

Example:

         $imap->expunge($folder) or die "Could not expunge: $@\n";

The expunge method accepts one optional argument, a folder name. It expunges the folder specified as the argument, or the currently selected folder (if any) when no argument is supplied.

Although RFC3501 does not permit optional arguments (like a folder name) to the EXPUNGE client command, the "expunge" method does. Note: expunging a folder deletes the messages that have the \Deleted flag set (i.e. messages flagged via "delete_message"). 🗑️

See also the "close" method, which "deselects" as well as expunges.

fetch 📥

Usage:

$imap->fetch( [$seq_set|ALL], @msg_data_items )

Example:

my $output = $imap->fetch(@args) or die "Could not fetch: $@\n";

The fetch method implements the FETCH IMAP client command. It accepts a list of arguments, which will be converted into a space-delimited list of arguments to the FETCH IMAP client command. If no arguments are supplied, then fetch does a FETCH ALL. If the Uid parameter is set to a true value, then the first argument will be treated as a UID or list of UID’s, which means that the UID FETCH IMAP client command will be run instead of FETCH. (It would really be a good idea at this point to review RFC3501. 👑)

If called in array context, fetch will return an array of output lines. The output lines will be returned just as they were received from the server, so your script will have to be prepared to parse out the bits you want. The only exception to this is literal strings, which will be inserted into the output line at the point at which they were encountered (without the {nnn} literal field indicator). See RFC3501 for a description of literal fields.

If fetch is called in a scalar context, then a reference to an array (as described above) is returned instead of the entire array.

fetch returns undef on failure. Inspect "LastError" or $@ for an explanation of your error.

fetch_hash 🍓

Usage:

$imap->fetch_hash( [$seq_set|ALL], @msg_data_items, [\%msg_by_ids] )

Examples:

my $hashref = $imap->fetch_hash("RFC822.SIZE");

OR

my $hashref = {};
$imap->fetch_hash( "RFC822.SIZE", $hashref );
print "Msg #$_ is $hashref->{$_}->{'RFC822.SIZE'} bytes\n" for (keys %$hashref);

The fetch_hash method accepts a list of message attributes to be fetched (as described in RFC3501). It returns a hash whose keys are all the messages in the currently selected folder and whose values are key-value pairs of fetch keywords and the message’s value for that keyword (see sample output below).

If fetch_hash is called in scalar context, it returns a reference to the hash instead of the hash itself. If the last argument is a hash reference, then that hash reference will be used as the place where results are stored (and that reference will be returned upon successful completion). If the last argument is not a reference, then it will be treated as one of the FETCH attributes and a new hash will be created and returned (either by value or by reference, depending on the context in which fetch_hash was called).

For example, if you have a folder with 3 messages and want the size and internal date for each of them, you could do the following:

use Mail::IMAPClient;
use Data::Dumper;
# ... other code goes here
$imap->select($folder);
my $hash = $imap->fetch_hash( "RFC822.SIZE", "INTERNALDATE" );
# (Same as:
#  my $hash = $imap->fetch_hash("RFC822.SIZE");
#  $imap->fetch_hash( "INTERNALDATE", $hash );
# ).
print Data::Dumper->Dumpxs( [$hash], ['$hash'] );

This would result in Data::Dumper output similar to the following:

   $hash = {
       '1' => {
                  'INTERNALDATE' => '21-Sep-2002 18:21:56 +0000',
                  'RFC822.SIZE' => '1586',
              },
       '2' => {
                  'INTERNALDATE' => '22-Sep-2002 11:29:42 +0000',
                  'RFC822.SIZE' => '1945',
              },
       '3' => {
                  'INTERNALDATE' => '23-Sep-2002 09:16:51 +0000',
                  'RFC822.SIZE' => '134314',
              }
         };

By itself this method may be useful for tasks like obtaining the size of every message in a folder. It issues one command and receives one (possibly long!) response from the server. 😭

If the fetch request causes the server to return data in a parenthesized list, the data within the parenthesized list may be escaped via the Escape() method. Use the Unescape() method to get the raw values back in this case.

flags 🎀

Example:

         my $flags = $imap->flags($msgid)
           or die "flags failed: $@\n";

The flags method implements the FETCH IMAP client command to list a single message’s flags. It accepts one argument, a message sequence number (or a message UID, if the Uid parameter is true), and returns an array (or a reference to an array, if called in scalar context) listing the flags that have been set. Flag names are provided with leading backslashes. 💅

Like, as of version 1.11 you can hand it either a list of message id's or a reference to an array of message id's (and "message id" here means either a sequence number, if the Uid parameter is false, or message UID's, if the Uid parameter is true) instead of just one single message sequence number or UID. So flexible ✨. And when you do that, plot twist: the return value is not an array or an array reference anymore — it's a hash reference, where each key is a message sequence number (or UID) and each value is a reference to an array of flags set for that message. iykyk 💅

So fr fr, if you wanna display the flags for every message in the folder where you keep the e-mail related to your plans for world domination 👑, you could do something like this:

  use Mail::IMAPClient;
  my $imap = Mail::IMAPClient->new(
      Server   => $imaphost,
      User     => $login,
      Password => $pass,
      Uid      => 1,        # optional
  );

  $imap->select("World Domination");
  # get the flags for every message in my 'World Domination' folder
  $flaghash = $imap->flags( scalar( $imap->search("ALL") ) );

  # pump through sorted hash keys to print results:
  for my $k ( sort { $flaghash->{$a} <=> $flaghash->{$b} } keys %$flaghash ) {
      # print: Message 1: \Flag1, \Flag2, \Flag3
      print "Message $k:\t", join( ", ", @{$flaghash->{$k}} ), "\n";
  }

🗂️ folders 🗂️

Example first, always:

  $imap->folders or die "Could not list folders: $@\n";

The folders method returns an array listing the folders that are available. Heads up though: it will only be successful if the object is in the Authenticated or Selected states 🫶.

It takes one optional argument, which is a prefix ✨. If you supply a prefix to folders, then only the folders beginning with that prefix get returned.

Like, for example:

  print join( ", ", $imap->folders ), ".\n";
  # Prints:
  # INBOX, Sent, Projects, Projects/Completed, Projects/Ongoing, Projects Software.
  print join( ", ", $imap->folders("Projects") ), ".\n";
  # Prints:
  # Projects, Projects/Completed, Projects/Ongoing, Projects Software.
  print join( ", ", $imap->folders("Projects" . $imap->separator) ), ".\n";
  # Prints:
  # Projects/Completed, Projects/Ongoing
Ok so lowkey important 🚨: older docs used to suggest that if you just want to list a folder's subfolders (and not the folder itself), you need to include the hierarchy separator character (as returned by the separator method). But nope — that does not match the behavior of the existing implementation, so you're gonna have to manually exclude the parent folder from the results yourself. Sorry bestie 😭

🌸 folders_hash 🌸

  my @fhashes = $imap->folders_hash
    or die "Could not get list of folder hashes.\n";

folders_hash takes one optional argument too, which is a prefix 💖. Supply a prefix and only the folders beginning with that prefix are returned.

You get back an array(ref) of hashes stuffed with info about the folders you asked for. Each hash has three keys (name, attrs, delim) and looks exactly like this:

  {
    name  => 'Mail/Box/Name',
    attrs => [ '\Marked', '\HasNoChildren' ],
    delim => '/',
  }

IMAP servers that implement RFC6154 return attributes you can use to spot special-use mailboxes (folders) 👀:

  my $sattr_re = /\A\\(?:All|Archive|Drafts|Flagged|Junk|Sent|Trash)\Z/;
  foreach my $fhash (@fhashes) {
      next unless defined $fhash->{name};
      my @special = grep { $sattr_re } @{ $fhash->{attrs} };
      print("special: $fhash->{name} : @special\n") if (@special);
  }
Version note 📌: method added in Mail::IMAPClient 3.34

💀 xlist_folders (DEPRECATED) 💀

This method is deprecated as of version 3.34 🚨. Please use folders_hash instead. See RFC6154 for the attributes to be used to identify special-use mailboxes (folders).

Example:

  my $xlist = $imap->xlist_folders
    or die "Could not get xlist folders.\n";

IMAP servers that implement the XLIST extension (Gmail, looking at you 👀) designate particular folders to be used for particular functions. Which is genuinely iconic when you wanna know which folder should be used for Trash but you literally can't predict the actual folder name (e.g. with Gmail, the folder names change depending on the user's locale settings 🌈).

The xlist_folders method returns a hash listing any "xlist" folder names, with the values listing the actual folders that should be used for those names. So for example, using this method with a Gmail user on the English (US) locale might give you this output from Data::Dumper:

  $VAR1 = {
      'Inbox'   => 'Inbox',
      'AllMail' => '[Gmail]/All Mail',
      'Trash'   => '[Gmail]/Trash',
      'Drafts'  => '[Gmail]/Drafts',
      'Sent'    => '[Gmail]/Sent Mail',
      'Spam'    => '[Gmail]/Spam',
      'Starred' => '[Gmail]/Starred'
  };

Same list, but for a user on the French locale, might look like this:

  $VAR1 = {
      'Inbox'   => 'Bo&AO4-te de r&AOk-ception',
      'AllMail' => '[Gmail]/Tous les messages',
      'Trash'   => '[Gmail]/Corbeille',
      'Drafts'  => '[Gmail]/Brouillons',
      'Sent'    => '[Gmail]/Messages envoy&AOk-s',
      'Spam'    => '[Gmail]/Spam',
      'Starred' => '[Gmail]/Suivis'
  };

Mail::IMAPClient recognizes these "xlist" folder names 🎀:

  • Inbox
  • AllMail
  • Trash
  • Drafts
  • Sent
  • Spam
  • Starred

These are currently the only ones Gmail supports. The XLIST extension isn't documented, and there are no other known implementations besides Gmail, so this list is based on what Gmail provides. That's the whole tea ☕.

If the server doesn't support the XLIST extension, this method returns undef.

Version note 📌: method added in Mail::IMAPClient 3.21

🦋 has_capability 🦋

Example:

  my $has_feature = $imap->has_capability($feature)
    or die "Could not do has_capability($feature): $@\n";

Returns:

  • undef — if the underlying capability call fails, then undef is returned 💀
  • "" or () — if the server does not have the requested capability, then you get either an empty string ("" in scalar context) or an empty list (() in list context)
  • a true value — if the server does have the requested capability, then a true value is returned ✨. The true value depends on the server response for the capability you requested. The value will be an array reference in scalar context, or an array in list context. The returned data is genuinely useful for understanding more about specific capabilities. For example, take this server CAPABILITY response:
  * CAPABILITY IMAP4rev1 SORT SORT=DISPLAY I18NLEVEL=1 AUTH=PLAIN AUTH=XTEST

Results come back as shown by the trailing comments:

  $c = $imap->has_capability("IMAP4rev1");    # [ "IMAP4rev1" ]
  @c = $imap->has_capability("IMAP4rev1");    # ( "IMAP4rev1" )
  $c = $imap->has_capability("SORT");         # [ "DISPLAY" ]
  @c = $imap->has_capability("SORT=DISPLAY"); # ( "SORT=DISPLAY" )
  $c = $imap->has_capability("AUTH");         # [ "PLAIN", "XTEST" ]
  @c = $imap->has_capability("AUTH");         # ( "PLAIN", "XTEST" )
  $c = $imap->has_capability("AUTH=XTEST");   # [ "AUTH=XTEST" ]
  @c = $imap->has_capability("AUTH=XTEST");   # ( "AUTH=XTEST" )
  $c = $imap->has_capability("AUTH=NADA");    # ''
  @c = $imap->has_capability("AUTH=NADA");    # ()
  $c = $imap->has_capability("NADA");         # ''
  @c = $imap->has_capability("NADA");         # ()

💤 idle 💤

Example:

  my $tag = $imap->idle or warn "idle failed: $@\n";
  doSomethingA();
  my $idlemsgs = $imap->idle_data() or warn "idle_data error: $@\n";
  doSomethingB();
  my $results = $imap->done($tag) or warn "Error from done: $@\n";

The idle method tells the IMAP server that the client is ready to accept unsolicited mailbox update messages (on the selected folder/mailbox) 📬. This method is only valid on servers that support the IMAP IDLE extension — see RFC2177 for the details.

idle accepts no arguments and returns the tag (identifier) that was sent by the client for this command. That tag should be supplied as the argument to done when you're ending the IDLE command 🫶.

On failure <undef> is returned and LastError is set.

Once idle has been successful, you can use the idle_data method. Buuut no mailbox operations may be called until the idle command has been terminated by calling done. Do it anyway and you'll get an error — and the idle command will typically be terminated by the server 💀.

See also idle_data and done.


⏳ idle_data ⏳

Usage:

  # an optional timeout in seconds may be specified
  $imap->idle_data( [$timeout] )

Example:

  my $tag = $imap->idle or warn "idle failed: $@\n";
  doSomethingA();
  my $idlemsgs = $imap->idle_data() or warn "idle_data error: $@\n";
  doSomethingB();
  my $results = $imap->done($tag) or warn "Error from done: $@\n";

The idle_data method is how you accept any unsolicited mailbox update messages that the server has sent during an idle command 🌸. It does not send any commands to the server — it simply looks for, and optionally waits for, data from the server and hands that data back to the caller.

It accepts an optional $timeout argument and returns an array (or an array reference if called in scalar context) with the messages from the server ✨.

By default a timeout of 0 seconds is used (do not block). Internally the timeout is passed to select in perlfunc. The timeout controls how long the select call blocks if there are no messages waiting to be read from the server 👀.

On failure <undef> is returned and LastError is set.

See also imap and done.

Version note 📌: method added in Mail::IMAPClient 3.23 Warning 🚨: this method is considered experimental and the interface/output may change in a future version. Not me warning you in advance 💀

👑 imap4rev1 👑

Example:

  $imap->imap4rev1 or die "Could not imap4rev1: $@\n";

Returns true if the IMAP server the IMAPClient object is connected to has the IMAP4REV1 capability 🔥. If the server doesn't have the capability, you get the empty string "" back. If the underlying capability call fails, then undef is returned.


📅 internaldate 📅

Example:

  my $msg_internal_date = $imap->internaldate($msgid)
    or die "internaldate failed: $@\n";

internaldate accepts one argument — a message id (or UID if the Uid parameter is true) — and returns that message's internal date, or undef if the call fails or if the internal date isn't returned 🫶.


🧚 get_bodystructure 🧚

Example:

  my $bodyStructObject = $imap->get_bodystructure($msgid)
    or die "Could not get_bodystructure: $@\n";

The get_bodystructure method takes exactly one argument — a message sequence number, or, if "Uid" is true, a message UID. It goes and grabs that message's body structure and hands you back a parsed Mail::IMAPClient::BodyStructure object for the message. Iconic, honestly. 💅


get_envelope 💌

Example:

my $envObject = $imap->get_envelope(@args)
  or die "Could not get_envelope: $@\n";

So get_envelope takes one argument, bestie — a message sequence number, or, if "Uid" is true, a message UID. It fetches the message's envelope and returns a Mail::IMAPClient::BodyStructure::Envelope object for it. And what even is that? It's literally just a version of the envelope that's been parsed into a Perl object. That's the whole vibe check. ✨

For more info on how to use this object once you've gotten it, go peek at the Mail::IMAPClient::BodyStructure documentation. (As of this writing there is no separate pod document for Mail::IMAPClient::BodyStructure::Envelope — so, yeah, that's the situation. 🫠)


getacl 🔐

Example:

my $hash = $imap->getacl($folder)
  or die "Could not getacl for $folder: $@\n";

getacl accepts one argument: the name of a folder. If no argument is provided, then the currently selected folder is used as the default. It hands back a reference to a hash. The keys of that hash are userids that have access to the folder, and the value of each element is the permissions for that user. Permissions come listed in a string, in the order returned from the server, with no white space or punctuation between them. Just a little wall of letters. Slay. 🌸


get_header 📨

Example:

my $messageId = $imap->get_header( $msg, "Message-Id" );

The get_header method takes two arguments: a message sequence number or UID, and the name of an RFC822 header (and please, without the trailing colon — we're not animals). It returns the value for that header in the message whose sequence number or UID you passed as the first argument.

  • If no value can be found, it returns "undef".
  • If multiple values are found, it returns the first one.
  • Its return value is always a scalar, always always, no exceptions. 🎀

get_header uses case insensitive matching to get the value, so like, you do not have to worry about the case of your second argument. Type it however your heart desires.

The get_header method is a short-cut for:

my $messageId = $imap->parse_headers($msg,"Subject")->{"Subject"}[0];

getquotaroot 📊

Example:

my $results = $imap->getquotaroot($mailboxname)
  or die "Could not getquotaroot for $mailboxname: $@\n";

The getquotaroot method implements the RFC2087 GETQUOTAROOT command. The $mailboxname defaults to "INBOX" if no argument is provided. Nothing but the classic default for you. 💜

On error "undef" is returned, otherwise "Results" are returned. The results should have the untagged QUOTAROOT response from the server along with the QUOTAROOT's resource usage and limits in an untagged QUOTA response.

See also RFC2087, "getquota", "setquota", "quota" and "quota_usage".


getquota 📈

Example:

my $results = $imap->getquota($quotaroot)
  or die "Could not getquota for $quotaroot: $@\n";

The getquota method implements the RFC2087 GETQUOTA command. The $quotaroot defaults to "user/User" if no argument is provided. Yes, that exact string, not INBOX. Different default, keep up bestie. 🫶

On error "undef" is returned, otherwise "Results" are returned. The results from the server should have the untagged QUOTA response from the server.

See also RFC2087, "getquotaroot", "quota" and "quota_usage".


quota 🧮

Example:

my $limit = $imap->quota($quotaroot)
  or die "Could not get quota limit for $quotaroot: $@\n";

The quota method takes the "Results" from getquota and parses out the "STORAGE" limit returned by the server. The $quotaroot defaults to "INBOX" if no argument is provided.

On error "undef" is returned, otherwise the integer "STORAGE" limit provided by the server is returned. An actual integer, not vibes. 🔥

See also RFC2087, "getquotaroot", "getquota" and "quota_usage".


quota_usage 🧾

Example:

my $usage = $imap->quota_usage($quotaroot)
  or die "Could not get quota usage for $quotaroot: $@\n";

The quota_usage method takes the "Results" from getquota and parses out the "STORAGE" usage returned by the server. The $quotaroot defaults to "INBOX" if no argument is provided.

On error "undef" is returned, otherwise the integer "STORAGE" usage provided by the server is returned.

See also RFC2087, "getquotaroot", "getquota" and "quota".


setquota ✍️

Example:

my $results = $imap->setquota( $quotaroot, $resource, $limit )
  or die "Could not setquota for $quotaroot: $@\n";

The setquota method implements the RFC2087 SETQUOTA command. It accepts multiple pairs of $resource and $limit arguments — so bring as many pairs as you want, it's giving generous. 🌈

The $quotaroot defaults to "user/User" if not defined.

On error "undef" is returned, otherwise "Results" are returned.

See also RFC2087, "getquotaroot" and "getquota".


is_parent 👯

Example:

my $hasKids = $imap->is_parent($folder);

The is_parent method accepts one argument: the name of a folder. It returns a value that indicates whether or not the folder has children. The value it returns is either:

  • 1 (or a positive integer) — the "\HasChildren" attribute is set, indicating that the folder has children.
  • 0 (zero) — the "\HasNoChildren" attribute is set, indicating that the folder has no children at this time.
  • "undef" — the "\NoInferiors" attribute is set, indicating the folder is not permitted to have children.

Eg:

my $parenthood = $imap->is_parent($folder);
if ( defined($parenthood) ) {
    if ($parenthood) {
        print "$folder has children.\n";
    }
    else {
        print "$folder is permitted children, but has none.\n";
    }
}
else {
    print "$folder is not permitted to have children.\n";
}

The three-state situation is lowkey a lot but it's fine, just check defined() first like the example does and you're golden. ⭐


list 📋

Example:

my @raw_output = $imap->list(@args)
  or die "Could not list: $@\n";

The list method implements the IMAP LIST client command. Arguments are passed to the IMAP server as received, separated from each other by spaces. If no arguments are supplied then the default list command tag LIST "" '*' is issued.

The list method returns an array (or an array reference, if called in a scalar context). The array is the unadulterated output of the LIST command. (If you want your output adulterated then see the "folders" method, above.)

An "undef" value is returned in case of errors. Be sure to check for it. 🚨 Not me warning you twice — check for it.

listrights 📜

Example:

$imap->listrights( $folder, $user )
  or die "Could not listrights: $@\n";

The listrights method implements the IMAP LISTRIGHTS client command (RFC2086). It accepts two arguments: the foldername and a user id. It returns the rights the specified user has for the specified folder.

  • If called in a scalar context then the rights are returned a strings, with no punctuation or white space or any nonsense like that.
  • If called in array context then listrights returns an array in which each element is one right.

Context-sensitive, main character energy. 👑


login 🔑

Example:

$imap->login or die "Could not login: $@\n";

The login method implements the IMAP LOGIN client command to log into the server. It automatically calls "authenticate" if the Authmechanism parameter is set to anything except 'LOGIN' — otherwise a clear text LOGIN is attempted.

The User and Password parameters must be set before the login method can be invoked. On success, a Mail::IMAPClient object with the Status of Authenticated is returned. On failure, undef is returned and $@ is set. The methods "new", "connect", and "Socket" may automatically invoke login — see the documentation of each method for details.

If the "Compress" parameter is set, the "compress" method will automatically be called after successful authentication.

See also "proxyauth" and "Proxy" for additional information regarding ways of authenticating with a server via SASL and/or PROXYAUTH.


proxyauth 🎭

Example:

$imap->login( "admin", "password" );
$imap->proxyauth("someuser");

The proxyauth method implements the IMAP PROXYAUTH client command. The command is used by Sun/iPlanet/Netscape IMAP servers to allow an administrative user to masquerade as another user. Literally the disguise era. 🙈


logout 🚪

Example:

$imap->logout or die "Could not logout: $@\n";

The logout method implements the LOGOUT IMAP client command. This method causes the server to end the connection and the IMAPClient client enters the Unconnected state. This method does not, destroy the IMAPClient object, thus the "connect" and "login" methods can be used to establish a new IMAP session. So like, it's not a breakup, it's just closing the tab. 💅

Note that RFC2683 section 3.1.2 (Severed connections) makes some recommendations on how IMAP clients should behave. It is up to the user of this module to decide on the preferred behavior and code accordingly.

Version note: documentation (from 2.x through 3.23) claimed that Mail::IMAPClient would attempt to log out of the server during DESTROY if the object is in the "Connected" state. This documentation was apparently incorrect from at least 2.2.2 and possibly earlier versions on up. 💀 So, yeah. That was a lie the docs told.


lsub 📬

Example:

$imap->lsub(@args) or die "Could not lsub: $@\n";

The lsub method implements the IMAP LSUB client command. Arguments are passed to the IMAP server as received, separated from each other by spaces. If no arguments are supplied then the default lsub command tag LSUB "" '*' is issued.

The lsub method returns an array (or an array reference, if called in a scalar context). The array is the unaltered output of the LSUB command. If you want an array of subscribed folders then see the "subscribed" method, below. 🎀


mark 🚩

Example:

$imap->mark(@msgs) or die "Could not mark: $@\n";

The mark method accepts a list of one or more messages sequence numbers, or a single reference to an array of one or more message sequence numbers, as its argument(s). It then sets the "\Flagged" flag for those message(s).

Of course, if the "Uid" parameter is set to a true value then those message sequence numbers had better be unique message id's. No cap, they better be. 👀

Note that specifying $imap->see(@msgs) is just a shortcut for specifying $imap->set_flag("Flagged",@msgs).


Massage 💆

Example:

$imap->search(HEADER => 'Message-id' => $imap->Massage($msg_id,1));
WARNING: This method may be deprecated in the future, consider using "Quote" instead of this method. ⚠️

The Massage method accepts a value as an argument and, optionally, a second value that, when true, indicates that the first argument is not the name of an existing folder.

WARNING: If the first argument has double quotes at the beginning and end of its value, those double quote will be stripped unless the second argument does not evaluate to true. 🚨 Read that one twice, fr fr.

It returns its argument as a correctly quoted string or a literal string.

Note that you should rarely use this on folder names, since methods that accept folder names as an argument will call Quote for you. So like, chill, it's handled. 🧚


message_count 🔢

Example:

…and the example wraps up like this:

  my $msgcount = $imap->message_count($folder);
  defined($msgcount) or die "message_count failed: $@\n";

The message_count method takes a folder name as its argument and hands you back the number of messages chilling in that folder. Under the hood it calls the status method (scroll up bestie, it's right there) and parses the results to pull out the message count. If you don't pass it an argument, it'll give you the number of messages in the folder you've currently got selected (assuming you actually used select or examine to select it and weren't out here trying something funky 🙈).

⚠️ Okay so real talk: RFC2683 has warnings about using the IMAP STATUS command (and therefore the status method, and therefore message_count) against the folder that's currently selected. Please, please actually think about this before you run message_count on your currently selected folder. You're probably better off using search or one of its variants (especially messages) and then just counting the results. That said… I regularly violate this rule on my own server and have suffered zero dire consequences 💅. Your mileage may vary, bestie.

🦋 message_string 🦋

Example:

  my $string = $imap->message_string($msgid)
    or die "message_string failed: $@\n";

message_string takes a message sequence number (or a message UID if Uid is true) as its argument and returns that message as a string. The value you get back contains the entire message in one single scalar variable — headers and all, no cap. Heads up though: using this method sets the message's \Seen flag as a side effect 😭 unless Peek is set to a true value.

🌸 message_to_file 🌸

Example:

  $imap->message_to_file( $file, @msgs )
    or die "message_to_file failed: $@\n";

message_to_file accepts a filename or a file handle, plus one or more message sequence numbers (or message UIDs if Uid is true), and plops the message string(s) — RFC822 headers included, always — into the file named in the first argument. If you passed a file handle instead, it prints them to that handle. Returns true on success and undef on failure.

If the first argument is a reference, it's assumed to be an open file handle and it will not be closed when the method finishes. If it's a file, it gets opened in append mode, written to, and then closed. Slay.

🫶 Note that using this method sets the message's \Seen flag as a side effect. But you can use the deny_seeing method to set it back, or set the Peek parameter to a true value to stop the \Seen flag from being set at all. Choose your fighter.

Ngl this method currently works by making some basic assumptions about how the server behaves — notably that the message text comes back as a literal string but that nothing else does. If you've got a better idea, I'd genuinely like to hear it 👀.

🎀 message_uid 🎀

Example:

  my $msg_uid = $imap->message_uid($msg_seq_no)
    or die "Could not get uid for $msg_seq_no: $@\n";

message_uid accepts a message sequence number (or a message UID if Uid is true) as its argument and returns the message's UID. And yes — if Uid is true, it'll use the IMAP UID FETCH UID client command to fetch and return the exact same argument you just supplied. That's an IMAP feature, so please don't come complaining to me about it 💀.

⭐ messages ⭐

Example:

  # Get a list of messages in the current folder:
  my @msgs = $imap->messages or warn "Could not list messages\n";
  # Get a reference to an array of messages in the current folder:
  my $msgs = $imap->messages or die "Get messages failed: $@\n";

Call messages in list context and it returns a list of all the messages in the currently selected folder. Call it in scalar context and it returns a reference to an array containing all the messages in that folder. It's literally the same as specifying $imap->search(ALL). Iconic.

An empty list is returned when there are no messages to be found. On failure undef is returned and LastError is set.

🧚 migrate 🧚

Example:

  $imap_src->migrate( $imap_dest, "ALL", $targetFolder )
    or die "Could not migrate: ", $imap_src->LastError;

migrate copies the indicated message(s) from the currently selected folder over to another Mail::IMAPClient object's session. It needs these arguments:

  1. a reference to the target Mail::IMAPClient object — not the calling object, which is the one connected to the source account;
  2. the message(s) to be copied, specified as either a) the message sequence number (or message UID if the UID parameter is true) of a single message, b) a reference to an array of message sequence numbers (or message UIDs if the UID parameter is true), or c) the special string "ALL", which is a shortcut for the results of "search"("ALL");
  3. the name of the destination folder on the target mailbox that's gonna receive the message(s). If you don't supply this argument, or it's undef, then the currently selected folder on the calling object gets used instead. The destination folder will be automatically created if it's necessary.

The target ($imap_dest) object must not be the same object as the source ($imap_src). Periodt.

Fair warning: this method does not attempt to minimise memory usage 😭. In the future it could be enhanced to (optionally) write message data to a temporary file so it doesn't have to store the entire message in memory.

To work around potential network timeouts on large messages, consider setting Reconnectretry to 1 on both $imap_src and $imap_dest — lowkey a lifesaver.

See also Supportedflags.

🔥 move 🔥

Example:

  my $newUid = $imap->move( $newFolder, $oldUid )
    or die "Could not move: $@\n";
  $imap->expunge;

move moves messages from the currently selected folder into the folder given as the first argument. If the Uid parameter is not true, then the rest of the arguments should be either:

  • a) a message sequence number,
  • b) a comma-separated list of message sequence numbers, or
  • c) a reference to an array of message sequence numbers.

If the Uid parameter is true, then the arguments should be:

  • a) a message UID,
  • b) a comma-separated list of message UIDs, or
  • c) a reference to an array of message UIDs.

If the target folder doesn't exist, it gets created. Very demure, very mindful.

If move succeeds it returns a true value. And here's the fun part: if the Mail::IMAPClient object is connected to a server with the UIDPLUS capability, that true value will be the comma-separated list of UIDs for the newly copied messages 🎉. The list comes back in the order the messages were moved, which should correspond to the order of the message UIDs you handed in.

If the move is not successful, move returns undef.

💀 Important: a move really just involves copying the message to the new folder and then setting the \Deleted flag. To actually delete the original message you'll need to run expunge (or close). Don't forget, or you'll have ghost messages.

🌈 namespace 🌈

Example:

  my $refs = $imap->namespace
    or die "namespace failed: $@\n";

namespace runs the NAMESPACE IMAP command (as defined in RFC 2342 — yes, we cite our sources). When called in list context it returns a list of three references. Each reference looks like this:

  [
    [ $prefix_1, $separator_1 ],
    [ $prefix_2, $separator_2 ],
    [ $prefix_n, $separator_n ],
  ]

The first reference gives you a list of prefixes and separator characters for the available personal namespaces. The second one does the same for the available shared namespaces. The third one is all about the available public namespaces.

If any of those three namespaces isn't available on the current server, you get an undef in its place instead of a reference. So for example, if shared folders weren't supported but personal and public namespaces were both available (with one namespace each), the returned value might look something like this:

  [ [ "", "/" ] , undef, [ "#news", "." ] ];

If namespace is called in scalar context, it returns a reference to that whole list of three references, giving you one single structure that pretty-prints like this:

  $VAR1 = [
      [
          [ $user_prefix_1, $user_separator_1 ],
          [ $user_prefix_2, $user_separator_2 ],
          [ $user_prefix_n, $user_separator_n ],
      ],                    # or undef
      [
          [ $shared_prefix_1, $shared_separator_1 ],
          [ $shared_prefix_2, $shared_separator_2 ],
          [ $shared_prefix_n, $shared_separator_n ],
      ],                    # or undef
      [
          [ $public_prefix_1, $public_separator_1 ],
          [ $public_prefix_2, $public_separator_2 ],
          [ $public_prefix_n, $public_separator_n ],
      ],                    # or undef
  ];

🍓 on 🍓

Example:

  my @msgs = $imap->on($Rfc3501_date)
    or warn "Could not find messages sent on $Rfc3501_date: $@\n";

on works exactly like the since method down below, except it returns a list of messages whose internal system dates are the same as the date you passed in as the argument. Same date, bestie ✨.

💜 parse_headers 💜

Example:

  my $hashref = $imap->parse_headers( $msg || \@msgs, "Date", "Subject" )
    or die "Could not parse_headers: $@\n";

parse_headers takes a message sequence number and a list of header fields as its arguments. It returns a hash reference where the keys are the header field names (colon removed, obviously) and the values are references to arrays of values. On failure undef is returned and LastError is set.

A picture would look something like this:

  $hashref = $imap->parse_headers( 1, "Date", "Received", "Subject", "To");
  $hashref = {
      "Date"     => [ "Thu, 09 Sep 1999 09:49:04 -0400" ]  ,
      "Received" => [ q/
        from mailhub ([111.11.111.111]) by mailhost.bigco.com
        (Netscape Messaging Server 3.6)  with ESMTP id AAA527D for
        <bigshot@bigco.com>; Fri, 18 Jun 1999 16:29:07 +0000
        /, q/
        from directory-daemon by mailhub.bigco.com (PMDF V5.2-31 #38473)
        id <0FDJ0010174HF7@mailhub.bigco.com> for bigshot@bigco.com
        (ORCPT rfc822;big.shot@bigco.com); Fri, 18 Jun 1999 16:29:05 +0000 (GMT)
        /, q/
        from someplace ([999.9.99.99]) by smtp-relay.bigco.com (PMDF V5.2-31 #38473)
        with ESMTP id <0FDJ0000P74H0W@smtp-relay.bigco.com> for big.shot@bigco.com; Fri,
        18 Jun 1999 16:29:05 +0000 (GMT)
        /] ,
      "Subject" => [ qw/ Help! I've fallen and I can't get up!/ ] ,
      "To"      => [ "Big Shot <big.shot@bigco.com> ] ,
  };

The text in the example for the "Received" array got formatted all pretty so it's actually readable 💅 — the real values that come back are just strings of words separated by spaces, with the newlines and carriage returns stripped off. Honestly the Received header is probably the number one reason parse_headers hands you a hash of lists instead of a hash of plain values. Like, it's not her fault, it's just how that header is.

If the second argument to parse_headers is 'ALL', or if you just... don't specify one at all, then every available header is included in the returned hash of lists. No gatekeeping ✨

And if a hash of lists is giving you emotional damage 😭 you can always call the "fetch" method yourself with the right parameters and parse the data however you want, bestie — your data, your rules. Also, for headers whose contents are already reflected in the envelope, you can use "get_envelope" as an alternative to "parse_headers".

If the "Uid" parameter is true, then the first argument gets treated as a message UID 👑. And if the first argument is a reference to an array of message sequence numbers (or UID's, when "Uid" is true), then parse_headers runs against each message in the array. In that case the return value is a hash where the key is the message sequence number (or UID) and the value is a reference to a hash, exactly like described above.

An example of using parse_headers to print the date and subject of every message in your demo folder could look like this:

  use Mail::IMAPClient;
  my $imap = Mail::IMAPClient->new(
      Server => $imaphost, User => $login, Password => $pass, Uid => 1
  );

  $imap->select("demo");

  my $msgs = $imap->search("ALL");
  for my $h (

   # get the Subject and Date from every message in folder "demo" the
   # first arg is a reference to an array listing all messages in the
   # folder (which is what gets returned by the $imap->search("ALL")
   # method when called in scalar context) and the remaining arguments
   # are the fields to parse out The key is the message number, which
   # in this case we don't care about:

    values %{ $imap->parse_headers( $msgs , "Subject", "Date") } )
  {
      # $h is the value of each element in the hash ref returned
      # from parse_headers, and $h is also a reference to a hash.
      # We'll only print the first occurrence of each field because
      # we don't expect more than one Date: or Subject: line per
      # message.
      print map { "$_:\t$h->{$_}[0]\n"} keys %$h;
  }

🌸 recent

Example:

  my @recent = $imap->recent or warn "No recent msgs: $@\n";

The recent method performs an IMAP SEARCH RECENT search against the selected folder and returns an array of sequence numbers (or UID's, if the "Uid" parameter is true) of the messages that are recent. Fresh mail energy 🌱

🦋 recent_count

Example:

  my $count = 0;
  defined($count = $imap->recent_count($folder))
    or die "recent_count failed: $@\n";

The recent_count method takes a folder name as its argument. It returns the number of recent messages in that folder (as returned by the IMAP client command STATUS folder RECENT), or "undef" if something went wrong. Also, credit where credit is due — the recent_count method was contributed by Rob Deker (deker@ikimbo.com) 🫶

💜 noop

Example:

  $imap->noop or die "noop failed: $@\n";

The noop method performs an IMAP NOOP command. Per RFC3501 this command does literally nothing and always succeeds — like, the most low-effort icon in the whole protocol 💀. BUT. If a connection times out or other errors happen while you're communicating with the server, this method can still fail. You can use this command as a periodic poll to check for (untagged) status updates from the server — new messages, etc. — and also to reset any inactivity/auto-logout timers the server might be keeping. It's giving "just checking in" text vibes 😌

🌈 reconnect

Example:

  $imap->noop or $imap->reconnect or die "noop failed: $@\n";

Attempts to reconnect if the IMAP connection... unless $imap is already in the IsConnected state, in which case, nothing to do bestie. This method calls "connect" and optionally "select" if a Folder was previously selected. On success it returns the (same) $imap object. On failure <undef> is returned and "LastError" is set.

Version note: method added in Mail::IMAPClient 3.17 🎀

⭐ rename

Example:

  $imap->rename( $oldname, $nedwname )
    or die "rename failed: $@\n";

The rename method accepts two arguments: the name of an existing folder, and a new name for that folder. The existing folder gets renamed to the new name using the RENAME IMAP client command. rename returns a true value if it worked, or "undef" if it didn't. (And yes, the example says $nedwname — that's how it's written here, no cap, we're keeping it exactly as-is 🙈)

🎀 restore_message

Example:

  $imap->restore_message(@msgs) or die "restore_message failed: $@\n";

The restore_message method is the undo button for a previous "delete_message" operation — but not if there's been an intervening "expunge" or "close", so like, don't count on it after that 💀. The IMAPClient object must be in "Selected" status to use the restore_message method.

The restore_message method accepts a list of arguments. If the "Uid" parameter is not set to a true value, then each item in the list should be either:

  • a message sequence number,
  • a comma-separated list of message sequence numbers,
  • a reference to an array of message sequence numbers, or

If the "Uid" parameter is set to a true value, then each item in the list should be either:

  • a message UID,
  • a comma-separated list of UID's, or
  • a reference to an array of message UID's.

The messages identified by the sequence numbers or UID's get their \Deleted flags cleared, effectively "undeleting" them ✨ restore_message returns the number of messages it was able to restore.

Note that restore_messages is similar to calling ""unset_flag"("\Deleted",@msgs)", except that restore_messages returns a (slightly) more meaningful value. Also it's easier to type. Honestly iconic reasoning 💅

🔥 run

Example:

  $imap->run(@args) or die "run failed: $@\n";

The run method exists to make those uncommon things possible... however, we would like you to contribute the knowledge of missing features with us 🫶

The run method excepts one or two arguments. The first argument is a string containing an IMAP client command, including a tag and all required arguments. The optional second argument is a string to look for that will indicate success. (The default is "/OK.*/"). The run method returns an array (or an arrayref in scalar context) of output lines from the command, which you are free to parse as you see fit.

The run method does not do any syntax checking, other than rudimentary checking for a tag. So like, be careful, she trusts you 👀

When run processes the command, it increments the transaction count and saves the command and responses in the History buffer the same way other commands do. However, it also creates a special entry in the History buffer named after the tag supplied in the string passed as the first argument. If you supply a numeric value as the tag, then you may risk overwriting a previous transaction's entry in the History buffer. ⚠️

If you want the control of run but you don't want to worry about tags, then see "tag_and_run", below.

Example:

  my $msgs1 = $imap->search(@args);
  if ($msgs1) {
      print "search matches: @$msgs1";
  }
  else {
      warn "Error in search: $@\n" if $@;
  }

  # or  note: be sure to quote string properly
  my $msgs2 = $imap->search( \( $imap->Quote($msgid), "FROM", q{"me"} ) )
    or warn "search failed: $@\n";

  # or  note: be sure to quote string properly
  my $msgs3 = $imap->search('TEXT "string not in mailbox"')
    or warn "search failed: $@\n";

The search method implements the SEARCH IMAP client command. Any arguments you supply to search get prefixed with a space and then appended to the SEARCH IMAP client command. The SEARCH IMAP client command allows for many options and arguments — see RFC3501 for the details, iykyk 📖

As of version 3.17, search tries to "DWIM" by automatically quoting things that likely need quotes when the words don't match any of the following:

   ALL ANSWERED BCC BEFORE BODY CC DELETED DRAFT FLAGGED
   FROM HEADER KEYWORD LARGER NEW NOT OLD ON OR RECENT
   SEEN SENTBEFORE SENTON SENTSINCE SINCE SMALLER SUBJECT
   TEXT TO UID UNANSWERED UNDELETED UNDRAFT UNFLAGGED
   UNKEYWORD UNSEEN

The following options exist to avoid the automatic quoting (note: the caller is responsible for verifying the data sent in these cases is properly escaped/quoted):

  • specify a single string/argument in the call to search.
  • specify args as scalar references (SCALAR) and the values of those SCALAR refs will be passed along as-is.

The search method returns an array containing the sequence numbers of messages that passed the SEARCH IMAP client command's search criteria. If the "Uid" parameter is true, then the array will contain message UID's. If search is called in scalar context, then a pointer to the array gets passed instead of the array itself. If no messages meet the criteria, then search returns an empty list (in list context) or "undef" (in scalar context).

Since a valid, successful search can legitimately return zero matches, you may wish to distinguish between a search that correctly returns zero hits and a search that failed for some other reason (i.e. invalid search parameters) 😬. Therefore, the $@ variable is always cleared before the SEARCH command is issued to the server, and will thus remain empty unless the server gives a BAD or NO response to the SEARCH command. Clever, right? Obsessed.

🌸 see

Example:

  $imap->see(@msgs) or die "see failed: $@\n";

The see method accepts a list of one or more message sequence numbers, or a single reference to an array of one or more message sequence numbers, as its argument(s). It then sets the \Seen flag for those message(s). Of course, if the "Uid" parameter is set to a true value, then those message sequence numbers had better be unique message id's — but then you already knew that, didn't you? 😏

Note that specifying "$imap->see(@msgs)" is just a shortcut for specifying "$imap->"set_flag"("Seen",@msgs)".

🦋 seen

Example:

  my @seenMsgs = $imap->seen or warn "No seen msgs: $@\n";

The seen method performs an IMAP SEARCH SEEN search against the selected folder and returns an array of sequence numbers of messages that have already been seen (ie their \Seen flag is set). If the "Uid" parameter is true, then an array of message UID's gets returned instead. If called in scalar context, then a reference to the array (rather than the array itself) will be returned.

💖 select

Example:

  $imap->select($folder) or die "select failed: $@\n";

The select method selects a folder and changes the object's state to Selected. It accepts one argument, which is the name of the folder to select. Main character folder energy 👑

🎀 selectable

Example:

         foreach my $f ( grep( $imap->selectable($_), $imap->folders ) ) {
             $imap->select($f);
         }

okay so selectable takes exactly one value — a folder name — and returns true if that folder is selectable, or false if it is not selectable. That’s the whole vibe check, bestie. 💅

💌 sentbefore

Example, right here:

  my @msgs = $imap->sentbefore($Rfc3501_date)
    or warn "Could not find any msgs sent before $Rfc3501_date: $@\n";

The sentbefore method works just like sentsince, below, except it searches for messages that were sent before the date supplied as an argument to the method. no cap.

🎀 senton

Example time:

  my @msgs = $imap->senton($Rfc3501_date)
    or warn "Could not find any messages sent on $Rfc3501_date: $@\n";

The senton method works just like sentsince, below, except it searches for messages that were sent on the exact date supplied as an argument to the method. periodt.

🦋 sentsince

Example:

  my @msgs = $imap->sentsince($Rfc3501_date)
    or warn "Could not find any messages sent since $Rfc3501_date: $@\n";

The sentsince method accepts one argument, a date in either epoch time format (seconds since 1/1/1970, or as output by time and as accepted by localtime) or in the date_text format as defined in RFC3501 (dd-Mon-yyyy, where Mon is the English-language three-letter abbreviation for the month).

It searches for items in the currently selected folder for messages sent since the day whose date is provided as the argument. It uses the RFC822 Date: header to determine the sentsince date. (Actually, it’s the server that uses the Date: header; this documentation just assumes that the date is coming from the Date: header because that’s what RFC3501 dictates.)

In the case of arguments supplied as a number of seconds, the returned result list will include items sent on or after that day, regardless of whether they arrived before the specified time on that day. The IMAP protocol does not support searches at a granularity finer than a day, so neither do I. On the other hand, the only thing I check for in a date_text argument is that it matches the pattern /\d\d-\D\D\D-\d\d\d\d/ (notice the lack of anchors), so if your server lets you add something extra to a date_text string then so will Mail::IMAPClient.

If you’d like, you can use the Rfc3501_date method to convert from epoch time (as returned by time) into an RFC3501 date specification. slay. ✨

🌸 separator

Example:

  my $sepChar = $imap->separator(@args)
    or die "Could not get separator: $@\n";

The separator method returns the character used as a separator character in folder hierarchies. On UNIX-based servers, this is often but not necessarily a forward slash (/). It accepts one argument, the name of a folder whose hierarchy’s separator should be returned. If no folder name is supplied then the separator for the INBOX is returned, which probably is good enough.

If you want your programs to be portable from IMAP server brand X to IMAP server brand Y, then you should never use hard-coded separator characters to specify subfolders. (In fact, it’s even more complicated than that, since some servers don’t allow any subfolders at all, some only allow subfolders under the "INBOX" folder, and some forbid subfolders in the inbox but allow them "next" to the inbox. Furthermore, some server implementations do not allow folders to contain both subfolders and mail messages; other servers allow this.) 💀

🧚 set_flag

Example:

  $imap->set_flag( "Seen", @msgs )
    or die "Could not set flag: $@\n";

The set_flag method accepts the name of a flag as its first argument and a list of one or more message sequence numbers, or a single reference to an array of one or more message sequence numbers, as its next argument(s). It then sets the flag specified for those message(s). Of course, if the Uid parameter is set to a true value then those message sequence numbers had better be unique message id’s, just as you’d expect.

Note that when specifying the flag in question, the preceding backslash (\) is entirely optional. (For you, that is. Mail::IMAPClient still has to remember to stick it in there before passing the command to the server if the flag is one of the reserved flags specified in RFC3501. This is in fact so important that the method checks its argument and adds the backslash when necessary, which is why you don’t have to worry about it overly much.) 🫶

🌈 setacl

Example:

  $imap->setacl( $folder, $userid, $aclstring )
    or die "Could not set acl: $@\n";

The setacl method accepts three input arguments, a folder name, a user id (or authentication identifier, to use the terminology of RFC2086), and an access rights modification string. See RFC2086 for more information.

(This is somewhat experimental and its implementation may change.) 🚧

⭐ since

Example:

  my @msgs = $imap->since($date)
    or warn "Could not find any messages since $date: $@\n";

The since method accepts a date in either epoch format (seconds since 1/1/1970, or as output by "time" in perlfunc and as accepted by "localtime" in perlfunc) or in the date_text format as defined in RFC3501 (dd-Mon-yyyy, where Mon is the English-language three-letter abbreviation for the month). It searches for items in the currently selected folder for messages whose internal dates are on or after the day whose date is provided as the argument. It uses the internal system date for a message to determine if that message was sent since the given date.

In the case of arguments supplied as a number of seconds, the returned result list will include items whose internal date is on or after that day, regardless of whether they arrived before the specified time on that day.

If since is called in a list context then it will return a list of messages meeting the SEARCH SINCE criterion, or an empty list if no messages meet the criterion.

If since is called in a scalar context then it will return a reference to an array of messages meeting the SEARCH SINCE criterion, or undef if no messages meet the criterion.

Since since is a front-end to search, some of the same rules apply. For example, the $@ variable will always be cleared before the SEARCH command is issued to the server, and will thus remain empty unless the server gives a BAD or NO response to the SEARCH command. iykyk. 😭

🍓 size

Example:

  my $size = $imap->size($msgId)
    or die "Could not find size of message $msgId: $@\n";

The size method accepts one input argument, a sequence number (or message UID if the Uid parameter is true). It returns the size of the message in the currently selected folder with the supplied sequence number (or UID). The IMAPClient object must be in a Selected state in order to use this method. 👑

🔥 sort

Example:

  my @msgs = $imap->sort(@args);
  warn "Error in sort: $@\n" if $@;

The sort method is just like the search method, only different. It implements the SORT extension as described in https://tools.ietf.org/html/rfc5256. It would be wise to use the has_capability method to verify that the SORT capability is available on your server before trying to use the sort method. If you forget to check and you’re connecting to a server that doesn’t have the SORT capability then sort will return undef. LastError will then say you are "BAD". If your server doesn’t support the SORT capability then you’ll have to use search and then sort the results yourself.

The first argument to sort is a space-delimited list of sorting criteria. The Internet Draft that describes SORT requires that this list be wrapped in parentheses, even if there is only one sort criterion. If you forget the parentheses then the sort method will add them. But you have to forget both of them, or none. This isn’t CMS running under VM!

The second argument is a character set to use for sorting. Different character sets use different sorting orders, so this argument is important. Since all servers must support UTF-8 and US-ASCII if they support the SORT capability at all, you can use one of those if you don’t have some other preferred character set in mind.

The rest of the arguments are searching criteria, just as you would supply to the search method. These are all documented in RFC3501. If you just want all of the messages in the currently selected folder returned to you in sorted order, use ALL as your only search criterion.

The sort method returns an array containing sequence numbers of messages that passed the SORT IMAP client command’s search criteria. If the Uid parameter is true then the array will contain message UID’s. If sort is called in scalar context then a pointer to the array will be passed, instead of the array itself. The message sequence numbers or unique identifiers are ordered according to the sort criteria specified. The sort criteria are nested in the order specified; that is, items are sorted first by the first criterion, and within the first criterion they are sorted by the second criterion, and so on.

The sort method will clear $@ before attempting the SORT operation just as the search method does. 💅

🎀 starttls

Example:

  $imap->starttls() or die "starttls failed: $@\n";

The starttls method accepts no arguments. This method is used to upgrade an existing connection which is not authenticated to a TLS/SSL connection by using the IMAP STARTTLS command followed by using the start_SSL class method from IO::Socket::SSL to do the necessary TLS negotiation. The negotiation is done in a blocking fashion with a default Timeout of 30 seconds. The arguments used in the call to start_SSL can be controlled by setting the Mail::IMAPClient Starttls attribute to an ARRAY reference containing the desired arguments.

Version note: method added in Mail::IMAPClient 3.22 🌈

🫶 status

Example:

  my @rawdata = $imap->status( $folder, qw/(Messages)/ )
    or die "Error obtaining status: $@\n";

The status method accepts one argument, the name of a folder (or mailbox, to use RFC3501’s terminology), and returns an array containing the results of running the IMAP STATUS client command against that folder. If additional arguments are supplied then they are appended to the IMAP STATUS client command string, separated from the rest of the string and each other with spaces.

If status is not called in an array context then it returns a reference to an array rather than the array itself.

The status method should not be confused with the Status method (with an uppercase S), which returns information about the IMAPClient object. (See the section labeled "Status Methods", below). 🔍

💜 store

Example:

  $imap->store(@args) or die "Could not store: $@\n";
  • store takes a message sequence number or a comma-separated list of them as its first arg, then a message data item name, then a value for that item. Right now the data items are the word FLAGS followed by a space and a list of flags (in parens). You can modify that FLAGS word by prefixing it with either + or - (meaning "add these flags" / "remove these flags") and by suffixing it with .SILENT (which cuts down how much the server yells back at you — genuinely a lifesaver with big message sets). Bestie, normally you will not need to call store at all, because there are oodles of methods that will call store for you with the correct arguments. And those methods are friendlier and more flexible about how you hand them your arguments. Peep see, deny_seeing, delete_message and restore_message. Or mark, unmark, set_flag and unset_flag. 💅

subject

Example:

  my $subject = $imap->subject($msg);

The subject method takes one argument — a message sequence number (or a message UID, if the Uid parameter is true). You get back the text in the Subject header of that message, Subject: prefix not included. It's a short-cut for:

  my $subject = $imap->get_header($msg, "Subject");

subscribed

Example:

  my @subscribedFolders = $imap->subscribed
    or warn "Could not find subscribed folders: $@\n";

The subscribed method works like the folders method above, except the returned list (or array reference, if you call it in scalar context 🌸) contains only the subscribed folders.

Like folders, you can optionally hand the subscribed method a prefix argument. No cap.

tag_and_run

Example:

  my $output = $imap->tag_and_run(@args)
    or die "Could not tag_and_run: $@\n";

The tag_and_run method takes one or two arguments. First argument is a string holding an IMAP client command, no tag, but with all the required arguments already in there. The optional second argument is a string to look for that'll signal success (without pattern delimiters). Default is OK.*.

So tag_and_run takes your string (from that first argument), prefixes it with the next transaction number, and runs the command. It returns an array of output lines from the command, and you can parse those however you see fit. Using this instead of run (above) frees you from having to worry about handling tags — and from worrying about the side effects of naming your own tags. Iconic behaviour, honestly. ✨

uidexpunge

Example:

  $imap->uidexpunge(@uids) or die "Could not uidexpunge: $@\n";

The uidexpunge method implements the UID EXPUNGE IMAP client command (that's the RFC4315 UIDPLUS extension, iykyk) to permanently remove all messages that have the \Deleted flag set and have a UID that's included in the list of UIDs. Like, gone gone. 😭

uidexpunge returns an array or arrayref (scalar context) of output lines returned from the UID EXPUNGE command.

uidexpunge returns undef on failure.

If the server doesn't support the UIDPLUS extension, this method returns undef.

uidnext

Example:

  my $nextUid = $imap->uidnext($folder) or die "uidnext failed: $@\n";

The uidnext method takes one argument — the name of a folder — and returns the numeric string that is the next available message UID for that folder. 🎀

thread

Example:

  my $thread = $imap->thread( $algorithm, $charset, @search_args );

The thread method takes zero to three arguments. First one is the threading algorithm to use, generally either ORDEREDSUBJECT or REFERENCES. Second is the character set to use, and third is the set of search arguments to use.

If you don't supply the algorithm, it defaults to REFERENCES if that's available, or ORDEREDSUBJECT if that's available. If neither of these is available then the thread method returns undef. 🫠

If you don't specify the character set it defaults to UTF-8.

If you don't specify the search arguments, the default is ALL.

If thread is called on an object connected to a server that doesn't support the THREADS extension, then the thread method will return undef.

The threads method will issue the THREAD command as defined in https://tools.ietf.org/html/rfc5256. It returns an array of threads. Each element in the array is either a message id or a reference to another array of (sub)threads.

If the Uid parameter is set to a true value then the message id's returned in the thread structure will be message UID's. Otherwise they'll be message sequence numbers.

uidvalidity

Example:

  my $validity = $imap->uidvalidity($folder)
    or die "uidvalidity failed: $@\n";

The uidvalidity method takes one argument — the name of a folder — and returns the numeric string that is the unique identifier validity value for the folder. 💖

unmark

Example:

  $imap->unmark(@msgs) or die "Could not unmark: $@\n";

The unmark method takes a list of one or more message sequence numbers, or a single reference to an array of one or more message sequence numbers, as its argument(s). Then it unsets the \Flagged flag for those message(s). Obviously if the Uid parameter is set to a true value then those message sequence numbers should really be unique message id's.

Note that writing $imap->unmark(@msgs) is just a shortcut for $imap->unset_flag("Flagged",@msgs). Two for one, slay. 💅

Also note that \Flagged is just one of many possible flags. It's a lil confusing, but you're gonna have to get used to the idea that among the reserved flags specified in RFC3501 there's one named \Flagged. It has no specific meaning — it means whatever the mailbox owner (or delegate) wants it to mean when it's turned on.

unseen

Example:

  my @unread = $imap->unseen or warn "Could not find unseen msgs: $@\n";

The unseen method performs an IMAP SEARCH UNSEEN search against the selected folder and returns an array of sequence numbers of messages that haven't been seen yet (ie their \Seen flag is not set). If the Uid parameter is true then you get an array of message UID's instead. And if you call it in scalar context then a pointer to the array (rather than the array itself) is what comes back. 🦋

unseen_count

Example:

  foreach my $f ($imap->folders) {
      print "The $f folder has ",
        $imap->unseen_count($f)||0, " unseen messages.\n";
  }

The unseen_count method takes the name of a folder as its argument and returns the number of unseen messages in that folder. If you don't pass a folder argument then it gives you the number of unseen messages in the currently selected Folder. 💀

unset_flag

Example:

  $imap->unset_flag( "\Seen", @msgs )
    or die "unset_flag failed: $@\n";

The unset_flag method takes the name of a flag as its first argument and a list of one or more messages sequence numbers, or a single reference to an array of one or more message sequence numbers, as its next argument(s). Then it unsets the flag you specified for those message(s). And yep — if the Uid parameter is set to a true value then those message sequence numbers had better be unique message id's, just like you'd expect. 🌟


🌈 Other IMAP Client Commands 🌈

Okay so story time: until release 2.99, when you called a method that didn't exist, it got automatically translated into an IMAP call with the same name via an AUTOLOAD hack. That "feature" got removed for various reasons: people made typos in the capitalization of method names and the program still seemed to work correctly. Plus it blocked further development of this module, because people didn't contribute their private extensions to the protocol implementation. So it's gone. Periodt. ⭐

copy($msg, $folder)

Copy a message from the currently selected folder into the folder whose name is in $folder.

subscribe($folder)

Subscribe to a folder.

CAUTION: Once again, remember to quote your quotes (or use the Quote method) if you want quotes to be part of the IMAP command string. 🙈

You can also use the default method to override the behavior of implemented IMAP methods by changing the case of the method name — preferably to all-uppercase so you don't conflict with the Class method and the accessor method namespace. For example, if you don't want the search method's behavior (which returns a list of message numbers) but would rather have an array of raw data returned from your search operation, you can run this snippet:

  my @raw = $imap->SEARCH("SUBJECT","Whatever...");

which is slightly more efficient than the equivalent:

  $imap->search("SUBJECT","Whatever...");
  my @raw = $imap->Results;

Of course you probably want the search results tucked nicely into a list for you anyway, in which case you might as well use the search method. 🎀


💖 Parameters 💖

There are several parameters that influence the behavior of an IMAPClient object. Each one is set by specifying a named value pair during new method invocation, like this:

  my $imap = Mail::IMAPClient->new ( parameter  => "value",
      parameter2 => "value",
      ...
  );

Parameters can also be set after an object has been instantiated, by using the parameter's eponymous accessor method, like this:

  my $imap = Mail::IMAPClient->new;
     $imap->parameter( "value");
     $imap->parameter2("value");

The eponymous accessor methods can also be used without arguments to obtain the current value of the parameter, like this:

  my $imap = Mail::IMAPClient->new;
     $imap->parameter( "value");
     $imap->parameter2("value");

    ...    # A whole bunch of awesome Perl code, omitted for brevity

  my $forgot  = $imap->parameter;
  my $forgot2 = $imap->parameter2;

Note that in these examples I'm using parameter and parameter2 as generic parameter names. The IMAPClient object doesn't actually have parameters named parameter and parameter2. On the contrary, the available parameters are: 🌸

Authmechanism

Example:

  $imap->Authmechanism("CRAM-MD5");
  # or
  my $authmech = $imap->Authmechanism();

If specified, the Authmechanism causes the specified authentication mechanism to be used whenever Mail::IMAPClient would otherwise invoke login. If the value you specified for the Authmechanism parameter is not a valid authentication mechanism for your server then you will never ever be able to log in again for the rest of your Perl script, probably. 😭 So maybe check first, like this:

  my $authmech = "CRAM-MD5";
  $imap->has_capability($authmech) and $imap->Authmechanism($authmech);

Of course if you know your server supports your favorite authentication mechanism then you know, so you can then include your Authmechanism with your new call, as in:

my $imap = Mail::IMAPClient->new(
    User    => $user,
    Passord => $passord,
    Server  => $server,
    Authmechanism  => $authmech,
    %etc
);

So like, if you pass Authmechanism but you don't pass Authcallback? Bestie, you better be repping one of the auth mechanisms Mail::IMAPClient supports right out of the box (think CRAM-MD5 and friends) 😌

Authcallback

Example, enjoy:

$imap->Authcallback( \&callback );

This is literally you setting a default callback for the default auth mechanism (peep "Authmechanism" above 👆). Together those two methods replace the automatic calls to login with automatic calls that look kinda like this:

$imap->authenticate($imap->Authmechanism,$imap->Authcallback);

And again, for the people in the back: if Authmechanism is supplied but Authcallback is not, then you had better be supporting one of the authentication mechanisms that Mail::IMAPClient supports "out of the box" (such as CRAM-MD5) 💅

Authuser

Authuser is the parameter the DIGEST-MD5 Authmechanism uses.

Normally when you authenticate, the username from the User parameter is what gets used. But with DIGEST-MD5 you can use Authuser to specify a different username for the login 🔀

Which is lowkey useful for marking messages as seen for the Authuser if you don't know that user's password — because seen state is, like, very often a per-user thing. iykyk 🫶

Buffer

Example:

$Buffer = $imap->Buffer();
# or:
$imap->Buffer($new_value);

Buffer sets the size of a block of I/O. It gets ignored unless Fast_io (below) is set to a true value (that's the default, btw) or unless you're using the migrate method. Its value should be the number of bytes to attempt to read in one I/O operation, and the default value is 4096 ✨

Now, when you're using migrate, you can often get dramatic throughput glow-ups by bumping this number upward. But — and hear me out — that also costs you memory, so if you set it too high you risk losing all the benefits of migrate's chunking algorithm. Your program can then terminate with an "out of memory" error and you'll have no one but yourself to blame 😭💀

Also note, as hinted above, Buffer affects the behavior of the migrate method regardless of whether you have Fast_io turned on. Believe me, you do not want to go around migrating tons of mail without using buffered I/O, no cap 🙅‍♀️

Clear

Example:

$Clear = $imap->Clear();
# or:
$imap->Clear($integer);

Okay so the name of this parameter is, for historical reasons, kind of a lie 🙈 It should be named Wrap, because it specifies how many transactions are stored in the wrapped history buffer. But it didn't always work that way — the buffer used to actually get cleared. The name stuck around anyway, in the interests of backwards compatibility.

Clear specifies that the object's history buffer should be wrapped after every n transactions, where n is the value you gave the Clear parameter. Calling the eponymous Clear method with no argument returns the current value of the Clear parameter but will not cause the history buffer to wrap.

Setting Clear to 0 turns off automatic history buffer wrapping, and setting it to 1 turns off the history buffer facility entirely (except for the last transaction, which literally cannot be disabled without breaking the IMAPClient module). Setting Clear to 0 will not cause an immediate clearing of the history buffer; setting it to 1 (or any other number) will (except, of course, for that inevitable last transaction) 💫

The default Clear value is set to five (5) in order to conserve memory 🌸

Compress

If you set this, Mail::IMAPClient attempts to enable use of the RFC4978 COMPRESS DEFLATE extension. It requires that the server supports this CAPABILITY. You can set this attribute to a true value to enable it, or to an ARRAYREF to control the arguments used in the call to Compress::Zlib::deflateInit() 🗜️

Mail::IMAPClient will automatically use Compress::Zlib to deflate/inflate the data to/from the server. This attribute is used in the login method.

See also compress and capability.

Version note: attribute added in Mail::IMAPClient 3.30 ⭐

Debug

Example:

$Debug = $imap->Debug();
# or:
$imap->Debug($true_or_false);

Sets the debugging flag to either a true or false value. You can supply it with the new method call or separately by calling the Debug object method. Using this parameter is strongly recommended when debugging scripts and required when reporting bugs 🐛💖

Debug_fh

Example:

$Debug_fh = $imap->Debug_fh();
# or:
$imap->Debug_fh($fileHandle);

Specifies the file handle that debugging info should be printed to. It can be either a file handle object reference or a file handle glob. Default is to print debugging info to STDERR.

For example, you can do:

use Mail::IMAPClient;
use IO::File;
# set $user, $pass, and $server here
my $dh = IO::File->new(">debugging.output")
  or die "Can't open debugging.output: $!\n";
my $imap = Mail::IMAPClient->new(
    User=>$user, Password=>$pass, Server=>$server, Debug=>1, Debug_fh => $dh
);

which is the same as:

use Mail::IMAPClient;
use IO::File;
# set $user, $pass, and $server here
my $imap = Mail::IMAPClient->new(
    User     => $user,
    Password => $pass,
    Server   => $server,
    Debug    => "yes, please",
    Debug_fh => IO::File->new(">debugging.output")
      || die "Can't open debugging.output: $!\n"
);

You can also do:

use Mail::IMAPClient;
# set $user, $pass, and $server here
open(DBG,">debugging.output")
  or die "Can't open debugging.output: $!\n";
my $imap = Mail::IMAPClient->new(
  User=>$user, Password=>$pass, Server=>$server, Debug=> 1, Debug_fh => *DBG
);

Specifying this parameter isn't very useful unless Debug is set to a true value 👀

Domain

Domain is the parameter used by the NTLM Authmechanism. The domain is an optional parameter for NTLM authentication 🏰

EnableServerResponseInLiteral

Removed in 2.99_01 (now autodetect) — she's gone, bestie, don't come looking 💀

Fast_io

Example:

$Fast_io = $imap->Fast_io();
# or:
$imap->Fast_io($true_or_false);

Fast_io controls whether or not the Mail::IMAPClient object will attempt to use non-blocking I/O on the IMAP socket. It's turned on by default (unless the caller provides the socket to be used) ⚡

See also Buffer.

Folder

Example:

$Folder = $imap->Folder();
# or:
$imap->Folder($new_value);

Folder returns the name of the currently-selected folder (in case you forgot 😅). It can also set the name of the currently selected folder — which is completely unnecessary if you used the select method (or select's read-only equivalent, the examine method) to select it.

Note that setting Folder does not automatically select a new folder; you use the select or examine object methods for that. Generally Folder should only be queried (by using the no-argument form of the Folder method). You'll only need to set Folder if you use some mysterious technique of your own for selecting a folder, which you probably won't do 🦋

Ignoresizeerrors

Certain (caching) servers, like Exchange 2007, often report the wrong message size. Instead of chopping the message into a size that fits the specified size, the reported size will just be simply ignored when this parameter is set to 1 🎀

Keepalive

Some firewalls and network gear like to timeout connections prematurely if the connection sits idle 😴 The Keepalive parameter, when set to a true value, affects the behavior of new and Socket by enabling SO_KEEPALIVE on the socket.

Version note: attribute added in Mail::IMAPClient 3.17

Maxcommandlength

Maxcommandlength is used by fetch() to limit the length of commands sent to a server. Default is 1000 chars, following the recommendation of RFC2683 section 3.2.1.5 📏

Note: this attribute should also be used for several other methods but this has not yet been implemented — please feel free to file bugs for methods where you run into problems with this.

This attribute should remove the need for utilities like imapsync to create their own split() functions and instead allows Mail::IMAPClient to DWIM ✨

In practice, this parameter has proven useful for overcoming a limit of 8000 octets for UW-IMAPD and 16384 octets for Courier/Cyrus IMAP servers.

Version note: attribute added in Mail::IMAPClient 3.17

Maxtemperrors

Example:

$Maxtemperrors = $imap->Maxtemperrors();
# or:
$imap->Maxtemperrors($number);

Maxtemperrors specifies the number of times a read or write operation is allowed to fail on a "Resource Temporarily Available" (e.g. EAGAIN) error. The default setting is undef, which means there is no limit 🔁

Setting this parameter to the string "unlimited" (instead of undef) to ignore "Resource Temporarily Unavailable" errors is deprecated 🚫

Note: This setting should be used with caution and may be removed in a future release. Setting this can cause methods to return to the caller before data is received (and then handled) properly, thereby possibly leaving the module in a bad state. In the future, this behavior may be changed in an attempt to avoid this situation. 😬

Password

Example:

$Password = $imap->Password();
# or:
$imap->Password($new_value);

Specifies the password to use when logging into the IMAP service on the host in the Server parameter as the user specified in the User parameter. Can be supplied with the new method call or separately by calling the Password object method 🔑

If Server, User, and Password are all provided to the new method, then the newly instantiated object will be connected to the host specified in Server (at either the port in Port or the default port 143) and then logged on as the user specified in the User parameter (using the password provided in Password). See the discussion of the new method, below 👇

Peek

Example:

$Peek = $imap->Peek();
# or:
$imap->Peek($true_or_false);

Setting Peek to a true value will prevent the body_string, message_string and message_to_file methods from automatically setting the \Seen flag 👀 Setting Peek to 0 (zero) will force body_string, message_string, message_to_file, and parse_headers to always set the \Seen flag 🙈

So like, the default is: seen flag gets set whenever you fetch the body of a message, but not when you're just grabbing the headers. And if you pass undef to the eponymous Peek method? That resets the Peek parameter right back to its pristine, default state. Clean slate energy. ✨


💌 Port

Example:

$Port = $imap->Port();
# or:
$imap->Port($new_value);

Tells you which port the IMAP server is chillin' on. If nobody hands it a value, it gets a default during the connect call — 993 when "Ssl" is true, or 143 otherwise. You can pass it in through the new method call, or set it separately with the Port object method. Your choice, bestie. 🎀

✍️ Prewritemethod

Prewritemethod should hold a reference to a subroutine that does "special things" to your data before it gets sent to the IMAP server — encryption, signing, that kind of glamorous stuff.

Here's the timing: this method gets called immediately prior to sending an IMAP client command to the server. Argument one is a reference to the Mail::IMAPClient object, and argument two is a string containing the command that's about to head server-ward. Your Prewritemethod should return a string that's been signed, encrypted, or whatever else you're doing — and that returned string is the thing that actually gets sent. 💅

Heads up though: your Prewritemethod is probably gonna need more context than that to do its job. The recommendation is to tuck all your other pertinent info into a hash and stash a reference to that hash somewhere your method can reach it — possibly right in the Mail::IMAPClient object itself. Cozy.

Also important: this method should not actually send anything over the socket connection to the server. It merely converts data prior to sending. No sneaky side-quests. 🙈

See also "Readmethod".

🔍 Ranges

Example:

$imap->Ranges(1);
# or:
my $search = $imap->search(@search_args);
if ( $imap->Ranges) { # $search is a MessageSet object
    print "This is my condensed search result: $search\n";
    print "This is every message in the search result: ",
      join(",",@$search),"\n;
}

Set this to a true value and the search method will hand you back a Mail::IMAPClient::MessageSet object when called in scalar context — instead of the array reference that fetch normally returns in scalar context. Set it to zero or leave it undefined, and search keeps returning an array reference in scalar context, business as usual.

And no cap: this parameter has no affect on the search method when search is called in a list context. Like, none at all. 🦋

🔌 RawSocket

Example:

$socket = $imap->RawSocket;
# or:
$imap->RawSocket($socketh);

The RawSocket method is your hookup for getting the socket handle of the current connection — say, so you can do I/O on the connection that Mail::IMAPClient doesn't otherwise support. Or you can use it to replace the current socket with a new handle (for instance an SSL handle, see IO::Socket::SSL, but be sure to see the "Socket" method as well). 👑

If you supply a socket handle yourself, either by doing something like:

$imap=Mail::IMAPClient->new(RawSocket => $sock, User => ... );

or by doing something like:

$imap = Mail::IMAPClient->new(User => $user,
            Password => $pass, Server => $host);
# blah blah blah
$imap->RawSocket($ssl);

then it's all on you to establish the connection AND to authenticate — whether via the "login" method, the fancier "authenticate", or, since you clearly know so much anyway, by just doing raw I/O against the socket until you're logged in. And if you go down any of those roads, you should also set the "State" parameter yourself to reflect the current state of the object (i.e. Connected, Authenticated, etc). 😭

Real talk: no operation will be attempted on the socket when this method is called. In particular, after the TCP connection towards the IMAP server is established, the protocol mandates the server to send an initial greeting message — and you'll have to explicitly cope with that message before doing any other operation, e.g. trying to call "login". Caveat emptor. 💀

For a more DWIM approach to setting the socket, see "Socket".

📖 Readmethod

Example:

$imap->Readmethod(   # IMAP, HANDLE, BUFFER, LENGTH, OFFSET
    sub {
        my ( $self, $handle, $buffer, $count, $offset ) = @_;
        my $rc = sysread( $handle, $$buffer, $count, $offset );
        # do something useful here...
    }
);

Readmethod should contain a reference to a subroutine that will replace sysread. Here's the whole arg lineup, bestie:

  • First: the used Mail::IMAPClient object.
  • Second: a reference to a socket.
  • Third: a reference to a scalar variable into which data is read (BUFFER). The data you place here should be "finished data" — so if you're decrypting or removing signatures, be sure you do that before you place data into this buffer. 🌸
  • Fourth: the number of bytes requested to be read; the LENGTH of the request.
  • Lastly: the OFFSET into the BUFFER where the data should be read. If not supplied it should default to zero.

Note that this method completely replaces reads from the connection to the server — so if you define one of these, your subroutine has to actually do the read. It's for things like this that we have the "Socket" parameter and eponymous accessor method. 🫶

Your Readmethod will probably need to know more than this to do whatever it does. Same deal as before: it's recommended that you tuck all other pertinent information into a hash, and store a reference to this hash somewhere where your method can get to it, possibly in the Mail::IMAPClient object itself.

See also "Prewritemethod".

📚 Readmoremethod

Readmoremethod should contain a reference to a subroutine that will replace/enhance the behavior of the internal _read_more() method. Args go like this: first the used Mail::IMAPClient object. Second, a reference to a socket. Third, a timeout value which is used as the timeout value for CORE::select() by default. Depending upon changes/features introduced by Readmethod, changes may be required here. 🔥

Version note: attribute added in Mail::IMAPClient 3.30

🔁 Reconnectretry

If an IMAP connection sits idle too long, the connection may get closed by the server or firewall, etc. Rude, honestly. The Reconnectretry parameter, when given a positive integer value, will cause Mail::IMAPClient to retrying IMAP commands up to X times when an EPIPE or ECONNRESET error occurs. This is disabled (0) by default.

See also "Keepalive"

Version note: attribute added in Mail::IMAPClient 3.17

🖥️ Server

Example:

$Server = $imap->Server();
# or:
$imap->Server($hostname);

Specifies the hostname or IP address of the host running the IMAP server. If you provide it as part of the "new" method call, then the new IMAP object will automatically be connected at the time of instantiation. (See the "new" method, below.) Can be supplied with the "new" method call or separately by calling the Server object method. Either way works, we're not gonna gatekeep. ✨

🕵️ Showcredentials

Normally debugging output will mask the login credentials when the plain text login mechanism is used. Setting Showcredentials to a true value suppresses that, so you can actually see the string being passed back and forth during plain text login.

Only set this to true when you're debugging problems with the IMAP LOGIN command — and then turn it off right away when you're finished working on that problem. Like, immediately. This is not a "leave it on for the vibes" situation. 🚨

Example:

print "This is very risky!\n" if $imap->Showcredentials();
# or:
$imap->Showcredentials(0);    # mask credentials again

🧦 Socket

PLEASE NOTE The semantics of this method has changed as of version 2.99_04 of this module. If you need the old semantics use "RawSocket".

Example:

$Socket = $imap->Socket();
# or:
$imap->Socket($socket_fh);

The Socket method lets you obtain the socket handle of the current connection. This may be necessary to do I/O on the connection that isn't otherwise supported by Mail::IMAPClient) or to replace the current socket with a new handle (for instance an SSL handle, see IO::Socket::SSL). 🦋

If you supply a socket handle yourself, either by doing something like:

$imap = Mail::IMAPClient->new( Socket => $sock, User => ... );

or by doing something like:

$imap = Mail::IMAPClient->new(
  User => $user, Password => $pass, Server => $host
);
$imap->Socket($ssl);

then you are responsible for establishing the connection — i.e. make sure that $ssl in the example is a valid and connected socket. No pressure or anything. 😅

This method is primarily used to provide a drop-in replacement for IO::Socket::(INET|IP), used by "connect" by default. In fact, this method is called by "connect" itself after having established a suitable IO::Socket::(INET|IP) socket connection towards the target server. For this reason, this method also carries the normal operations associated with "connect", namely:

  • read the initial greeting message from the server;
  • call "login" if the conditions apply (see "connect" for details);
  • leave the Mail::IMAPClient object in a suitable state.

For these reasons, the following example will work "out of the box":

use IO::Socket::SSL;
my $imap = Mail::IMAPClient->new
 ( User     => 'your-username',
   Password => 'your-password',
   Socket   => IO::Socket::SSL->new
   (  Proto    => 'tcp',
      PeerAddr => 'some.imap.server',
      PeerPort => 993, # IMAP over SSL standard port
   ),
);

If you need more control over the socket, e.g. you have to implement a fancier authentication method, see "RawSocket". 👑

🔐 Starttls

If an IMAP connection must start TLS/SSL after connecting to a server then set this attribute. If the value is set to an arrayref then they will be used as arguments to IO::Socket::SSL->start_SSL. By default this connection is set to blocking while establishing the connection with a timeout of 30 seconds. The socket will be reset to the original blocking/non-blocking value after a successful TLS negotiation has occurred. The arguments used in the call to start_SSL can be controlled by setting this attribute to an ARRAY reference containing the desired arguments. 🎀

Version note: attribute added in Mail::IMAPClient 3.22

🧰 Socketargs

The arguments used in the call to IO::Socket::{UNIX|INET|IP|SSL}->new can be controlled by setting this attribute to an ARRAY reference containing the desired arguments.

For example, to always pass MultiHomed => 1 to IO::Socket::...->new the following can be used:

$imap = Mail::IMAPClient->new(
  ..., Socketargs => [ MultiHomed => 1 ], ...
);

See also "Ssl" for specific control of the args to IO::Socket::SSL.

Version note: attribute added in Mail::IMAPClient 3.34

🔒 Ssl

Okay so if your IMAP connection needs SSL, set the Ssl attribute to '1' and Mail::IMAPClient will automatically use IO::Socket::SSL instead of IO::Socket::(INET|IP) to connect to the server. This attribute is used in the connect method. You can control the arguments used in the call to IO::Socket::SSL->new by setting this attribute to an ARRAY reference containing the desired arguments. ✨

See also connect for details on connection initiation, and Socket and Rawsocket if you need to take more control of connection management. 🫶

🕰️ Version note: attribute added in Mail::IMAPClient 3.18

🏷️ Supportedflags

Especially when migrate() is used, the receiving peer may need to be configured explicitly with the list of supported flags; that may be different from the source IMAP server. Lowkey important, bestie.

The names are to be specified as an ARRAY. Black-slashes and casing will be ignored.

You may also specify a CODE reference, which will be called for each of the flags separately. In this case, the flags are not (yet) normalized. The returned lists from those CODE calls shape the resulting flag list. 💅

⏳ Timeout

Example:

$Timeout = $imap->Timeout();
# or:
$imap->Timeout($seconds);

Specifies the timeout value in seconds for reads (default is 600). Specifying a Timeout will prevent Mail::IMAPClient from blocking in a read.

Since timeouts are implemented via the Perl select operator, the Timeout parameter may be set to a fractional number of seconds. Setting Timeout to 0 (zero) disables the timeout feature. ⏰

🆔 Uid

Example:

$Uid = $imap->Uid();
# or:
$imap->Uid($true_or_false);

If Uid is set to a true value (i.e. 1) then the behavior of the fetch, search, copy, and store methods (and their derivatives) is changed so that arguments that would otherwise be message sequence numbers are treated as message UID's and so that return values (in the case of the search method and its derivatives) that would normally be message sequence numbers are instead message UID's. 👑

Internally this is implemented as a switch that, if turned on, causes methods that would otherwise issue an IMAP FETCH, STORE, SEARCH, or COPY client command to instead issue UID FETCH, UID STORE, UID SEARCH, or UID COPY, respectively. The main difference between message sequence numbers and message UID's is that, according to RFC3501, UID's must not change during a session and should not change between sessions, and must never be reused. Sequence numbers do not have that same guarantee and in fact may be reused right away. 😭

Since folder names also have a unique identifier (UIDVALIDITY), which is provided when the folder is selected or examined or by doing something like $imap->status($folder,"UIDVALIDITY"), it is possible to uniquely identify every message on the server, although normally you won't need to bother.

The methods currently affected by turning on the Uid flag are:

  copy            fetch
  search          store
  message_string  message_uid
  body_string     flags
  move            size
  parse_headers   thread

Note that if for some reason you only want the Uid parameter turned on for one command, then you can choose between the following two snippets, which are equivalent:

Example 1:

$imap->Uid(1);
my @uids = $imap->search('SUBJECT',"Just a silly test"); #
$imap->Uid(0);

Example 2:

my @uids;
foreach $r ($imap->UID("SEARCH","SUBJECT","Just a silly test") {
    chomp $r;
    $r =~ s/\r$//;
    $r =~ s/^\*\s+SEARCH\s+// or next;
    push @uids, grep(/\d/,(split(/\s+/,$r)));
}

In the second example, we used the default method to issue the UID IMAP client command, being careful to use an all-uppercase method name so as not to inadvertently call the Uid accessor method. Then we parsed out the message UIDs manually, since we don't have the benefit of the built-in search method doing it for us. 🧚

🚨 Please be very careful when turning the Uid parameter on and off throughout a script. If you lose track of whether you've got the Uid parameter turned on you might do something sad, like deleting the wrong message. Remember, like all eponymous accessor methods, the Uid method without arguments will return the current value for the Uid parameter, so do yourself a favor and check. The safest approach is probably to turn it on at the beginning (or just let it default to being on) and then leave it on. (Remember that leaving it turned off can lead to problems if changes to a folder's contents cause resequencing.) 💀

By default, the Uid parameter is turned on. ✅

👤 User

Example:

$User = $imap->User();
# or:
$imap->User($userid);

Specifies the userid to use when logging into the IMAP service. Can be supplied with the new method call or separately by calling the User object method.

Parameters can be set during new method invocation by passing named parameter/value pairs to the method, or later by calling the parameter's eponymous object method. 🫶


🩺 Status Methods 🩺

There are several object methods that return the status of the object. They can be used at any time to check the status of an IMAPClient object, but are particularly useful for determining the cause of failure when a connection and login are attempted as part of a single new method invocation. The status methods are:

🪄 Escaped_history

Example:

my @history = $imap->Escaped_history;

The Escaped_history method is almost identical to the History method. Unlike the History method, however, server output transmitted literally will be wrapped in double quotes, with all double quotes, backslashes escaped. If called in a scalar context, Escaped_history returns an array reference rather than an array.

Escaped_history is useful if you are retrieving output and processing it manually, and you are depending on the above special characters to delimit the data. It is not useful when retrieving message contents; use message_string or body_string for that. 😌

🪄 Escaped_results

Example:

my @results = $imap->Escaped_results;

The Escaped_results method is almost identical to the Results method. Unlike the Results method, however, server output transmitted literally will be wrapped in double quotes, with all double quotes, backslashes escaped. If called in a scalar context, Escaped_results returns an array reference rather than an array.

Escaped_results is useful if you are retrieving output and processing it manually, and you are depending on the above special characters to delimit the data. It is not useful when retrieving message contents; use message_string or body_string for that. 🎀

📜 History

Example:

my @history = $imap->History;

The History method is almost identical to the Results method. Unlike the Results method, however, the IMAP command that was issued to create the results being returned is not included in the returned results. If called in a scalar context, History returns an array reference rather than an array. 🦋

🚫 IsUnconnected

Returns a true value if the object is currently in an Unconnected state.

✅ IsConnected

Returns a true value if the object is currently in either a Connected, Authenticated, or Selected state.

🔐 IsAuthenticated

Returns a true value if the object is currently in either an Authenticated or Selected state.

📬 IsSelected

Returns a true value if the object is currently in a Selected state.

😭 LastError

Internally LastError is implemented just like a parameter (as described in "Parameters", above). There is a LastError attribute and an eponymous accessor method which returns the LastError text string describing the last error condition encountered by the server.

Note that some errors are more serious than others, so LastError's value is only meaningful if you encounter an error condition that you don't like. For example, if you use the exists method to see if a folder exists and the folder does not exist, then an error message will be recorded in LastError even though this is not a particularly serious error. On the other hand, if you didn't use exists and just tried to select a non-existing folder, then select would return undef after setting LastError to something like NO SELECT failed: Can't open mailbox "mailbox": no such mailbox. At this point it would be useful to print out the contents of LastError as you die. 💀

🧾 LastIMAPCommand

New in version 2.0.4, LastIMAPCommand returns the exact IMAP command string to be sent to the server. Useful mainly in constructing error messages when LastError just isn't enough.

📊 Report

The Report method returns an array containing a history of the IMAP session up to the point that Report was called. It is primarily meant to assist in debugging but can also be used to retrieve raw output for manual parsing. The value of the Clear parameter controls how many transactions are in the report.

📥 Results

The Results method returns an array containing the results of one IMAP client command. It accepts one argument, the transaction number of the command whose results are to be returned. If transaction number is unspecified then Results returns the results of the last IMAP client command issued. If called in a scalar context, Results returns an array reference rather than an array.

🔄 State

The State method returns a numerical value that indicates the current status of the IMAPClient object. If invoked with an argument, it will set the object's state to that value. If invoked without an argument, it behaves just like Status, below.

Normally you will not have to invoke this function. An exception is if you are bypassing the Mail::IMAPClient module's connect and/or login modules to set up your own connection (say, for example, over a secure socket), in which case you must manually do what the connect and login methods would otherwise do for you.

🚦 Status

The Status method returns a numerical value that indicates the current status of the IMAPClient object. (Not to be confused with the status method, all lower-case, which is the implementation of the STATUS IMAP client command.)

🏷️ Transaction

The Transaction method returns the tag value (or transaction number) of the last IMAP client command.

🌈 Custom Authentication Mechanisms 🌈

Okay bestie, listen — if all you wanna do is plain text auth or any of the supported "Advanced Authentication Mechanisms", then you can literally skip this whole section. No cap, you don't need it. 💅

But if you're out here wanting to build your own auth mechanism? There's a whole pile of methods and parameters for exactly that. Everything talked about here is described in more detail elsewhere in this doc — this section is just your starting point for building your own authentication mechanism. ✨

There are SO many auth mechanisms out there, and if your fave isn't supported yet but you somehow got it working — please consider donating it to this module? Patches and suggestions are always welcome, fr fr. 🫶

Adding support for add-on authentication mechanisms in Mail::IMAPClient is pretty straightforward. You create a callback that provides the response to the server's challenge. The Authcallback parameter holds a reference to that callback — it can be an anonymous subroutine or a named subroutine, your call. Then you identify your authentication mechanism, either via the Authmechanism parameter or as an argument to authenticate. 🎀

You might also need a subroutine to encrypt (or whatever) data before it gets sent to the server — the Prewritemethod parameter has to contain a reference to that subroutine. And you'll need to decrypt data coming from the server; a reference to the subroutine that does that goes in the Readmethod parameter. 🔥

This framework is built on a couple of assumptions, and you should know them:

  • a) the mechanism you're using requires a challenge-response exchange, and
  • b) the mechanism doesn't fundamentally alter the exchange between client and server, it just wraps the exchange in a layer of encryption.

It also assumes the line-oriented nature of the IMAP conversation is preserved. Authentication mechanisms that break messages up into blocks of a predetermined size might still be possible, but they'll certainly be more difficult to implement. 😭

Alternatively — if you have access to imtest, a utility included in the Cyrus IMAP distribution, you can use that utility to broker your communications with the IMAP server. This is quite easy to implement. There's an example, examples/imtestExample.pl, chilling in the examples subdirectory of the source distribution. 🌸

The following list summarizes the methods and parameters you might find useful when implementing advanced authentication:

🌟 The authenticate method

The authenticate method uses the Authmechanism parameter to figure out how to authenticate with the server — see the method documentation for details.

🔌 Socket and RawSocket

The Socket and RawSocket methods give you access to the socket connection. The socket is typically created automatically by the connect method, but if you're implementing an advanced authentication technique you may choose to set up your own socket connection and then set this parameter manually, bypassing the connect method completely. This is also useful if you want to use IO::Socket::(INET|IP) alternatives like IO::Socket::SSL and need full control. 👑

RawSocket simply gets/sets the socket without attempting any interaction on it. In this case, you have to be sure to handle all the preliminary operations and manually set the Mail::IMAPClient object in sync with its actual status with respect to this socket (see below for additional parameters about this, especially the State parameter).

Unlike RawSocket, Socket attempts to carry on preliminary connection phases if the conditions apply. If both parameters are present, this takes precedence over RawSocket. If Starttls is set, then the starttls method will be called by Socket.

PLEASE NOTE As of version 2.99_04 of this module, semantics for Socket have changed to make it more "DWIM". RawSocket was introduced as a replacement for the Socket parameter in older versions.

🧭 State, Server, User, Password, Proxy and Domain Parameters

If you need to make your own connection to the server and perform your authentication manually, then you can set these parameters to keep your Mail::IMAPClient object in sync with its actual status. Of these, only the State parameter is always necessary. The others need to be set only if you think your program will need them later. 🦋

🔑 Authmechanism

Set this to the value that AUTHENTICATE should send to the server as the authentication mechanism. If you're brokering your own authentication then this parameter may be less useful. It exists primarily so that you can set it when you call new to instantiate your object. The new method will call connect, which will call login. If login sees that you've set an Authmechanism, then it will call authenticate, using your Authmechanism and Authcallback parameters as arguments. ✨

🎯 Authcallback

The Authcallback, if set, holds a pointer to a subroutine (CODEREF). The login method will use this as the callback argument to the authenticate method if the Authmechanism and Authcallback parameters are both set. If you set Authmechanism but not Authcallback, then the default callback for your mechanism will be used. All supported authentication mechanisms have a default callback; in every other case, not supplying the callback results in an error. 💀

Most advanced authentication mechanisms require a challenge-response exchange. After the authenticate method sends <tag> AUTHENTICATE <Authmechanism>\015\012 to the IMAP server, the server replies with a challenge. The authenticate method then invokes the code whose reference is stored in the Authcallback parameter like this:

$Authcallback->( $challenge, $imap )

where $Authcallback is the code reference stored in the Authcallback parameter, $challenge is the challenge received from the IMAP server, and $imap is a pointer to the Mail::IMAPClient object. The return value from the Authcallback routine should be the response to the challenge, and that return value will be sent by the authenticate method to the server. 🧚

🪄 Prewritemethod/Readmethod

The Prewritemethod can hold a subroutine that will do whatever encryption is necessary and then return the result to the caller so it in turn can be sent to the server.

The Readmethod can hold a subroutine to be used to replace sysread usually performed by Mail::IMAPClient.

See "Prewritemethod" and "Readmethod" for details.


🐛 REPORTING BUGS 🐛

Please file bug reports via https://github.com/plobbes/mail-imapclient/issues — that's the spot, bestie. 🙈


Copyright (C) 1999-2003 The Kernen Group, Inc.
Copyright (C) 2007-2009 Mark Overmeer
Copyright (C) 2010-2021 Phil Pearl (Lobbes)
All rights reserved.

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.0 or, at your option, any later version of Perl 5 you may have available. 💖

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See either the GNU General Public License or the Artistic License for more details. ⭐


And that's a wrap on the whole page, babe — you made it to the very end. 🎉 This one's perl v5.40.2, dated 2024-10-16, Mail::IMAPClient(3). Go forth and slay your IMAP connections, ily, bye 👑💜

📦 where this page comes from