=encoding utf8

=head1 NAME

Mail::Transport::IMAP4 - proxy to Mail::IMAPClient

=head1 INHERITANCE

 Mail::Transport::IMAP4
   is a Mail::Transport::Receive
   is a Mail::Transport
   is a Mail::Reporter

=head1 SYNOPSIS

  my $imap = Mail::Transport::IMAP4->new(...);
  my $message = $imap->receive($id);
  $imap->send($message);

  my Mail::Box::Manager $mgr = Mail::Box::Manager->new;
  $mgr->open(
      # Generic folder options
      folder => 'imaps://...',
      access => 'rw',
      extract => 'ALWAYS',

      # Mail::IMAPClient options start with [A-Z]
      IgnoreSizeErrors => 1,
      Ssl => 1,
  );

=head1 DESCRIPTION

The IMAP4 protocol is quite complicated: it is feature rich and allows
various asynchronous actions.  The main document describing IMAP is
rfc3501 (which obsoleted the original specification of protocol 4r1
in rfc2060 in March 2003).

This package, as part of MailBox, does not implement the actual
protocol itself but uses Mail::IMAPClient to do the work. The task
for this package is to hide as many differences between that module's
interface and the common MailBox folder types.  Multiple
L<Mail::Box::IMAP4|Mail::Box::IMAP4> folders can share one L<Mail::Transport::IMAP4|Mail::Transport::IMAP4>
connection.

The Mail::IMAPClient module is the best IMAP4 implementation for
Perl5, but is not maintained.  There are many known problems with the
module, and solving those is outside the scope of MailBox.  See
L<https://rt.cpan.org/Public/Dist/Display.html?Name=Mail-IMAPClient>
for all the reported bugs.

Extends L<"DESCRIPTION" in Mail::Transport::Receive|Mail::Transport::Receive/"DESCRIPTION">.

=head1 METHODS

Extends L<"METHODS" in Mail::Transport::Receive|Mail::Transport::Receive/"METHODS">.

=head2 Constructors

Extends L<"Constructors" in Mail::Transport::Receive|Mail::Transport::Receive/"Constructors">.

=over 4

=item $class-E<gt>B<new>(%options)

Create the IMAP connection to the server.  IMAP servers can handle
multiple folders for a single user, which means that connections
may get shared.  This is sharing is hidden for the user.

When an C<imap_client> is specified, then the options C<hostname>,
C<port>, C<username>, and C<password> are extracted from it.

All C<%options> which start with a capital are passed as initiation
to Mail::IMAPClient.  See that manual about the huge pile of
parameters.  When talking to Microsoft Exchange, you probabaly need the
C<IgnoreSizeErros>.  Probably, you need C<Ssl> or C<StartTLS> as well.
As feature, you may also pass a HASH to Ssl, where C<Mail::IMAPClient>
only accepts an ARRAY.

For backwards compatibility, C<ssl> is an alternative for C<Ssl>,
and C<starttls> for C<StartTLS>.
Improves base, see L<Mail::Reporter/"Constructors">

 -Option      --Defined in     --Default
  authenticate                   'AUTO'
  domain                         <server_name>
  executable    Mail::Transport  undef
  hostname      Mail::Transport  'localhost'
  imap_client                    Mail::IMAPClient
  interval      Mail::Transport  30
  password      Mail::Transport  undef
  port          Mail::Transport  143
  proxy         Mail::Transport  undef
  retry         Mail::Transport  <unlimited>
  timeout       Mail::Transport  120
  username      Mail::Transport  undef
  via           Mail::Transport  'imap'

=over 2

=item authenticate => TYPE|ARRAY

Authenthication method to L<login()|Mail::Transport::IMAP4/"Protocol [internals]">, which will be passed to
Mail::IMAPClient subroutine authenticate.  See the latter method for
the available types.  You may provide an ARRAY of types.

=item domain => WINDOWS_DOMAIN

Used for NTLM authentication.

=item executable => $file

=item hostname => $host|\@hosts

=item imap_client => OBJECT|CLASS

When an OBJECT is supplied, that client will be used for the implementation
of the IMAP4 protocol. Information about server and such are extracted from
the OBJECT to have the accessors to produce correct results. The OBJECT
shall be a L<Mail::IMAPClient|Mail::IMAPClient>.

When a CLASS is given, an object of that type is created for you.  The created
object can be retrieved via L<imapClient()|Mail::Transport::IMAP4/"Protocol [internals]">, and than configured as
defined by L<Mail::IMAPClient|Mail::IMAPClient>.

=item interval => $span

=item password => $password

=item port => $port

=item proxy => $path

=item retry => $count|undef

=item timeout => $span

=item username => $username

=item via => CLASS|$name

=back

=back

