=encoding utf8

=head1 NAME

Mail::Box::Manager - manage a set of folders

=head1 INHERITANCE

 Mail::Box::Manager
   is a Mail::Reporter

 Mail::Box::Manager is extended by
   Mail::Box::Manage::User

=head1 SYNOPSIS

  use Mail::Box::Manager;
  my $mgr     = new Mail::Box::Manager;

  # Create folder objects.
  my $folder   = $mgr->open(folder => $ENV{MAIL});
  my $message1 = $folder->message(0);
  $mgr->copyMessage('Draft', $message);

  my @messages = $folder->message(0,3);
  $mgr->moveMessage('Outbox', @messages, create => 1 );
  $mgr->close($folder);

  # Create thread-detectors (see Mail::Box::Thread::Manager)
  my $t       = $mgr->discoverThreads($inbox, $outbox);

  my $threads = $mgr->discoverThreads(folder => $folder);
  foreach my $thread ($threads->all)
  {   $thread->print;
  }

  $mgr->registerType(mbox => 'Mail::Box::MyType');

=head1 DESCRIPTION

The manager keeps track on a set of open folders and a set of message-thread
supporting objects.  You are not obliged to use this object (you can
directly create a L<Mail::Box::Mbox|Mail::Box::Mbox> if you prefer), but you will create
more portable and safer code if you do use it.

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

=head1 METHODS

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

=head2 Constructors

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

=over 4

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

Inherited, see L<Mail::Reporter/"Constructors">

 -Option             --Default
  autodetect           undef
  default_folder_type  'mbox'
  folder_types         <all standard types>
  folderdir            [ '.' ]
  folderdirs           <synonym for C<folderdir>>

=over 2

=item autodetect => $type|\@types

Select only a subset of the folder C<@types> which are implemented by MailBox
to be detected automatically.  This may improve the auto-detection of
folder types.  Normally, all folder types will be tried when a folder's
name is incorrect, but this option limits the types which are checked
and therefore may respond faster.

=item default_folder_type => $type|CLASS

