Mail-IMAPClient

 view release on metacpan or  search on metacpan

lib/Mail/IMAPClient.pod  view on Meta::CPAN

=head2 sort

Example:

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

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

The first argument to B<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 B<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 L</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 I<ALL> as your only search
criterion.

The B<sort> method returns an array containing sequence numbers of
messages that passed the SORT IMAP client command's search criteria.
If the L</Uid> parameter is true then the array will contain message
UID's.  If B<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 C<$@> before attempting the I<SORT>
operation just as the L</search> method does.

=head2 starttls

Example:

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

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

Version note: method added in Mail::IMAPClient 3.22

=head2 status

Example:

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

The B<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 B<status> is not called in an array context then it returns a
reference to an array rather than the array itself.

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

=head2 store

Example:

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

The B<store> method accepts a message sequence number or
comma-separated list of message sequence numbers as a first argument,
a message data item name, and a value for the message data item.
Currently, data items are the word "FLAGS" followed by a space and a
list of flags (in parens).  The word "FLAGS" can be modified by
prefixing it with either a "+" or a "-" (to indicate "add these flags"
or "remove these flags") and by suffixing it with ".SILENT" (which
reduces the amount of output from the server; very useful with large
message sets).  Normally you won't need to call B<store> because there
are oodles of methods that will invoke store for you with the correct
arguments.  Furthermore, these methods are friendlier and more
flexible with regards to how you specify your arguments.  See for
example L</see>, L</deny_seeing>, L</delete_message>, and
L</restore_message>.  Or L</mark>, L</unmark>, L</set_flag>, and
L</unset_flag>.

=head2 subject

Example:

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

The B<subject> method accepts one argument, a message sequence number
(or a message UID, if the I<Uid> parameter is true).  The text in the

lib/Mail/IMAPClient.pod  view on Meta::CPAN

=head2 Prewritemethod

I<Prewritemethod> parameter should contain a reference to a subroutine
that will do "special things" to data before it is sent to the IMAP
server (such as encryption or signing).

This method will be called immediately prior to sending an IMAP client
command to the server.  Its first argument is a reference to the
I<Mail::IMAPClient> object and the second argument is a string
containing the command that will be sent to the server.  Your
I<Prewritemethod> should return a string that has been signed or
encrypted or whatever; this returned string is what will actually be
sent to the server.

Your I<Prewritemethod> will probably need to know more than this to do
whatever it does.  It is 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 I<Mail::IMAPClient>
object itself.

Note that this method should not actually send anything over the
socket connection to the server; it merely converts data prior to
sending.

See also L</Readmethod>.

=head2 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;
  }

If set to a true value, then the L</search> method will return a
L<Mail::IMAPClient::MessageSet> object if called in a scalar context,
instead of the array reference that B<fetch> normally returns when
called in a scalar context.  If set to zero or if undefined, then
B<search> will continue to return an array reference when called in
scalar context.

This parameter has no affect on the B<search> method when B<search>
is called in a list context.

=head2 RawSocket

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

The I<RawSocket> method can be used to obtain the socket handle of the
current connection (say, to do I/O on the connection that is not
otherwise supported by Mail::IMAPClient) or to replace the current
socket with a new handle (for instance an SSL handle, see
L<IO::Socket::SSL>, but be sure to see the L</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 will be up to you to establish the connection AND to
authenticate, either via the L</login> method, or the fancier
L</authenticate>, or, since you know so much anyway, by just doing raw
I/O against the socket until you're logged in.  If you do any of this
then you should also set the L</State> parameter yourself to reflect
the current state of the object (i.e. Connected, Authenticated, etc).

Note that no operation will be attempted on the socket when this
method is called.  In particular, after the TCP connections towards
the IMAP server is established, the protocol mandates the server to
send an initial greeting message, and you will have to explicitly cope
with this message before doing any other operation, e.g. trying to
call L</login>. Caveat emptor.

For a more DWIM approach to setting the socket see L</Socket>.

=head2 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...
      }
  );

B<Readmethod> should contain a reference to a subroutine that will
replace sysread.  The subroutine will be passed the following
arguments: 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 placed here should be "finished
data", so if you are decrypting or removing signatures then be sure to
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 then your subroutine will
have to actually do the read.  It is for things like this that we have
the L</Socket> parameter and eponymous accessor method.

Your I<Readmethod> will probably need to know more than this to do
whatever it does.  It is 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 I<Mail::IMAPClient>

lib/Mail/IMAPClient.pod  view on Meta::CPAN

Version note: attribute added in Mail::IMAPClient 3.30

=head2 Reconnectretry

If an IMAP connection sits idle too long, the connection may be closed
by the server or firewall, etc.  The B<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 L</Keepalive>

Version note: attribute added in Mail::IMAPClient 3.17

=head2 Server

Example:

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

Specifies the hostname or IP address of the host running the IMAP
server.  If provided as part of the L</new> method call, then the new
IMAP object will automatically be connected at the time of
instantiation.  (See the L</new> method, below.) Can be supplied with
the L</new> method call or separately by calling the B<Server> object
method.

=head2 Showcredentials

Normally debugging output will mask the login credentials when the
plain text login mechanism is used.  Setting I<Showcredentials> to a
true value will suppress this, so that you can see the string being
passed back and forth during plain text login.  Only set this to true
when you are debugging problems with the IMAP LOGIN command, and then
turn it off right away when you're finished working on that problem.