=head2 Attributes

Extends L<"Attributes" in Mail::Transport::Receive|Mail::Transport::Receive/"Attributes">.

=over 4

=item $obj-E<gt>B<authentication>( ['AUTO'|$type|$types] )

Returns a LIST of ARRAYS, each describing one possible way to contact
the server. Each pair contains a mechanism name and a challenge callback
(which may be C<undef>).

The settings are used by L<login()|Mail::Transport::IMAP4/"Protocol [internals]"> to get server access.  The initial
value origins from L<new(authenticate)|Mail::Transport::IMAP4/"METHODS">, but may be changed later.

Available basic C<$types> are C<CRAM-MD5>, C<NTLM>, and C<PLAIN>.  With
C<AUTO>, all available types will be tried.  When the Authen::NTLM
is not installed, the C<NTLM> option will silently be skipped.  Be warned
that, because of C<PLAIN>, erroneous username/password combinations will
be passed readible as last attempt!

The C<NTLM> authentication requires Authen::NTLM to be installed.  Other
methods may be added later.  Besides, you may also specify a CODE
reference which implements some authentication.

An ARRAY as C<$type> can be used to specify both mechanism as callback.  When
no array is used, callback of the pair is set to C<undef>.  See
L<Mail::IMAPClient/authenticate> for the gory details.

» example: 

  $transporter->authentication('CRAM-MD5', [MY_AUTH => \&c], 'PLAIN');

  foreach my $pair ($transporter->authentication)
  {   my ($mechanism, $challenge) = @$pair;
      ...
  }

=item $obj-E<gt>B<domain>( [$domain] )

Used in NTLM authentication to define the Windows domain which is
accessed.  Initially set by L<new(domain)|Mail::Transport::IMAP4/"METHODS"> and defaults to the
server's name.

=item $obj-E<gt>B<usesSSL>()

Returns a boolean.

=back

=head2 Receiving mail

Extends L<"Receiving mail" in Mail::Transport::Receive|Mail::Transport::Receive/"Receiving mail">.

=over 4

=item $obj-E<gt>B<receive>( [$unique_message_id] )

Inherited, see L<Mail::Transport::Receive/"Receiving mail">

=back

=head2 Server connection

Extends L<"Server connection" in Mail::Transport::Receive|Mail::Transport::Receive/"Server connection">.

=over 4

=item $obj-E<gt>B<findBinary>( $name, [@directories] )

Inherited, see L<Mail::Transport/"Server connection">

=item $obj-E<gt>B<remoteHost>()

Inherited, see L<Mail::Transport/"Server connection">

=item $obj-E<gt>B<retry>()

Inherited, see L<Mail::Transport/"Server connection">

=back

=head2 Exchanging Information

=head2 Protocol [internals]

The follow methods handle protocol internals, and should not be used
by a normal user of this class.

=over 4

=item $obj-E<gt>B<appendMessage>( $message, $foldername, [$date] )

Write the message to the server.
The optional DATA can be a RFC-822 date or a timestamp.

=item $obj-E<gt>B<createFolder>($name)

Add a folder.

=item $obj-E<gt>B<createImapClient>($class, %options)

Create an object of C<$class>, which extends L<Mail::IMAPClient>.

=item $obj-E<gt>B<currentFolder>( [$foldername] )

Be sure that the specific FOLDER is the current one selected.  If the
folder is already selected, no IMAP traffic will be produced.

The boolean return value indicates whether the folder is selectable. It
will return C<undef> if it does not exist.

=item $obj-E<gt>B<deleteFolder>($name)

Remove one folder.

=item $obj-E<gt>B<destroyDeleted>($folder)

Command the server to delete for real all messages which are flagged to
be deleted.

=item $obj-E<gt>B<fetch>(\@messages, $info)

Get some C<$info> about the C<@messages> from the server.  The specified messages
shall extend L<Mail::Box::Net::Message|Mail::Box::Net::Message>, Returned is a list
of hashes, each info about one result.  The contents of the hash
differs per C<$info>, but at least a C<message> field will be present, to
relate to the message in question.

The right folder should be selected before this method is called. When
the connection was lost, C<undef> is returned.  Without any
messages, and empty array is returned.  The retrieval is done by
L<Mail::IMAPClient|Mail::IMAPClient> method C<fetch()>, which is then
parsed.

=item $any-E<gt>B<flagsToLabels>($what, @flags)

In SCALAR context, a hash with labels is returned.  In LIST context, pairs
are returned.

The C<$what> parameter can be C<'SET'>, C<'CLEAR'>, or C<'REPLACE'>.  With
the latter, all standard imap flags which do not appear in the list will
be ignored: their value may either by set or cleared.  See L<getFlags()|Mail::Transport::IMAP4/"Protocol [internals]">