Specifies the default folder C<$type> for newly created folders.  If this
option is not specified, the most recently registered type is used (see
L<registerType()|Mail::Box::Manager/"Attributes"> and the L<new(folder_types)|Mail::Box::Manager/"METHODS"> option.

=item folder_types => $typedef|\@typedefs

Add one or more new folder C<@typedefs> to the list of known types.
The order is important: when you open a file without specifying its type,
the manager will start trying the last added list of types, in order.

Each C<$typedef> is specified as an array which contains name, class, and
defaults for options which overrule the usual defaults.  You may specify
folder-specific defaults as OPTIONS.  They override the settings of
the manager.

=item folderdir => DIRECTORY

The default directory, or directories, where folders are
located. The C<Mail::Box::Manager> can autodetect the existing folder-types.
There may be different kinds of folders opened at the same time, and
messages can be moved between those types, although that may result in
a loss of information depending on the folder types.

=item folderdirs => [DIRECTORIES]

=back

=back

=head2 Attributes

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

=over 4

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

Returns the default folder type, some class name.

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

Z<>

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

Returns the list of currently defined folder types.

» example: 

  print join("\n", $manager->folderTypes), "\n";

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

In list context, this returns all folderdirs specified.  In SCALAR
context only the first.

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

With C<registerType> you can register one C<$type> of folders.  The C<$class>
is compiled automatically, so you do not need to C<use> them in your own
modules.  The C<$type> is just an arbitrary name.

The added types are prepended to the list of known types, so they are
checked first when a folder is opened in autodetect mode.

» example: 

  $manager->registerType(mbox => 'Mail::Box::Mbox',
      save_on_exit => 0, folderdir => '/tmp');

=item $obj-E<gt>B<threads>( [@params] )

return the descovered threads (cached value).  When any C<@params> are passed, then
L<discoverThreads()|Mail::Box::Manager/"Manage message threads"> will be called for backwards compatibility.

=back

=head2 Manage open folders

=over 4

=item $obj-E<gt>B<close>($folder, %options)

Remove the specified C<$folder> from the index of open folders.
Indirectly it will update the files on disk if needed (depends on
the L<Mail::Box::new(save_on_exit)|Mail::Box/"Constructors"> flag for each folder). C<%options> are
passed to L<Mail::Box::close()|Mail::Box/"The folder"> of the folder.

The folder's messages will also be withdrawn from the known message threads.
You may also close the folder directly. The manager will be informed
about this event and take appropriate actions.

 -Option       --Default
  close_by_self  <C<false>>

=over 2

=item close_by_self => BOOLEAN

Used internally to avoid confusion about how the close was started.  Do
not change this.

=back

» example: 

  my $inbox = $mgr->open('inbox');
  $mgr->close($inbox);
  $inbox->close;        # alternative

=item $obj-E<gt>B<closeAllFolders>(%options)

C<closeAllFolders> calls close() for each folder managed by
this object.  It is called just before the program stops (before global
cleanup).

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

Returns C<true> if the C<$folder> is currently open.

» example: 

  print "Yes\n" if $mgr->isOpenFolder('Inbox');

=item $obj-E<gt>B<open>( [$foldername], %options )

Open a folder which name is specified as first parameter or with
the option flag C<folder>.  The folder type is autodetected unless
the C<type> is specified.

C<open> carries options for the manager which are described here, but
may also have additional options for the folder type.  For a
description of the folder options, see the options to the constructor
L<Mail::Box::new()|Mail::Box/"Constructors"> for each type of mail box.

 -Option      --Default
  authenticate  'AUTO'
  create        false
  folder        $ENV{MAIL}
  folderdir     '.'
  type          <first, usually 'mbox'>

=over 2

=item authenticate => $type|\@types|'AUTO'

The C<$type> of authentication to be used, or an ARRAY of C<@types> which the
client prefers.  The server may provide preferences as well, and that
order will be kept.  This option is only supported by a small subset of
folder types, especially by POP and IMAP.

=item create => BOOLEAN

Create the folder if it does not exist. By default, this is not done.
The C<type> option specifies which type of folder is created.

=item folder => $name|$url

Which folder to open, specified by C<$name> or special C<$url>.
The URL format is composed as

  type://username:password@hostname:port/foldername

Like real URLs, all fields are optional and have smart defaults, as long
as the string starts with a known folder type.  Far
from all folder types support all these options, but at least they are
always split-out.  Be warned that special characters in the password should
be properly url-encoded.

When you specify anything which does not match the URL format, it is
passed directly to the C<new> method of the folder which is opened.

=item folderdir => DIRECTORY

The directory where the folders are usually stored.

=item type => $foldertypename|$foldertype

Specify the type of the folder.  If you do not specify this option while
opening a folder for reading, the manager checks all registered folder
types in order for the ability to open the folder. If you open a new
folder for writing, then the default will be the most recently registered
type. (If you add more than one type at once, the first of the list is
used.)

Currently, the types are C<mbox>, C<mh>, C<maildir>, C<pop3>, C<pop3s>,
C<imap4>, and C<imap4s>.  You may also use names C<pop>, C<pops>, C<imap>,
and C<imaps>.

=back

» example: opening folders via the manager

  my $jack  = $manager->open(folder => '=jack', type => 'mbox');

  my $rcvd  = $manager->open('myMail',
     type => 'Mail::Box::Mbox', access => 'rw');

  my $inbox = $manager->open('Inbox')
     or die "Cannot open Inbox.\n";

  my $pop   = 'pop3://myself:secret@pop3.server.com:120/x';
  my $send  = $manager->open($url);

  my $send  = $manager->open(folder => '/x',
    type => 'pop3', username => 'myself', password => 'secret'
    server_name => 'pop3.server.com', server_port => '120');

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

Returns a list of all open folders.

=back

=head2 Manage existing folders

=over 4

=item $obj-E<gt>B<delete>($foldername, %options)

Remove the named folder.  The C<%options> are the same as those for L<open()|Mail::Box::Manager/"Manage open folders">.

The deletion of a folder can take some time.  Dependent on the type of
folder, the folder must be read first.  For some folder-types this will
be fast.

 -Option   --Default
  recursive  <folder's default>

=over 2

=item recursive => BOOLEAN

Some folder can only be recursively deleted, other have more flexibility.

=back

=back

=head2 Move messages to folders

=over 4

=item $obj-E<gt>B<appendMessage>( [$folder|$foldername], $messages, %options )

Append one or more messages to a folder (therefore, an C<appendMessages()>
is defined as well). You may specify a C<$foldername> or an opened folder
as the first argument. When the name is that of an open folder, it is
treated as if the folder-object was specified, and not directly access
the folder-files.  You may also specify the foldername as part of the
options list.

If a message is added to an already opened folder, it is only added to
the structure internally in the program.  The data will not be written to
disk until a write of that folder takes place.  When the name of an
unopened folder is given, the folder is opened, the messages stored on
disk, and then the folder is closed.

A message must be an instance of a L<Mail::Message|Mail::Message>.  The actual message
type does not have to match the folder type--the folder will try to
resolve the differences with minimal loss of information.  The coerced
messages (how the were actually written) are returned as list.

The C<%options> is a list of key/values, which are added to (overriding)
the default options for the detected folder type.

» example: 

  $mgr->appendMessage('=send', $message, folderdir => '/');
  $mgr->appendMessage($received, $inbox->messages);

  my @appended = $mgr->appendMessages($inbox->messages, folder => 'Drafts');
  $_->label(seen => 1) for @appended;

=item $obj-E<gt>B<copyMessage>( [$folder|$foldername], @messages, %options )

Copy C<@messages> from one folder into another folder.  If the destination
folder is already opened, L<Mail::Box::copyTo()|Mail::Box/"The folder"> is used.  Otherwise,
L<Mail::Box::appendMessages()|Mail::Box/"The folder"> is called.

You need to specify a folder's name or folder object as the first
argument, or in the options list.  The options are the same as those
which can be specified when opening a folder.

 -Option--Default
  share   false

=over 2

=item share => BOOLEAN

Try to share the physical storage of the messages.  The folder types
may be different, but it all depends on the actual folder where the
message is copied to.  Silently ignored when not possible to share.

=back

» example: 

  my $drafts = $mgr->open(folder => 'Drafts');
  my $outbox = $mgr->open(folder => 'Outbox');
  $mgr->copyMessage($outbox, $drafts->message(0));

  my @messages = $drafts->message(1,2);
  $mgr->copyMessage('=Trash', @messages,
     folderdir => '/tmp', create => 1);

  $mgr->copyMessage($drafts->message(1), create => 1,
     folder => '=Drafts' folderdir => '/tmp');

=item $obj-E<gt>B<moveMessage>( [$folder|$foldername], @messages, %options )

Move C<@messages> from one C<$folder> to another.

BE WARNED that removals from a folder only take place when the folder
is closed, so the message is only flagged to be deleted in the opened
source folder.

BE WARNED that message labels may get lost when a message is moved from
one folder type to an other.  An attempt is made to translate labels,
but there are many differences in interpretation by applications.

  $mgr->moveMessage($received, $inbox->message(1))

is equivalent to

  $mgr->copyMessage($received, $inbox->message(1), share => 1);
  $inbox->message(1)->delete;

 -Option--Default
  share   true

=over 2

=item share => BOOLEAN

=back

=back

=head2 Manage message threads

=over 4

=item $obj-E<gt>B<discoverThreads>( [@folders], %options )

Create a new L<Mail::Box::Thread::Manager|Mail::Box::Thread::Manager> object which collects the message
threads found in the combined specified C<@folders>.

All other C<%options> are passed to L<Mail::Box::Thread::Manager::new()|Mail::Box::Thread::Manager/"METHODS">.

 -Option       --Default
  folders        <positional folder arguments>
  threader_type  Mail::Box::Thread::Manager

=over 2

=item folders => \@folders

As alternative for positional parameters to select the C<@folders>, you can also
pass them via this named parameter.

=item threader_type => CLASS

=back

» example: 

  my $t2 = $mgr->discoverThreads($inbox);
  my $t3 = $mgr->discoverThreads($inbox, $send);
  my $t1 = $mgr->discoverThreads(folders => [ $inbox, $send ]);

=back

=head2 Internals

=over 4

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

Try to decompose a folder name which is specified as C<$url> (see open())
into separate options.  Special characters like @-sign, colon, and slash
used in the user or password parts must be passed C<$url>-encoded.

=item $obj-E<gt>B<toBeThreaded>($folder, $messages)

Signal to the manager that all thread managers which are using the
specified folder must be informed that new messages are
coming in.

=item $obj-E<gt>B<toBeUnthreaded>($folder, $messages)

Signal to the manager that all thread managers which are using the
specified folder must be informed that new messages are
or going out.

=back

=head2 Error handling

Extends L<"Error handling" in Mail::Reporter|Mail::Reporter/"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::Reporter|Mail::Reporter/"Cleanup">.

=over 4

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

Inherited, see L<Mail::Reporter/"Cleanup">

=back

=head1 DETAILS

On many places in the documentation you can read that it is useful to
have a manager object.  There are two of them: the L<Mail::Box::Manager|Mail::Box::Manager>,
which maintains a set of open folders, and an extension of it: the
L<Mail::Box::Manage::User|Mail::Box::Manage::User>.

=head2 Managing open folders

It is useful to start your program by creating a folder manager object,
an L<Mail::Box::Manager|Mail::Box::Manager>.  The object takes a few burdons from your neck:

=over 4

=item * autodetect the type of folder which is used.

This means that your application can be fully folder type independent.

=item * autoload the required modules

There are so many modules involved in MailBox, that it is useful to
have some lazy autoloading of code.  The manager knows which modules
belong to which type of folder.

=item * avoid double openings

Your programming mistakes may cause the same folder to be opened twice.
The result of that could be very destructive.  Therefore, the manager
keeps track on all open folders and avoids the same folder to be opened
for the second time.

=item * close folders at clean-up

When the program is ending, the manager will cleanly close all folders
which are still open.  This is required, because the autodestruct
sequence of Perl works in an unpredicatable order.

=item * message thread detection

MailBox can discover message threads which span multiple folders. Any set
of open folders may be grouped in a tree of replies on replies on replies.
When a folder is closed, it will automatically be removed from the threads,
and a new folder can dynamically be added to the structure.

=back

The manager is really simplifying things, and should therefore be the
base of all programs. However, it is possible to write useful programs
without it.

=head2 Managing a user

One step further is the L<Mail::Box::Manage::User|Mail::Box::Manage::User> object (since MailBox
v2.057), which not only keeps track on open folders, but also collects
information about not-open folders.

The user class is, as the name says, targeted on managing one single user.
Where the L<Mail::Box::Manager|Mail::Box::Manager> will open any set of folder files, probably
from multiple users, the user class want one root folder directory.

In many aspects, the user manager simplifies the task for user-based servers
and other user-centric applications by setting smart defaults.

=head1 DIAGNOSTICS

=over 4

=item Error: Folder $name is not a Mail::Box; cannot add a message.

The folder where the message should be appended to is an object which is
not a folder type which extends L<Mail::Box|Mail::Box>.  Probably, it is not a folder
at all.
Cast by C<appendMessage()>

=item Error: Use appendMessage() to add messages which are not in a folder.

You do not need to copy this message into the folder, because you do
not share the message between folders.
Cast by C<copyMessage()>

=item Warning: Use moveMessage() or copyMessage() to move between open folders.

The message is already part of a folder, and now it should be appended
to a different folder.  You need to decide between copy or move, which
both will clone the message (not the body, because they are immutable).
Cast by C<appendMessage()>

=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: failed for folder default $class: $@

Cast by C<open()>

=item Error: folder $name does not exist, failed opening $type.

The folder does not exist and creating is not permitted (see
L<open(create)|Mail::Box::Manager/"Manage open folders">) or did not succeed.  When you do not have sufficient
access rights to the folder (for instance wrong password for POP3),
this warning will be produced as well.

The manager tried to open a folder of the specified type.  It may help
to explicitly state the type of your folder with the C<type> option.
There will probably be another warning or error message which is related
to this report and provides more details about its cause.  You may also
have a look at L<new(autodetect)|Mail::Box::Manager/"METHODS"> and L<new(folder_types)|Mail::Box::Manager/"METHODS">.
Cast by C<open()>

=item Error: folder $name is already open.

You cannot ask the manager for a folder which is already open. In some
older releases (before MailBox 2.049), this was permitted, but then
behaviour changed, because many nasty side-effects are to be expected.
For instance, an L<Mail::Box::update()|Mail::Box/"The folder"> on one folder handle would
influence the second, probably unexpectedly.
Cast by C<open()>

=item Warning: folder type $type is unknown, using autodetect.

The specified folder type (see L<open(type)|Mail::Box::Manager/"Manage open folders">, possibly derived from
the folder name when specified as url) is not known to the manager.
This may mean that you forgot to require the L<Mail::Box|Mail::Box> extension
which implements this folder type, but probably it is a typo.  Usually,
the manager is able to figure-out which type to use by itself.
Cast by C<open()>

=item Error: illegal folder URL '$url'.

The folder name was specified as URL, but not according to the syntax.
See L<decodeFolderURL()|Mail::Box::Manager/"Internals"> for an description of the syntax.
Cast by C<open()>

=item Error: no foldername specified to open.

L<open()|Mail::Box::Manager/"Manage open folders"> needs a folder name as first argument (before the list of options),
or with the C<folder> option within the list.  If no name was found, the
MAIL environment variable is checked.  When even that does not result in
a usable folder, then this error is produced.  The error may be caused by
an accidental odd-length option list.
Cast by C<open()>

=item Error: threader $class is not derived from $base.

Cast by C<discoverThreads()>

=item Error: unusable threader $class: $@

Cast by C<discoverThreads()>

=item Warning: will never create a folder $name without having write access.

You have set L<open(create)|Mail::Box::Manager/"Manage open folders">, but only want to read the folder.  Create is
only useful for folders which have write or append access modes
(see L<Mail::Box::new(access)|Mail::Box/"Constructors">).
Cast by C<open()>

=item Error: you need to pass a $base derived threader, got $class.

Cast by C<discoverThreads()>

=back

=head1 SEE ALSO

This module is part of Mail-Box version 4.02,
built on April 10, 2026. Website: F<http://perl.overmeer.net/CPAN/>

=head1 LICENSE

For contributors see file ChangeLog.

This software is copyright (c) 2001-2026 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.

