The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

Mail::Box - Manage a message-folder.

CLASS HIERARCHY

 Mail::Box
 is a Mail::Reporter

SYNOPSIS

 use Mail::Box::Manager;
 my $mgr    = Mail::Box::Manager->new;
 my $folder = $mgr->open(folder => $ENV{MAIL}, ...);
 print $folder->name;

 # Get the first message.
 print $folder->message(0);

 # Delete the third message
 $folder->message(3)->delete;

 # Get the number of undeleted messages in scalar context.
 my $emails = $folder->messages;

 # Iterate over the messages.
 foreach ($folder->messages) {...}     # all messages
 foreach (@$folder) {...}              # all messages

 $folder->addMessage(new Mail::Box::Message(...));

Tied-interface: (See Mail::Box::Tie)

 tie my(@inbox), 'Mail::Box::Tie::ARRAY', $inbox;
 $inbox[3]->print        # same as $folder->message(3)->print

 tie my(%inbox), 'Mail::Box::Tie::HASH', $inbox;
 $inbox{$msgid}->print   # same as $folder->messageId($msgid)->print

DESCRIPTION

A Mail::Box::Manager creates Mail::Box objects. But you already knew, because you started with the Mail::Box-Overview manual page. That is obligatory reading, sorry!

Mail::Box is the base-class for accessing various types of mail-folder organizational structures in a uniform way. The various folder types vary on how they store their messages. For example, a folder may store many messages in a single file, or store each message in a separate file in a directory. Similarly, there may be different techniques for locking the folders.

The Mail::Box is used to get Mail::Box::Message objects from the mailbox. Applications then usually use information or add information to the message object. For instance, the application can set a flag which indicates whether a message has been replied to or not. In addition, applications can extend Mail::Box::Message by deriving from it. See Mail::Box::Message and its derived classes for more information.

METHOD INDEX