Unknown flags in C<@flags> are stripped from their backslash and
lower-cased.  For instance, '\SomeWeirdFlag' will become
`someweirdflag =E<gt> 1'.  It will be set to '1' for C<SET>, and '0'
in case of C<CLEAR>.

» example: translating IMAP4 flags into MailBox flags

  my @flags  = ('\Seen', '\Flagged');
  my $labels = Mail::Transport::IMAP4->flags2labels(SET => @flags);

=item $obj-E<gt>B<folders>( [$foldername] )

Returns a list of folder names which are sub-folders of the specified
C<$foldername>.  Without C<$foldername>, the top-level foldernames are returned.

=item $obj-E<gt>B<getFields>( $uid, $name, [$name, ...] )

Get the records with the specified NAMES from the header.  The header
fields are returned as list of L<Mail::Message::Field::Fast|Mail::Message::Field::Fast> objects.
When the name is C<ALL>, the whole header is returned.

=item $obj-E<gt>B<getFlags>($folder, $id)

Returns the values of all flags which are related to the message with the
specified C<$id>.  These flags are translated into the names which are
standard for the MailBox suite.

A HASH is returned.  Names which do not appear will also provide
a value in the returned: the negative for the value is it was present.

=item $obj-E<gt>B<getMessageAsString>($message|$uid)

Returns the whole text of the specified message: the head and the body.

=item $obj-E<gt>B<ids>()

Returns a list of UIDs which are defined by the IMAP server.

=item $obj-E<gt>B<imapClient>()

Returns the object which implements the IMAP4 protocol, an instance
of a Mail::IMAPClient, which is logged-in and ready to use.

If the contact to the server was still present or could be established,
an Mail::IMAPClient object is returned.  Else, C<undef> is returned and
no further actions should be tried on the object.

=item $any-E<gt>B<labelsToFlags>(HASH|PAIRS)

Convert MailBox labels into IMAP flags.  Returned is a string.  Unsupported
labels are ignored.

=item $obj-E<gt>B<listFlags>()

Returns all predefined flags as list.

=item $obj-E<gt>B<login>()

Establish a new connection to the IMAP4 server, using username and password.

=item $obj-E<gt>B<setFlags>($id, $label, $value, [$label, $value], ...)

Change the flags on the message which are represented by the label.  The
value which can be related to the label will be lost, because IMAP only
defines a boolean value, where MailBox labels can contain strings.

Returned is a list of (C<$label> => C<$value>) pairs which could not be send to
the IMAP server.  These values may be cached in a different way.

=back

=head2 Error handling

Extends L<"Error handling" in Mail::Transport::Receive|Mail::Transport::Receive/"Error handling">.

=over 4

=item $obj-E<gt>B<AUTOLOAD>()

Inherited, see L<Mail::Reporter/"Error handling">

=item $obj-E<gt>B<notImplemented>()

Inherited, see L<Mail::Reporter/"Error handling">

=back

=head2 Cleanup

Extends L<"Cleanup" in Mail::Transport::Receive|Mail::Transport::Receive/"Cleanup">.

=over 4

=item $obj-E<gt>B<DESTROY>()

The connection is cleanly terminated when the program is
terminated.
Improves base, see L<Mail::Reporter/"Cleanup">

=back

=head1 DIAGNOSTICS

=over 4

=item Notice: IMAP4 authenication $type to $service successful

Cast by C<login()>

=item Error: IMAP4 cannot connect to $service: $@

Cast by C<login()>

=item Error: IMAP4 requires a username and password

Cast by C<login()>

=item Error: IMAP4 username $user requires a password

Cast by C<login()>

=item Error: cannot create imap client: {error}

Cast by C<createImapClient()>

=item Error: class $package does not implement method $method.

Fatal error: the specific C<$package> (or one of its superclasses) does not
implement this method where it should. This message means that some other
related classes do implement this method however the class at hand does
not.  Probably you should investigate this and probably inform the author
of the package.
Cast by C<notImplemented()>

=item Error: couldn't contact to IMAP4 $service

Cast by C<login()>

=item Notice: couldn't select folder $name but it does exist.

Cast by C<currentFolder()>

=item Warning: failed attempt to login $user, retrying $retries times.

Cast by C<login()>

=item Notice: folder $name does not exist!

Cast by C<currentFolder()>

=item Notice: selected IMAP4 folder $name.

Cast by C<currentFolder()>

=back

=head1 SEE ALSO

This module is part of Mail-Box-IMAP4 version 4.01,
built on December 13, 2025. Website: F<http://perl.overmeer.net/CPAN/>

=head1 LICENSE

For contributors see file ChangeLog.

This software is copyright (c) 2001-2025 by Mark Overmeer.

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