Example:

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

=head2 Socket

B<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
L</RawSocket>.

Example:

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

The I<Socket> method can be used to obtain the socket handle of the
current connection.  This may be necessary to do I/O on the connection
that is not 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 C<$ssl> in the example is a valid and connected socket.

This method is primarily used to provide a drop-in replacement for
IO::Socket::(INET|IP), used by L</connect> by default.  In fact, this
method is called by L</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 L</connect>, namely:

=over 4

=item *

read the initial greeting message from the server;

=item *

call L</login> if the conditions apply (see L</connect> for details);

=item *

leave the I<Mail::IMAPClient> object in a suitable state.

=back

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 L</RawSocket>.

=head2 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

=head2 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 L</Ssl> for specific control of the args to IO::Socket::SSL.

Version note: attribute added in Mail::IMAPClient 3.34

=head2 Ssl

If an IMAP connection requires SSL you can set the Ssl attribute to
'1' and Mail::IMAPClient will automatically use L<IO::Socket::SSL>
instead of IO::Socket::(INET|IP) to connect to the server.  This
attribute is used in the L</connect> method.  The arguments used in
the call to IO::Socket::SSL->new can be controlled by setting this
attribute to an ARRAY reference containing the desired arguments.

See also L</connect> for details on connection initiation and
L</Socket> and L</Rawsocket> if you need to take more control of
connection management.

Version note: attribute added in Mail::IMAPClient 3.18

=head2 Supportedflags

Especially when C<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.

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 of the CODE calls are shape the
resulting flag list.

=head2 Timeout

Example:

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

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

Since timeouts are implemented via the Perl L<select|perlfunc/select>
operator, the I<Timeout> parameter may be set to a fractional number
of seconds.  Setting I<Timeout> to 0 (zero) disables the timeout
feature.

=head2 Uid

Example:

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

If L</Uid> is set to a true value (i.e. 1) then the behavior of the
L</fetch>, L</search>, L</copy>, and L</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 L</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,

lib/Mail/IMAPClient.pod  view on Meta::CPAN


There are a number of methods and parameters that you can use to build
your own authentication mechanism.  All of the methods and parameters
discussed in this section are described in more detail elsewhere in
this document.  This section provides a starting point for building
your own authentication mechanism.

There are I<many> authentication mechanisms out there, if your
preferred mechanism is not currently supported but you manage to get
it working please consider donating them to this module.  Patches and
suggestions are always welcome.

Support for add-on authentication mechanisms in Mail::IMAPClient is
pretty straight forward.  You create a callback to be used to provide
the response to the server's challenge.  The L</Authcallback> parameter
contains a reference to the callback, which can be an anonymous
subroutine or a named subroutine.  Then, you identify your
authentication mechanism, either via the L</Authmechanism> parameter or
as an argument to L</authenticate>.

You may also need to provide a subroutine to encrypt (or whatever)
data before it is sent to the server.  The L</Prewritemethod> parameter
must contain a reference to this subroutine.  And, you will need to
decrypt data from the server; a reference to the subroutine that does
this must be stored in the L</Readmethod> parameter.

This framework is based on the assumptions that a) the mechanism you
are using requires a challenge-response exchange, and b) the mechanism
does not fundamentally alter the exchange between client and server
but merely wraps the exchange in a layer of encryption.  It also
assumes that the line-oriented nature of the IMAP conversation is
preserved; authentication mechanisms that break up messages into
blocks of a predetermined size may still be possible but will
certainly be more difficult to implement.

Alternatively, if you have access to B<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.
An example, F<examples/imtestExample.pl>, can be found in the
C<examples> subdirectory of the source distribution.

The following list summarizes the methods and parameters that you may
find useful in implementing advanced authentication:

=over 4

=item The authenticate method

The L</authenticate> method uses the L</Authmechanism> parameter to
determine how to authenticate with the server see the method
documentation for details.

=item Socket and RawSocket

The L</Socket> and L</RawSocket> methods provide access to the socket
connection.  The socket is typically automatically created by the
L</connect> method, but if you are implementing an advanced
authentication technique you may choose to set up your own socket
connection and then set this parameter manually, bypassing the
B<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.

L</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 regarding this, especially the
L</State> parameter).

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

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

=item 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 L</State> parameter is always necessary.  The others
need to be set only if you think your program will need them later.

=item Authmechanism

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

=item Authcallback

The L</Authcallback>, if set, holds a pointer to a subroutine
(CODEREF).  The L</login> method will use this as the callback
argument to the B<authenticate> method if the B<Authmechanism> and
B<Authcallback> parameters are both set.  If you set B<Authmechanism>
but not B<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 L</authenticate> method sends "<tag> AUTHENTICATE
<Authmechanism>\015\012" to the IMAP server, the server replies with a
challenge.  The L</authenticate> method then invokes the code whose
reference is stored in the B<Authcallback> parameter as follows:

  $Authcallback->( $challenge, $imap )

where C<$Authcallback> is the code reference stored in the
B<Authcallback> parameter, C<$challenge> is the challenge received



( run in 0.928 second using v1.01-cache-2.11-cpan-39bf76dae61 )