The general methods for Mail::Box objects:

      addMessage  MESSAGE                  message INDEX [,MESSAGE]
      addMessages MESSAGE [, MESS...       messageId MESSAGE-ID [,MESS...
      allMessageIds                        messages
      close OPTIONS                        modified [BOOLEAN]
      create FOLDERNAME [, OPTIONS]        name
      current [NUMBER|MESSAGE|MES...       new OPTIONS
      delete                               openSubFolder NAME [,OPTIONS]
   MR errors                            MR report [LEVEL]
      find MESSAGE-ID                   MR reportAll [LEVEL]
      listSubFolders OPTIONS            MR trace [LEVEL]
      locker                            MR warnings
   MR log [LEVEL [,STRINGS]]               writeable

The extra methods for extension writers:

   MR AUTOLOAD                          MR notImplemented
      DESTROY                              organization
      appendMessages OPTIONS               read OPTIONS
      clone OPTIONS                        readMessages
      coerce MESSAGE                       scanForMessages MESSAGE, ME...
      determineBodyType MESSAGE, ...       sort PREPARE, COMPARE, LIST
      folderdir [DIR]                      storeMessage MESSAGE
      foundIn [FOLDERNAME], OPTIONS        timespan2seconds TIME
   MR inGlobalDestruction                  toBeThreaded MESSAGES
   MR logPriority LEVEL                    toBeUnthreaded MESSAGES
   MR logSettings                          write OPTIONS

Prefixed methods are described in MR = Mail::Reporter.

METHODS

new OPTIONS

(Class method) Open a new folder. OPTIONS is a list of labeled parameters defining options for the mailboxes. Some options pertain to Mail::Box, and others are added by sub-classes. The list below describes all the options provided by Mail::Box and the various sub-classes distributed with it. Those provided by the Mail::Box class are described in detail here. For a description of the other options, see the documentation for the respective sub-class.

 OPTION            DEFINED BY         DEFAULT
 access            Mail::Box          'r'
 create            Mail::Box          0
 folder            Mail::Box          $ENV{MAIL}
 folderdir         Mail::Box          undef
 head_wrap         Mail::Box          72
 extract           Mail::Box          10kb
 log               Mail::Reporter     'WARNINGS'
 remove_when_empty Mail::Box          1
 save_on_exit      Mail::Box          1
 trace             Mail::Reporter     'WARNINGS'
 trusted           Mail::Box          <depends on folder location>

Only useful to write extension to Mail::Box, for instance within the implementation of Mail::Box::Mbox. Common users of folders you will not specify these:

 OPTION            DEFINED BY         DEFAULT
 body_type         Mail::Box::Mbox    <see below, folder specific>
 body_delayed_type Mail::Box          'Mail::Message::Body::Delayed'
 coerce_options    Mail::Box          []
 head_type         Mail::Box          'Mail::Message::Head::Complete'
 locker            Mail::Box          undef
 lock_type         Mail::Box          'Mail::Box::Locker::DotLock'
 lock_file         Mail::Box          foldername.'.lock'
 lock_timeout      Mail::Box          1 hour
 lock_wait         Mail::Box          10 seconds
 multipart_type    Mail::Box          'Mail::Message::Body::Multipart'
 manager           Mail::Box          undef
 message_type      Mail::Box          'Mail::Box::Message'
 organization      Mail::Box          'FILE'

The normal usage options for Mail::Box::new() are:

  • access => MODE

    Access-rights to the folder. MODE can be read-only ("r"), append ("a"), and read-write ("rw"). Folders are opened for read-only ("r") by default.

    These modes have nothing in common with the modes actually used to open the folder-files within this module. For instance, if you specify "rw", and open the folder, only read-permission on the folder-file is required. Writing to a folder will always create a new file to replace the old one.

  • folder => FOLDERNAME

    Which folder to open (for reading or writing). When used for reading (the access option set to "r" or "a") the mailbox should already exist and be readable. The file or directory of the mailbox need not exist if it is opened for reading and writing ("rw"). Write-permission is checked when opening an existing mailbox.

  • folderdir => DIRECTORY

    Where are folders written by default? You can specify a folder-name preceeded by = to explicitly state that the folder is located below this directory. For example: if folderdir => '/tmp' and folder => '=abc', then the name of the folder-file is '/tmp/abc'.

  • head_wrap => INTEGER

    Fold the structured headers to the specified length (defaults to 72). Folding is disabled when 0 is specified.

  • save_on_exit => BOOL

    Sets the policy for saving the folder when it is closed. (See the close() method.) A folder can be closed manually or via a number of implicit methods (including when the program is terminated). By default this option is set to TRUE.

  • remove_when_empty => BOOLEAN

    Determines whether or not to remove the folder file or directory automatically when the write would result in a folder without sub-folders or messages. This option is dependent on the type of folder, and is true by default.

  • trusted => BOOLEAN

    Flags whether to trust the data in the folder or not. Folders which reside in your folderdir will be trusted by default, but folders which are outside it will need some extra checking.

    If you do not check encodings of received messages, you may print text messages with binary data to the screen. This is a security risk.

To control delay-loading of messages, as well the headers as the bodies, the next three option specify the algorithm. extract determines whether we want delay-loading, and body_type determines which kind of body we want when we decide to parse it.

  • extract => INTEGER

  • extract => CODE

  • extract => METHOD

  • extract => 'LAZY'|'ALWAYS'

    When the header of a message is read, you may want to postpone the reading of the body. Header information is more often needed than the body data, so why parse it always together? The cost of delaying is not too high.

    If you supply a number to this option, bodies of those messages with a total size less than that number will be extracted from the folder only when nessesary.

    If you supply a code reference, that subroutine is called every time that the extraction mechanism wants to determine whether to parse the body or not. The subroutine is called with the following arguments:

        $code->(FOLDER, HEAD)

    where FOLDER is a reference to the folder we are reading. HEAD refers to a Mail::Message::Head. The routine must return a true value (extract now) or a false value (be lazy, do not parse yet). Think about using the guessBodySize() and guessTimestamp() on the header to determine your choice.

    The third possibility is to specify the NAME of a method. In that case, for each message is called:

       FOLDER->NAME(HEAD)

    Where each parameter has the same meaning as described above.

    The fourth way to use this parameter involves constants: with 'LAZY' all messages will be delayed. With 'ALWAYS' you force unconditional loading.

    Examples:

        $folder->new(extract => 'LAZY');
        $folder->new(extract => 10000);
        $folder->new(extract => sub
           { my ($f, $head) = @_;
             my $size = $head->guessBodySize;
             defined $size ? $size < 10000 : 1
           }); #same
    
        $folder->new(extract => 'sent_by_me');
        sub Mail::Box::send_by_me($$)
        {   my ($self, $header) = @_;
            $header->get('from') =~ m/\bmy\@example.com\b/i;
        }
  • body_type => CLASS|CODE

    When messages are read from a folder-file, the headers will be stored in a head_type-object. For the body, however, there is a range of choices about type, which are all described in the Mail::Message::Body manual page.

    Specify a CODE-reference which produces the body-type to be created, or a CLASS of the body which is used when the body is not a multipart. In case of a code, the header-structure is passed as first argument to the routine.

    Do not return a delayed body-type (like ::Delayed), because that is determined by the extract() method. Do always check for multipart messages, otherwise your parts (attachments) will not be split-up.

    For instance:

       $mgr->open(body_type => \&which_body);
    
       sub which_body($) {
           my $head = shift;
           my $size = $head->guessBodySize || 0;
           my $type = $size > 100000 ? 'File' : 'Lines';
           "Mail::Message::Body::$type";
       }

    The default depends on the mail-folder type, although the general default is Mail::Message::Body::Lines. Please check the applicatable manual pages.

Options for extension-writers are:

  • coerce_options => ARRAY

    Keep configuration information for messages which are coerced into the specified folder type, starting with a different folder type (or even no folder at all).

    Messages which are coerced are always fully read, so this kind of information does not need to be kept here.

  • head_type => CLASS

    The type of header which contains all header information. Must extend Mail::Message::Head::Complete.

  • lock_type => CLASS|STRING

    The type of the locker object. This may be the full name of a CLASS which extends Mail::Box::Locker, or one of the known locker types 'DotLock', 'File', 'NFS', or 'NONE'.

  • locker => OBJECT

    An OBJECT which extends Mail::Box::Locker, and will handle folder locking replacing the default lock behavior.

  • manager => MANAGER

    A reference to the object which manages this folder -- typically an Mail::Box::Manager instance.

  • message_type => CLASS

    What kind of message-objects are stored in this type of folder. The default is Mail::Box::Message (which is a sub-class of Mail::Message). The class you offer must be an extension of Mail::Box::Message.

  • organization => 'FILE' | 'DIRECTORY'

    Tells whether a folder is one file containing many messages (like Mbox-folders) or one directory per folder, a message per file (like MH-folders).

close OPTIONS

lose the folder, optionally writing it. close takes the same options as write, as well as a few others:

WARNING: When moving messages from one folder to another, be sure to write the destination folder before writing and closing the source folder. Otherwise you may lose data if the system crashes or if there are software problems.

  • write => 'ALWAYS'|'NEVER'|'MODIFIED'

    Specifies whether the folder should be written. As could be expected, 'ALWAYS' means always (even if there are no changes), 'NEVER' means that changes to the folder will be lost, and 'MODIFIED' (which is the default) only saves the folder if there are any changes.

  • force => BOOL

    Override the access setting specified when the folder was opened. This option only has an effect if its value is TRUE. NOTE: Writing to the folder may not be permitted by the operating system, in which case even force will not help.

locker

Returns the locking object.

delete

Remove the specified folder file or folder directory (depending on the type of folder) from disk. Of course, THIS IS DANGEROUS: you "may" lose data.

WARNING: When moving messages from one folder to another, be sure to write the destination folder before deleting the source folder. Otherwise you may lose data if the system crashes or if there are software problems.

Examples:

   my $folder = Mail::Box::File->new(folder => 'InBox');
   $folder->delete;
openSubFolder NAME [,OPTIONS]

Open (or create, if it does not exist yet) a new subfolder in an existing folder.

Example:

    my $folder = Mail::Box::Mbox->new(folder => '=Inbox');
    my $sub    = $folder->openSubFolder('read');
name

Returns the name of the folder. What the name represents depends on the actual type of mailbox used.

Example:

   print $folder->name;
writeable

Checks whether the current folder is writeable.

Example:

    $folder->addMessage($msg) if $folder->writeable;
modified [BOOLEAN]

modified checks if the folder is modified, optionally after setting the flag. A folder is modified when any of the messages is to be deleted, any of the messages has changed, or messages are added after the folder was read from file.

message INDEX [,MESSAGE]

Get or set a message with on a certain index. Messages which are flagged for deletion are counted. Negative indexes start at the end of the folder.

See the activeMessage method to index message that are not marked for deletion.

Examples:

    my $msg = $folder->message(3);
    $folder->message(3)->delete;   # status changes to `deleted'
    $folder->message(3, $msg);
    print $folder->message(-1);    # last message.
messageId MESSAGE-ID [,MESSAGE]

With one argument, returns the message in the folder with the specified MESSAGE-ID. If a reference to a message object is passed as the optional second argument, the message is first stored in the folder, replacing any existing message whose message ID is MESSAGE-ID. (The message ID of MESSAGE need not match MESSAGE-ID.)

The MESSAGE-ID may still be in angles, which will be stripped. In that case blanks (which origin from header line folding) are removed too. Other info around the angles will be removed too.

WARNING: when the message headers are delay-parsed, the message might be in the folder but not yet parsed into memory. In this case, use the find() method instead of messageId if you really need a thorough search.

Examples:

   my $msg = $folder->messageId('<complex-message.id>');
   $folder->messageId("<complex-message\n.id>", $msg);
   my $msg = $folder->messageId('complex-message.id');
   my $msg = $folder->messageId('garbage <complex-message.id> trash');
find MESSAGE-ID

Like messageId(), this method searches for a message with the MESSAGE-ID, returning the corresponding message object. However, find() will cause unparsed message in the folder to be parsed until the message-id is found. The folder will be scanned back to front.

messages

Returns all messages. In scalar context, it returns the number of undeleted messages in the folder. Dereferencing a folder to an array is overloaded to call this method.

Examples:

    foreach my $message ($folder->messages) {...}
    foreach my $message (@$folder) {...}
    my @messages   = $folder->messages;
    my @not_deleted= grep {! $_->deleted} $folder->messages;
    my $nr_of_msgs = $folder->messages;
    $folder->[2];   # third message
allMessageIds

Returns a list of all message-ids in the folder, including those of messages which are to be deleted.

For some folder-types (like MH), this method may cause all message-files to be read. See their respective manual pages.

Examples:

    foreach my $id ($folder->allMessageIds) {
        $folder->messageId($id)->print;
    }
addMessage MESSAGE
addMessages MESSAGE [, MESSAGE, ...]

Add a message to the folder. A message is usually a Mail::Box::Message object or a sub-class thereof. The message shall not be in an other folder, when you use this method. In case it is, use moveMessage() or copyMessage().

Messages with id's which already exist in this folder are not added.

Examples:

   $folder->addMessage($msg);
   $folder->addMessages($msg1, $msg2, ...);
current [NUMBER|MESSAGE|MESSAGE-ID]

Some mail-readers keep the current message, which represents the last used message. This method returns [after setting] the current message. You may specify a NUMBER, to specify that that message number is to be selected as current, or a MESSAGE/MESSAGE-ID (as long as you are sure that the header is already loaded, otherwise they are not recognized).

Examples:

   $folder->current(0);
   $folder->current($message);
create FOLDERNAME [, OPTIONS]

(Class method) Create a folder. If the folder already exists, it will be left unchanged. As options, you may specify:

  • folderdir => DIRECTORY

    When the foldername is preceeded by a =, the folderdir directory will be searched for the named folder.

listSubFolders OPTIONS

(Class and Instance method) List the names of all sub-folders to this folder. Use these names in openSubFolder, to open these folders on a mailbox type way. For Mbox-folders, sub-folders are simutated.

 OPTION            DEFINED BY         DEFAULT
 folder            Mail::Box          <obligatory>
 folderdir         Mail::Box          <from object>
 check             Mail::Box          <false>
 skip_empty        Mail::Box          <false>

The options general to all folder types are:

  • folder => FOLDERNAME

    The folder whose sub-folders should be listed.

  • folderdir => DIRECTORY

  • check => BOOL

    Specifies whether empty folders (folders which currently do not contain any messages) should be included. It may not be useful to open empty folders, but saving to them is useful.

  • skip_empty => BOOL

    Shall empty folders (folders which currently do not contain any messages) be included? Empty folders are not useful to open, but may be useful to save to.

Examples:

   my $folder = $mgr->open('=in/new');
   my @subs = $folder->listSubFolders;

   my @subs = Mail::Box::Mbox->listSubFolders(folder => '=in/new');
   my @subs = Mail::Box::Mbox->listSubFolders; # toplevel folders.

METHODS for extensions writers

The next set of methods is for normal use, but only for people who write entensions (develop new folder types).

clone OPTIONS

Create a new folder, with the same settings as this folder. One of the specified options must be new folder to be opened. Other options overrule those of the folder where this is a clone from.

Example:

   my $folder2 = $folder->clone(folder => '=jan');
read OPTIONS

Read messages from the folder into memory. The OPTIONS are folder specific.

NOTE: if you are copying messages from one folder to another, use addMessages instead of read.

determineBodyType MESSAGE, HEAD

Determine which kind of body will be created for this message when reading the folder initially.

storeMessage MESSAGE

Store the message in the folder without the checks as performed by addMessage.

write OPTIONS

Write the data to disk. The folder is returned if successful. To write to a different file, you must first create a new folder, then move the messages, and then write the folder.

WARNING: When moving messages from one folder to another, be sure to write the destination folder before writing and closing the source folder. Otherwise you may lose data if the system crashes or if there are software problems.

 OPTION            DEFINED BY         DEFAULT
 force             Mail::Box          <true>
 head_wrap         Mail::Box          72
 keep_deleted      Mail::Box          <false>
 save_deleted      Mail::Box          <false>
  • force => BOOL

    Override write-protection by the access option while opening the folder (whenever possible, it may still be blocked by the operating system).

  • keep_deleted => BOOL

    Do not remove messages which were flagged to be deleted from the folder from memory, but do remove them from disk.

  • save_deleted => BOOL

    Do also write messages which where flagged to be deleted to their folder. The flag is conserved (when possible), which means that the next write may remove them for real.

coerce MESSAGE

Coerce the MESSAGE to be of the correct type to be placed in the folder. You are not may specify Mail::Internet and MIME::Entity here: they will be translated into Mail::Message messages first.

organization

Return whether a folder is organized as one 'FILE' with many messages or a 'DIRECTORY' with one message per file.

folderdir [DIR]

Get or set the directory which is used to store mail-folders by default.

Examples:

   print $folder->folderdir;
   $folder->folderdir("$ENV{HOME}/nsmail");
readMessages

Called by read() to actually read the messages from one specific folder type. The read() organizes the general activities.

writeMessages

Called by write() to actually write the messages from one specific folder type. The write() organizes the general activities.

appendMessages OPTIONS

(Class method) Append one or more messages to an unopened folder. Usually, this method is called by the Mail::Box::Manager (its method appendMessage()), in which case the correctness of the folder type is checked.

This method takes a list of labeled parameters, which may contain any option which can be used when a folder is opened (most importantly folderdir). Two aditional parameters shall be specified:

  • folder => FOLDERNAME

    The name of the folder to which the messages are to be appended. The folder implementation will avoid opening the folder when possible, because this is resource consuming.

  • message => MESSAGE

  • messages => ARRAY-OF-MESSAGES

    One reference to a MESSAGE or a reference to an ARRAY of MESSAGEs, which may be of any type. The messages will be first coerced into the correct message type to fit in the folder, and then will be added to it.

Examples:

    my $message = Mail::Message->new(...);
    Mail::Box::Mbox->appendMessages
      ( folder    => '=xyz'
      , message   => $message
      , folderdir => $ENV{FOLDERS}
      );

better:

    my Mail::Box::Manager $mgr;
    $mgr->appendMessages($message, folder => '=xyz');
foundIn [FOLDERNAME], OPTIONS

(class method) Determine if the specified folder is of the type handled by the folder class. This method is extended by each folder sub-type.

The FOLDERNAME specifies the name of the folder, as is specified by the application. You need to specified the folder option when you skip this first argument.

OPTIONS is a list of extra information for the request. Read the documentation for each type of folder for folder-specific options, but each folder class will at least support the folderdir option:

  • folderdir => DIRECTORY

    The location where the folders of this class are stored by default. If the user specifies a name starting with a =, that indicates that the folder is to be found in this default DIRECTORY.

Examples:

   Mail::Box::Mbox->foundIn('=markov', folderdir => "$ENV{HOME}/Mail");
   Mail::Box::MH->foundIn(folder => '=markov');
toBeThreaded MESSAGES
toBeUnthreaded MESSAGES

The specified message is ready to be included in (or remove from) a thread. This will be passed on to the mail-manager, which keeps an overview on which thread-detection objects are floating around.

scanForMessages MESSAGE, MESSAGE-IDS, TIMESTAMP, WINDOW

The MESSAGE which is known contains references to messages before it which are not found yet. But those messages can be in the same folder. Scan back in this folder for the MESSAGE-IDS (which may be one string or a reference to an array of strings). The TIMESTAMP and WINDOW (see options in new()) limit the search.

sort PREPARE, COMPARE, LIST

(class method) Implements a general sort, with preparation phase. First prepare a value foreach each element of the list by calling the specified routine with the element as first argument. Then sort it based on the COMPARE routine. In this case, the two argumements to be compared are parsed.

timespan2seconds TIME

TIME is a string, which starts with a float, and then one of the words 'hour', 'hours', 'day', 'days', 'week', or 'weeks'. For instance:

    '1 hour'
    '4 weeks'
DESTROY

This method is called by Perl when an folder-object is no longer accessible by the rest of the program.

SEE ALSO

Mail::Box-Overview

AUTHOR

Mark Overmeer (mailbox@overmeer.net). All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

VERSION

This code is beta, version 2.00_18.

Copyright (c) 2001 Mark Overmeer. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

1 POD Error

The following errors were encountered while parsing the POD:

Around line 1517:

You forgot a '=back' before '=head1'