1Mail::Box(3) User Contributed Perl Documentation Mail::Box(3)
2
3
4
6 Mail::Box - manage a mailbox, a folder with messages
7
9 Mail::Box
10 is a Mail::Reporter
11
12 Mail::Box is extended by
13 Mail::Box::Dir
14 Mail::Box::File
15 Mail::Box::Net
16
18 use Mail::Box::Manager;
19 my $mgr = Mail::Box::Manager->new;
20 my $folder = $mgr->open(folder => $ENV{MAIL}, ...);
21 print $folder->name;
22
23 # Get the first message.
24 print $folder->message(0);
25
26 # Delete the third message
27 $folder->message(3)->delete;
28
29 # Get the number of messages in scalar context.
30 my $emails = $folder->messages;
31
32 # Iterate over the messages.
33 foreach ($folder->messages) {...} # all messages
34 foreach (@$folder) {...} # all messages
35
36 $folder->addMessage(Mail::Box::Message->new(...));
37
38 Tied-interface:
39
40 tie my(@inbox), 'Mail::Box::Tie::ARRAY', $inbox;
41
42 # Four times the same:
43 $inbox[3]->print; # tied
44 $folder->[3]->print; # overloaded folder
45 $folder->message(3)->print; # usual
46 print $folder->[3]; # overloaded message
47
48 tie my(%inbox), 'Mail::Box::Tie::HASH', $inbox;
49
50 # Twice times the same
51 $inbox{$msgid}->print; # tied
52 $folder->messageId($msgid)->print;# usual
53
55 A Mail::Box::Manager creates "Mail::Box" objects. But you already
56 knew, because you started with the Mail::Box-Overview manual page.
57 That page is obligatory reading, sorry!
58
59 "Mail::Box" is the base class for accessing various types of mailboxes
60 (folders) in a uniform manner. The various folder types vary on how
61 they store their messages, but when some effort those differences could
62 be hidden behind a general API. For example, some folders store many
63 messages in one single file, where other store each message in a
64 separate file within the same directory.
65
66 No object in your program will be of type "Mail::Box": it is only used
67 as base class for the real folder types. "Mail::Box" is extended by
68
69 Extends "DESCRIPTION" in Mail::Reporter.
70
72 overload: ""
73 (stringification) The folder objects stringify to their name. This
74 simplifies especially print statements and sorting a lot.
75
76 example: use overloaded folder as string
77
78 # Three lines with overloading: resp. cmp, @{}, and ""
79 foreach my $folder (sort @folders)
80 { my $msgcount = @$folder;
81 print "$folder contains $msgcount messages\n";
82 }
83
84 overload: @{}
85 When the folder is used as if it is a reference to an array, it
86 will show the messages, like messages() and message() would do.
87
88 example: use overloaded folder as array
89
90 my $msg = $folder->[3];
91 my $msg = $folder->message(3); # same
92
93 foreach my $msg (@$folder) ...
94 foreach my $msg ($folder->messages) ... # same
95
96 overload: cmp
97 (string comparison) folders are compared based on their name. The
98 sort rules are those of the build-in "cmp".
99
101 Extends "METHODS" in Mail::Reporter.
102
103 Constructors
104 Extends "Constructors" in Mail::Reporter.
105
106 Mail::Box->new(%options)
107 Open a new folder. A list of labeled %options for the mailbox can
108 be supplied. Some options pertain to Mail::Box, and others are
109 added by sub-classes.
110
111 To control delay-loading of messages, as well the headers as the
112 bodies, a set of *_type options are available. "extract" determines
113 whether we want delay-loading.
114
115 -Option --Defined in --Default
116 access 'r'
117 body_delayed_type Mail::Message::Body::Delayed
118 body_type <folder specific>
119 coerce_options []
120 create <false>
121 extract 10240
122 field_type undef
123 fix_headers <false>
124 folder $ENV{MAIL}
125 folderdir undef
126 head_delayed_type Mail::Message::Head::Delayed
127 head_type Mail::Message::Head::Complete
128 keep_dups <false>
129 lock_file undef
130 lock_timeout 1 hour
131 lock_type Mail::Box::Locker::DotLock
132 lock_wait 10 seconds
133 locker undef
134 log Mail::Reporter 'WARNINGS'
135 manager undef
136 message_type <folder-class>::Message
137 multipart_type Mail::Message::Body::Multipart
138 remove_when_empty <true>
139 save_on_exit <true>
140 trace Mail::Reporter 'WARNINGS'
141 trusted <depends on folder location>
142
143 access => MODE
144 Access-rights to the folder. Folders are opened for read-only
145 (which means write-protected) by default! MODE can be
146
147 'r': read-only (default)
148 'a': append
149 'rw': read-write
150 'd': delete
151
152 These MODE has no relation to the modes actually used to open the
153 folder files within this module. For instance, if you specify
154 "rw", and open the folder, only read permission on the folder-
155 file is required.
156
157 Be warned: writing a MBOX folder may create a new file to replace
158 the old folder. The permissions and owner of the file may get
159 changed by this.
160
161 body_delayed_type => CLASS
162 The bodies which are delayed: which will be read from file when
163 it is needed, but not before.
164
165 body_type => CLASS|CODE
166 When messages are read from a folder-file, the headers will be
167 stored in a "head_type" object. For the body, however, there is
168 a range of choices about type, which are all described in
169 Mail::Message::Body.
170
171 Specify a CODE-reference which produces the body-type to be
172 created, or a CLASS of the body which is used when the body is
173 not a multipart or nested. In case of a code reference, the
174 header structure is passed as first argument to the routine.
175
176 Do not return a delayed body-type (like "::Delayed"), because
177 that is determined by the "extract" option while the folder is
178 opened. Even delayed message will require some real body type
179 when they get parsed eventually. Multiparts and nested messages
180 are also outside your control.
181
182 For instance:
183
184 $mgr->open('InBox', body_type => \&which_body);
185
186 sub which_body($) {
187 my $head = shift;
188 my $size = $head->guessBodySize || 0;
189 my $type = $size > 100000 ? 'File' : 'Lines';
190 "Mail::Message::Body::$type";
191 }
192
193 The default depends on the mail-folder type, although the general
194 default is Mail::Message::Body::Lines. Please check the
195 applicable manual pages.
196
197 coerce_options => ARRAY
198 Keep configuration information for messages which are coerced
199 into the specified folder type, starting with a different folder
200 type (or even no folder at all). Messages which are coerced are
201 always fully read, so this kind of information does not need to
202 be kept here.
203
204 create => BOOLEAN
205 Automatically create the folder when it does not exist yet. This
206 will only work when access is granted for writing or appending to
207 the folder.
208
209 Be careful: you may create a different folder type than you
210 expect unless you explicitly specify
211 Mail::Box::Manager::open(type).
212
213 extract => INTEGER | CODE | METHOD | 'LAZY'|'ALWAYS'
214 Defines when to parse (process) the content of the message. When
215 the header of a message is read, you may want to postpone the
216 reading of the body: header information is more often needed than
217 the body data, so why parse it always together? The cost of
218 delaying is not too high, and with some luck you may never need
219 parsing the body.
220
221 If you supply an INTEGER to this option, bodies of those messages
222 with a total size less than that number will be extracted from
223 the folder only when necessary. Messages where the size (in the
224 "Content-Length" field) is not included in the header, like often
225 the case for multiparts and nested messages, will not be
226 extracted by default.
227
228 If you supply a CODE reference, that subroutine is called every
229 time that the extraction mechanism wants to determine whether to
230 parse the body or not. The subroutine is called with the
231 following arguments:
232
233 CODE->(FOLDER, HEAD)
234
235 where FOLDER is a reference to the folder we are reading. HEAD
236 refers to the Mail::Message::Head::Complete head of the message
237 at hand. The routine must return a "true" value (extract now) or
238 a "false" value (be lazy, do not parse yet). Think about using
239 the Mail::Message::Head::guessBodySize() and
240 Mail::Message::guessTimestamp() on the header to determine your
241 choice.
242
243 The third possibility is to specify the NAME of a method. In
244 that case, for each message is called:
245
246 FOLDER->NAME(HEAD)
247
248 Where each component has the same meaning as described above.
249
250 The fourth way to use this option involves constants: with "LAZY"
251 all messages will be delayed. With "ALWAYS" you enforce
252 unconditional parsing, no delaying will take place. The latter
253 is usuful when you are sure you always need all the messages in
254 the folder.
255
256 $folder->new(extract => 'LAZY'); # Very lazy
257 $folder->new(extract => 10000); # Less than 10kB
258
259 # same, but implemented yourself
260 $folder->new(extract => &large);
261 sub large($) {
262 my ($f, $head) = @_;
263 my $size = $head->guessBodySize;
264 defined $size ? $size < 10000 : 1
265 };
266
267 # method call by name, useful for Mail::Box
268 # extensions. The example selects all messages
269 # sent by you to be loaded without delay.
270 # Other messages will be delayed.
271 $folder->new(extract => 'sent_by_me');
272 sub Mail::Box::send_by_me($) {
273 my ($self, $header) = @_;
274 $header->get('from') =~ m/\bmy\@example.com\b/i;
275 }
276
277 field_type => CLASS
278 The type of the fields to be used in a header. Must extend
279 Mail::Message::Field.
280
281 fix_headers => BOOLEAN
282 Broken MIME headers usually stop the parser: all lines not parsed
283 are added to the body of the message. With this flag set, the
284 erroneous line is added to the previous header field and parsing
285 is continued. See
286 Mail::Box::Parser::Perl::new(fix_header_errors).
287
288 folder => FOLDERNAME
289 Which folder to open (for reading or writing). When used for
290 reading (the "access" option set to "r" or "a") the mailbox
291 should already exist and must be readable. The file or directory
292 of the mailbox need not exist if it is opened for reading and
293 writing ("rw"). Write-permission is checked when opening an
294 existing mailbox.
295
296 The folder name can be preceded by a "=", to indicate that it is
297 named relative to the directory specified in new(folderdir).
298 Otherwise, it is taken as relative or absolute path.
299
300 folderdir => DIRECTORY
301 Where are folders to be found by default? A folder-name may be
302 preceded by a equals-sign ("=", a "mutt" convension) to
303 explicitly state that the folder is located below the default
304 directory. For example: in case "folderdir => '/tmp'" and
305 "folder => '=abc'", the name of the folder-file is '/tmp/abc'.
306 Each folder type has already some default set.
307
308 head_delayed_type => CLASS
309 The headers which are delayed: which will be read from file when
310 it is needed, but not before.
311
312 head_type => CLASS
313 The type of header which contains all header information. Must
314 extend Mail::Message::Head::Complete.
315
316 keep_dups => BOOLEAN
317 Indicates whether or not duplicate messages within the folder
318 should be retained. A message is considered to be a duplicate if
319 its message-id is the same as a previously parsed message within
320 the same folder. If this option is false (the default) such
321 messages are automatically deleted, because it is considered
322 useless to store the same message twice.
323
324 lock_file => FILENAME
325 The name of the file which is used to lock. This must be
326 specified when locking is to be used.
327
328 lock_timeout => SECONDS
329 When the lock file is older than the specified number of SECONDS,
330 it is considered a mistake. The original lock is released, and
331 accepted for this folder.
332
333 lock_type => CLASS|STRING|ARRAY
334 The type of the locker object. This may be the full name of a
335 CLASS which extends Mail::Box::Locker, or one of the known locker
336 types "DotLock", "Flock", "FcntlLock", "Mutt", "NFS", "POSIX", or
337 "NONE". If an ARRAY is specified, then a Multi locker is built
338 which uses the specified list.
339
340 lock_wait => SECONDS
341 SECONDS to wait before failing on opening this folder.
342
343 locker => OBJECT
344 An OBJECT which extends Mail::Box::Locker, and will handle folder
345 locking replacing the default lock behavior.
346
347 log => LEVEL
348 manager => MANAGER
349 A reference to the object which manages this folder -- typically
350 an Mail::Box::Manager instance.
351
352 message_type => CLASS
353 What kind of message objects are stored in this type of folder.
354 The default is constructed from the folder class followed by
355 "::Message". For instance, the message type for
356 "Mail::Box::POP3" is "Mail::Box::POP3::Message"
357
358 multipart_type => CLASS
359 The default type of objects which are to be created for multipart
360 message bodies.
361
362 remove_when_empty => BOOLEAN
363 Determines whether to remove the folder file or directory
364 automatically when the write would result in a folder without
365 messages nor sub-folders.
366
367 save_on_exit => BOOLEAN
368 Sets the policy for saving the folder when it is closed. A
369 folder can be closed manually (see close()) or in a number of
370 implicit ways, including on the moment the program is terminated.
371
372 trace => LEVEL
373 trusted => BOOLEAN
374 Flags whether to trust the data in the folder or not. Folders
375 which reside in your "folderdir" will be trusted by default (even
376 when the names if not specified staring with "="). Folders which
377 are outside the folderdir or read from STDIN
378 (Mail::Message::Construct::read()) are not trused by default, and
379 require some extra checking.
380
381 If you do not check encodings of received messages, you may print
382 binary data to the screen, which is a security risk.
383
384 The folder
385 $obj->addMessage($message, %options)
386 Add a message to the folder. A message is usually a
387 Mail::Box::Message object or a sub-class thereof. The message
388 shall not be in an other folder, when you use this method. In case
389 it is, use Mail::Box::Manager::moveMessage() or
390 Mail::Box::Manager::copyMessage() via the manager.
391
392 Messages with id's which already exist in this folder are not
393 added.
394
395 BE WARNED that message labels may get lost when a message is moved
396 from one folder type to an other. An attempt is made to translate
397 labels, but there are many differences in interpretation by
398 applications.
399
400 -Option--Default
401 share <not used>
402
403 share => BOOLEAN
404 Try to share the physical resource of the current message with
405 the indicated message. It is sometimes possible to share
406 messages between different folder types. When the sharing is not
407 possible, than this option is simply ignored.
408
409 Sharing the resource is quite dangerous, and only available for a
410 limited number of folder types, at the moment only some
411 Mail::Box::Dir folders; these file-based messages can be
412 hardlinked (on platforms that support it). The link may get
413 broken when one message is modified in one of the folders.... but
414 maybe not, depending on the folder types involved.
415
416 example:
417
418 $folder->addMessage($msg);
419 $folder->addMessages($msg1, $msg2, ...);
420
421 $obj->addMessages(@messages)
422 Adds a set of message objects to the open folder at once. For some
423 folder types this may be faster than adding them one at a time.
424
425 example:
426
427 $folder->addMessages($msg1, $msg2, ...);
428
429 Mail::Box->appendMessages(%options)
430 Append one or more messages to an unopened folder. Usually, this
431 method is called by the Mail::Box::Manager::appendMessage(), in
432 which case the correctness of the folder type is checked.
433
434 For some folder types it is required to open the folder before it
435 can be used for appending. This can be fast, but this can also be
436 very slow (depends on the implementation). All %options passed
437 will also be used to open the folder, if needed.
438
439 -Option --Default
440 folder <required>
441 message undef
442 messages undef
443 share <false>
444
445 folder => FOLDERNAME
446 The name of the folder to which the messages are to be appended.
447 The folder implementation will avoid opening the folder when
448 possible, because this is resource consuming.
449
450 message => MESSAGE
451 messages => ARRAY-OF-MESSAGES
452 One reference to a MESSAGE or a reference to an ARRAY of
453 MESSAGEs, which may be of any type. The messages will be first
454 coerced into the correct message type to fit in the folder, and
455 then will be added to it.
456
457 share => BOOLEAN
458 Try to share physical storage of the message. Only available for
459 a limited number of folder types, otherwise no-op.
460
461 example:
462
463 my $message = Mail::Message->new(...);
464 Mail::Box::Mbox->appendMessages
465 ( folder => '=xyz'
466 , message => $message
467 , folderdir => $ENV{FOLDERS}
468 );
469
470 better:
471
472 my Mail::Box::Manager $mgr;
473 $mgr->appendMessages($message, folder => '=xyz');
474
475 $obj->close(%options)
476 Close the folder, which usually implies writing the changes. This
477 will return "false" when writing is required but fails. Please do
478 check this result.
479
480 WARNING: When moving messages from one folder to another, be sure
481 to write the destination folder before writing and closing the
482 source folder. Otherwise you may lose data if the system crashes
483 or if there are software problems.
484
485 -Option --Default
486 force <false>
487 save_deleted false
488 write MODIFIED
489
490 force => BOOLEAN
491 Override the new(access) setting which was specified when the
492 folder was opened. This option only has an effect if its value is
493 TRUE. NOTE: Writing to the folder may not be permitted by the
494 operating system, in which case even "force" will not help.
495
496 save_deleted => BOOLEAN
497 Do also write messages which where flagged to be deleted to their
498 folder. The flag for deletion is conserved (when possible),
499 which means that a re-open of the folder may remove the messages
500 for real. See write(save_deleted).
501
502 write => 'ALWAYS'|'NEVER'|'MODIFIED'
503 Specifies whether the folder should be written. As could be
504 expected, "ALWAYS" means always (even if there are no changes),
505 "NEVER" means that changes to the folder will be lost, and
506 "MODIFIED" only saves the folder if there are any changes.
507
508 example:
509
510 my $f = $mgr->open('spam', access => 'rw')
511 or die "Cannot open spam: $!\n";
512
513 $f->message(0)->delete
514 if $f->messages;
515
516 $f->close
517 or die "Couldn't write $f: $!\n";
518
519 $obj->copyTo($folder, %options)
520 Copy the folder's messages to a new folder. The new folder may be
521 of a different type.
522
523 -Option --Default
524 delete_copied <false>
525 select 'ACTIVE'
526 share <not used>
527 subfolders <folder type dependent>
528
529 delete_copied => BOOLEAN
530 Flag the messages from the source folder to be deleted, just
531 after it was copied. The deletion will only take effect when the
532 originating folder is closed.
533
534 select => 'ACTIVE'|'DELETED'|'ALL'|LABEL|!LABEL|FILTER
535 Which messages are to be copied. See the description of
536 messages() about how this works.
537
538 share => BOOLEAN
539 Try to share the message between the folders. Some
540 Mail::Box::Dir folder types do support it by creating a hardlink
541 (on UNIX/Linux).
542
543 subfolders => BOOLEAN|'FLATTEN'|'RECURSE'
544 How to handle sub-folders. When false (0 or "undef"), sub-
545 folders are simply ignored. With "FLATTEN", messages from sub-
546 folders are included in the main copy. "RECURSE" recursively
547 copies the sub-folders as well. By default, when the destination
548 folder supports sub-folders "RECURSE" is used, otherwise
549 "FLATTEN". A value of true will select the default.
550
551 example:
552
553 my $mgr = Mail::Box::Manager->new;
554 my $imap = $mgr->open(type => 'imap', host => ...);
555 my $mh = $mgr->open(type => 'mh', folder => '/tmp/mh',
556 create => 1, access => 'w');
557
558 $imap->copyTo($mh, delete_copied => 1);
559 $mh->close; $imap->close;
560
561 $obj->delete(%options)
562 Remove the specified folder file or folder directory (depending on
563 the type of folder) from disk. Of course, THIS IS DANGEROUS: you
564 "may" lose data. Returns a "true" value on success.
565
566 WARNING: When moving messages from one folder to another, be sure
567 to write the destination folder before deleting the source folder.
568 Otherwise you may lose data if the system crashes or if there are
569 software problems.
570
571 -Option --Default
572 recursive 1
573
574 recursive => BOOLEAN
575
576 example: removing an open folder
577
578 my $folder = Mail::Box::Mbox->new(folder => 'InBox', access => 'rw');
579 ... some other code ...
580 $folder->delete;
581
582 example: removing an closed folder
583
584 my $folder = Mail::Box::Mbox->new(folder => 'INBOX', access => 'd');
585 $folder->delete;
586
587 $obj->folderdir( [$directory] )
588 Get or set the $directory which is used to store mail-folders by
589 default.
590
591 example:
592
593 print $folder->folderdir;
594 $folder->folderdir("$ENV{HOME}/nsmail");
595
596 $obj->name()
597 Returns the name of the folder. What the name represents depends
598 on the actual type of mailbox used.
599
600 example:
601
602 print $folder->name;
603 print "$folder"; # overloaded stringification
604
605 $obj->organization()
606 Returns how the folder is organized: as one "FILE" with many
607 messages, a "DIRECTORY" with one message per file, or by a "REMOTE"
608 server.
609
610 $obj->size()
611 Returns the size of the folder in bytes, not counting in the
612 deleted messages. The error in the presented result may be as
613 large as 10%, because the in-memory representation of messages is
614 not always the same as the size when they are written.
615
616 $obj->type()
617 Returns a name for the type of mail box. This can be "mbox", "mh",
618 "maildir", or "pop3".
619
620 $obj->update(%options)
621 Read new messages from the folder, which where received after
622 opening it. This is quite dangerous and shouldn't be possible:
623 folders which are open are locked. However, some applications do
624 not use locks or the wrong kind of locks. This method reads the
625 changes (not always failsafe) and incorporates them in the open
626 folder administration.
627
628 The %options are extra values which are passed to the
629 updateMessages() method which is doing the actual work here.
630
631 $obj->url()
632 Represent the folder as a URL (Universal Resource Locator) string.
633 You may pass such a URL as folder name to
634 Mail::Box::Manager::open().
635
636 example:
637
638 print $folder->url;
639 # may result in
640 # mbox:/var/mail/markov or
641 # pop3://user:password@pop.aol.com:101
642
643 Folder flags
644 $obj->access()
645 Returns the access mode of the folder, as set by new(access)
646
647 $obj->isModified()
648 Checks if the folder, as stored in memory, is modified. A true
649 value is returned when any of the messages is to be deleted, has
650 changed, or messages were added after the folder was read from
651 file.
652
653 WARNING: this flag is not related to an external change to the
654 folder structure on disk. Have a look at update() for that.
655
656 $obj->modified( [BOOLEAN] )
657 Sets whether the folder is modified or not.
658
659 $obj->writable()
660 Checks whether the current folder is writable.
661
662 example:
663
664 $folder->addMessage($msg) if $folder->writable;
665
666 The messages
667 $obj->current( [$number|$message|$message_id] )
668 Some mail-readers keep the current message, which represents the
669 last used message. This method returns [after setting] the current
670 message. You may specify a $number, to specify that that message
671 number is to be selected as current, or a $message/$message_id (as
672 long as you are sure that the header is already loaded, otherwise
673 they are not recognized).
674
675 example:
676
677 $folder->current(0);
678 $folder->current($message);
679
680 $obj->find($message_id)
681 Like messageId(), this method searches for a message with the
682 $message_id, returning the corresponding message object. However,
683 "find" will cause unparsed message in the folder to be parsed until
684 the message-id is found. The folder will be scanned back to front.
685
686 $obj->findFirstLabeled( $label, [BOOLEAN, [$msgs]] )
687 Find the first message which has this $label with the correct
688 setting. The BOOLEAN indicates whether any true value or any false
689 value is to be found in the ARRAY of $msgs. By default, a true
690 value is searched for. When a message does not have the requested
691 label, it is taken as false.
692
693 example: looking for a labeled message
694
695 my $current = $folder->findFirstLabeled('current');
696
697 my $first = $folder->findFirstLabeled(seen => 0);
698
699 my $last = $folder->findFirstLabeled(seen => 0,
700 [ reverse $self->messages('ACTIVE') ] )
701
702 $obj->message( $index, [$message] )
703 Get or set a message with on a certain index. Messages which are
704 flagged for deletion are counted. Negative indexes start at the
705 end of the folder.
706
707 example:
708
709 my $msg = $folder->message(3);
710 $folder->message(3)->delete; # status changes to `deleted'
711 $folder->message(3, $msg);
712 print $folder->message(-1); # last message.
713
714 $obj->messageId( $message_id, [$message] )
715 With one argument, returns the message in the folder with the
716 specified $message_id. If a reference to a message object is passed
717 as the optional second argument, the message is first stored in the
718 folder, replacing any existing message whose message ID is
719 $message_id. (The message ID of $message need not match
720 $message_id.)
721
722 !!WARNING!!: when the message headers are delay-parsed, the message
723 might be in the folder but not yet parsed into memory. In this
724 case, use find() instead of "messageId()" if you really need a
725 thorough search. This is especially the case for directory
726 organized folders without special indexi, like Mail::Box::MH.
727
728 The $message_id may still be in angles, which will be stripped. In
729 that case blanks (which origin from header line folding) are
730 removed too. Other info around the angles will be removed too.
731
732 example:
733
734 my $msg = $folder->messageId('<complex-message.id>');
735 $folder->messageId("<complex-message\n.id>", $msg);
736 my $msg = $folder->messageId('complex-message.id');
737 my $msg = $folder->messageId('garbage <complex-message.id> trash');
738
739 $obj->messageIds()
740 Returns a list of all message-ids in the folder, including those of
741 messages which are to be deleted.
742
743 For some folder-types (like MH), this method may cause all message-
744 files to be read. See their respective manual pages.
745
746 example:
747
748 foreach my $id ($folder->messageIds) {
749 $folder->messageId($id)->print;
750 }
751
752 $obj->messages( <'ALL'|$range|'ACTIVE'|'DELETED'|$label|
753 !$label|$filter> )
754 Returns multiple messages from the folder. The default is "ALL"
755 which will return (as expected maybe) all the messages in the
756 folder. The "ACTIVE" flag will return the messages not flagged for
757 deletion. This is the opposite of "DELETED", which returns all
758 messages from the folder which will be deleted when the folder is
759 closed.
760
761 You may also specify a $range: two numbers specifying begin and end
762 index in the array of messages. Negative indexes count from the
763 end of the folder. When an index is out-of-range, the returned
764 list will be shorter without complaints.
765
766 Everything else than the predefined names is seen as labels. The
767 messages which have that label set will be returned. When the
768 sequence starts with an exclamation mark (!), the search result is
769 reversed.
770
771 For more complex searches, you can specify a $filter, which is
772 simply a code reference. The message is passed as only argument.
773
774 example:
775
776 foreach my $message ($folder->messages) {...}
777 foreach my $message (@$folder) {...}
778
779 # twice the same
780 my @messages = $folder->messages;
781 my @messages = $folder->messages('ALL');
782
783 # Selection based on a range (begin, end)
784 my $subset = $folder->messages(10,-8);
785
786 # twice the same:
787 my @not_deleted= grep {not $_->isDeleted}
788 $folder->messages;
789 my @not_deleted= $folder->messages('ACTIVE');
790
791 # scalar context the number of messages
792 my $nr_of_msgs = $folder->messages;
793
794 # third message, via overloading
795 $folder->[2];
796
797 # Selection based on labels
798 $mgr->moveMessages($spam, $inbox->message('spam'));
799 $mgr->moveMessages($archive, $inbox->message('seen'));
800
801 $obj->nrMessages(%options)
802 Simply calls messages() in scalar context to return a count instead
803 of the messages itself. Some people seem to understand this
804 better. Note that nrMessages() will default to returning a count
805 of "ALL" messages in the folder, including both "ACTIVE" and
806 "DELETED".
807
808 The %options are passed to (and explained in) messages().
809
810 $obj->scanForMessages($message, $message_ids, $timespan, $window)
811 You start with a $message, and are looking for a set of messages
812 which are related to it. For instance, messages which appear in
813 the 'In-Reply-To' and 'Reference' header fields of that message.
814 These messages are known by their $message_ids and you want to find
815 them in the folder.
816
817 When all message-ids are known, then looking-up messages is simple:
818 they are found in a plain hash using messageId(). But Mail::Box is
819 lazy where it can, so many messages may not have been read from
820 file yet, and that's the preferred situation, because that saves
821 time and memory.
822
823 It is not smart to search for the messages from front to back in
824 the folder: the chances are much higher that related message reside
825 closely to each other. Therefore, this method starts scanning the
826 folder from the specified $message, back to the front of the
827 folder.
828
829 The $timespan can be used to terminate the search based on the time
830 enclosed in the message. When the constant string "EVER" is used
831 as $timespan, then the search is not limited by that. When an
832 integer is specified, it will be used as absolute time in time-
833 ticks as provided by your platform dependent "time" function. In
834 other cases, it is passed to timespan2seconds() to determine the
835 threshold as time relative to the message's time.
836
837 The $window is used to limit the search in number of messages to be
838 scanned as integer or constant string "ALL".
839
840 Returned are the message-ids which were not found during the scan.
841 Be warned that a message-id could already be known and therefore
842 not found: check that first.
843
844 example: scanning through a folder for a message
845
846 my $refs = $msg->get('References') or return;
847 my @msgids = $ref =~ m/\<([^>]+\>/g;
848 my @failed = $folder->scanForMessages($msg, \@msgids, '3 days', 50);
849
850 Sub-folders
851 $obj->listSubFolders(%options)
852 Mail::Box->listSubFolders(%options)
853 List the names of all sub-folders to this folder, not recursively
854 decending. Use these names as argument to openSubFolder(), to get
855 access to that folder.
856
857 For MBOX folders, sub-folders are simulated.
858
859 -Option --Default
860 check <false>
861 folder <from calling object>
862 folderdir <from folder>
863 skip_empty <false>
864
865 check => BOOLEAN
866 Should all returned foldernames be checked to be sure that they
867 are of the right type? Each sub-folder may need to be opened to
868 check this, with a folder type dependent penalty (in some cases
869 very expensive).
870
871 folder => FOLDERNAME
872 The folder whose sub-folders should be listed.
873
874 folderdir => DIRECTORY
875 skip_empty => BOOL
876 Shall empty folders (folders which currently do not contain any
877 messages) be included? Empty folders are not useful to open, but
878 may be useful to save to.
879
880 example:
881
882 my $folder = $mgr->open('=in/new');
883 my @subs = $folder->listSubFolders;
884
885 my @subs = Mail::Box::Mbox->listSubFolders(folder => '=in/new');
886 my @subs = Mail::Box::Mbox->listSubFolders; # toplevel folders.
887
888 $obj->nameOfSubFolder( $subname, [$parentname] )
889 Mail::Box->nameOfSubFolder( $subname, [$parentname] )
890 Returns the constructed name of the folder with NAME, which is a
891 sub-folder of this current one. You have either to call this
892 method as instance method, or specify a $parentname.
893
894 example: how to get the name of a subfolder
895
896 my $sub = Mail::Box::Mbox->nameOfSubfolder('xyz', 'abc');
897 print $sub; # abc/xyz
898
899 my $f = Mail::Box::Mbox->new(folder => 'abc');
900 print $f->nameOfSubfolder('xyz'); # abc/xyz
901
902 my $sub = Mail::Box::Mbox->nameOfSubfolder('xyz', undef);
903 print $sub; # xyz
904
905 $obj->openRelatedFolder(%options)
906 Open a folder (usually a sub-folder) with the same options as this
907 one. If there is a folder manager in use, it will be informed
908 about this new folder. %options overrule the options which where
909 used for the folder this method is called upon.
910
911 $obj->openSubFolder($subname, %options)
912 Open (or create, if it does not exist yet) a new subfolder in an
913 existing folder.
914
915 example:
916
917 my $folder = Mail::Box::Mbox->new(folder => '=Inbox');
918 my $sub = $folder->openSubFolder('read');
919
920 $obj->topFolderWithMessages()
921 Mail::Box->topFolderWithMessages()
922 Some folder types can have messages in the top-level folder, some
923 other can't.
924
925 Internals
926 $obj->coerce($message, %options)
927 Coerce the $message to be of the correct type to be placed in the
928 folder. You can specify Mail::Internet and MIME::Entity objects
929 here: they will be translated into Mail::Message messages first.
930
931 $obj->create($foldername, %options)
932 Mail::Box->create($foldername, %options)
933 Create a folder. If the folder already exists, it will be left
934 unchanged. The folder is created, but not opened! If you want to
935 open a file which may need to be created, then use
936 Mail::Box::Manager::open() with the create flag, or
937 Mail::Box::new(create).
938
939 -Option --Default
940 folderdir undef
941
942 folderdir => DIRECTORY
943 When the foldername is preceded by a "=", the "folderdir"
944 directory will be searched for the named folder.
945
946 $obj->determineBodyType($message, $head)
947 Determine which kind of body will be created for this message when
948 reading the folder initially.
949
950 Mail::Box->foundIn( [$foldername], %options )
951 Determine if the specified folder is of the type handled by the
952 folder class. This method is extended by each folder sub-type.
953
954 The $foldername specifies the name of the folder, as is specified
955 by the application. You need to specified the "folder" option when
956 you skip this first argument.
957
958 %options is a list of extra information for the request. Read the
959 documentation for each type of folder for type specific options,
960 but each folder class will at least support the "folderdir" option:
961
962 -Option --Default
963 folderdir undef
964
965 folderdir => DIRECTORY
966 The location where the folders of this class are stored by
967 default. If the user specifies a name starting with a "=", that
968 indicates that the folder is to be found in this default
969 DIRECTORY.
970
971 example:
972
973 Mail::Box::Mbox->foundIn('=markov',
974 folderdir => "$ENV{HOME}/Mail");
975 Mail::Box::MH->foundIn(folder => '=markov');
976
977 $obj->lineSeparator( [<STRING|'CR'|'LF'|'CRLF'>] )
978 Returns the character or characters used to separate lines in the
979 folder file, optionally after setting it to STRING, or one of the
980 constants. The first line of the folder sets the default.
981
982 UNIX uses a LF character, Mac a CR, and Windows both a CR and a LF.
983 Each separator will be represented by a "\n" within your program.
984 However, when processing platform foreign folders, complications
985 appear. Think about the "Size" field in the header.
986
987 When the separator is changed, the whole folder me be rewritten.
988 Although, that may not be required.
989
990 $obj->locker()
991 Returns the locking object.
992
993 $obj->read(%options)
994 Read messages from the folder into memory. The %options are folder
995 specific. Do not call "read()" yourself: it will be called for you
996 when you open the folder via the manager or instantiate a folder
997 object directly.
998
999 NOTE: if you are copying messages from one folder to another, use
1000 addMessages() instead of "read()".
1001
1002 example:
1003
1004 my $mgr = Mail::Box::Manager->new;
1005 my $folder = $mgr->open('InBox'); # implies read
1006 my $folder = Mail::Box::Mbox->new(folder => 'Inbox'); # same
1007
1008 $obj->readMessages(%options)
1009 Called by read() to actually read the messages from one specific
1010 folder type. The read() organizes the general activities.
1011
1012 The %options are "trusted", "head_type", "field_type",
1013 "message_type", "body_delayed_type", and "head_delayed_type" as
1014 defined by the folder at hand. The defaults are the constructor
1015 defaults (see new()).
1016
1017 $obj->storeMessage($message)
1018 Store the message in the folder without the checks as performed by
1019 addMessage().
1020
1021 $obj->toBeThreaded($messages)
1022 The specified message is ready to be removed from a thread. This
1023 will be passed on to the mail-manager, which keeps an overview on
1024 which thread-detection objects are floating around.
1025
1026 $obj->toBeUnthreaded($messages)
1027 The specified message is ready to be included in a thread. This
1028 will be passed on to the mail-manager, which keeps an overview on
1029 which thread-detection objects are floating around.
1030
1031 $obj->updateMessages(%options)
1032 Called by update() to read messages which arrived in the folder
1033 after it was opened. Sometimes, external applications dump
1034 messages in a folder without locking (or using a different lock
1035 than your application does).
1036
1037 Although this is quite a dangerous, it only fails when a folder is
1038 updated (reordered or message removed) at exactly the same time as
1039 new messages arrive. These collisions are sparse.
1040
1041 The options are the same as for readMessages().
1042
1043 $obj->write(%options)
1044 Write the data to disk. The folder (a "true" value) is returned if
1045 successful. Deleted messages are transformed into destroyed
1046 messages: their memory is freed.
1047
1048 WARNING: When moving messages from one folder to another, be sure
1049 to write (or close()) the destination folder before writing (or
1050 closing) the source folder: otherwise you may lose data if the
1051 system crashes or if there are software problems.
1052
1053 To write a folder to a different file, you must first create a new
1054 folder, then move all the messages, and then write or close() that
1055 new folder.
1056
1057 -Option --Default
1058 force <false>
1059 save_deleted <false>
1060
1061 force => BOOLEAN
1062 Override write-protection with new(access) while opening the
1063 folder (whenever possible, it may still be blocked by the
1064 operating system).
1065
1066 save_deleted => BOOLEAN
1067 Do also write messages which where flagged to be deleted to their
1068 folder. The flag for deletion is conserved (when possible),
1069 which means that a re-open of the folder may remove the messages
1070 for real. See close(save_deleted).
1071
1072 $obj->writeMessages(%options)
1073 Called by write() to actually write the messages from one specific
1074 folder type. The "write" organizes the general activities. All
1075 options to write() are passed to "writeMessages" as well. Besides,
1076 a few extra are added by "write" itself.
1077
1078 -Option --Default
1079 messages <required>
1080
1081 messages => ARRAY
1082 The messages to be written, which is a sub-set of all messages in
1083 the current folder.
1084
1085 Other methods
1086 $obj->timespan2seconds($time)
1087 Mail::Box->timespan2seconds($time)
1088 $time is a string, which starts with a float, and then one of the
1089 words 'hour', 'hours', 'day', 'days', 'week', or 'weeks'. For
1090 instance: '1 hour' or '4 weeks'.
1091
1092 Error handling
1093 Extends "Error handling" in Mail::Reporter.
1094
1095 $obj->AUTOLOAD()
1096 Inherited, see "Error handling" in Mail::Reporter
1097
1098 $obj->addReport($object)
1099 Inherited, see "Error handling" in Mail::Reporter
1100
1101 $obj->defaultTrace( [$level]|[$loglevel, $tracelevel]|[$level,
1102 $callback] )
1103 Mail::Box->defaultTrace( [$level]|[$loglevel, $tracelevel]|[$level,
1104 $callback] )
1105 Inherited, see "Error handling" in Mail::Reporter
1106
1107 $obj->errors()
1108 Inherited, see "Error handling" in Mail::Reporter
1109
1110 $obj->log( [$level, [$strings]] )
1111 Mail::Box->log( [$level, [$strings]] )
1112 Inherited, see "Error handling" in Mail::Reporter
1113
1114 $obj->logPriority($level)
1115 Mail::Box->logPriority($level)
1116 Inherited, see "Error handling" in Mail::Reporter
1117
1118 $obj->logSettings()
1119 Inherited, see "Error handling" in Mail::Reporter
1120
1121 $obj->notImplemented()
1122 Inherited, see "Error handling" in Mail::Reporter
1123
1124 $obj->report( [$level] )
1125 Inherited, see "Error handling" in Mail::Reporter
1126
1127 $obj->reportAll( [$level] )
1128 Inherited, see "Error handling" in Mail::Reporter
1129
1130 $obj->trace( [$level] )
1131 Inherited, see "Error handling" in Mail::Reporter
1132
1133 $obj->warnings()
1134 Inherited, see "Error handling" in Mail::Reporter
1135
1136 Cleanup
1137 Extends "Cleanup" in Mail::Reporter.
1138
1139 $obj->DESTROY()
1140 This method is called by Perl when an folder-object is no longer
1141 accessible by the rest of the program.
1142
1144 Different kinds of folders
1145 In general, there are three classes of folders: those who group
1146 messages per file, those who group messages in a directory, and those
1147 do not provide direct access to the message data. These folder types
1148 are each based on a different base class.
1149
1150 • File based folders Mail::Box::File
1151
1152 File based folders maintain a folder (a set of messages) in one
1153 single file. The advantage is that your folder has only one single
1154 file to access, which speeds-up things when all messages must be
1155 accessed at once.
1156
1157 One of the main disadvantages over directory based folders is that
1158 you have to construct some means to keep all message apart. For
1159 instance MBOX adds a message separator line between the messages in
1160 the file, and this line can cause confusion with the message's
1161 contents.
1162
1163 Where access to all messages at once is faster in file based
1164 folders, access to a single message is (much) slower, because the
1165 whole folder must be read. However, in directory based folders you
1166 have to figure-out which message you need, which may be a hassle as
1167 well.
1168
1169 Examples of file based folders are MBOX, DBX, and NetScape.
1170
1171 • Directory based folders Mail::Box::Dir
1172
1173 In stead of collecting multiple messages in one file, you can also
1174 put each message in a separate file and collect those files in a
1175 directory to represent a folder.
1176
1177 The main disadvantages of these folders are the enormous amount of
1178 tiny files you usually get in your file-system. It is extremely
1179 slow to search through your whole folder, because many files have
1180 to be opened to do so.
1181
1182 The best feature of this organization is that each message is kept
1183 exactly as it was received, and can be processed with external
1184 scripts as well: you do not need any mail user agent (MUA).
1185
1186 Examples of directory organized folders are MH, Maildir, EMH and
1187 XMH.
1188
1189 • Network (external) folders Mail::Box::Net
1190
1191 Where both types described before provide direct access to the
1192 message data, maintain these folder types the message data for you:
1193 you have to request for messages or parts of them. These folders
1194 do not have a filename, file-system privileges and system locking
1195 to worry about, but typically require a hostname, folder and
1196 message IDs, and authorization.
1197
1198 Examples of these folder types are the popular POP and IMAP, and
1199 database oriented message storage.
1200
1201 Available folder types
1202 • Mail::Box::Dbx (read only)
1203
1204 Dbx files are created by Outlook Express. Using the external
1205 (optional) Mail::Transport::Dbx module, you can read these folders,
1206 even when you are running MailBox on a UNIX/Linux platform.
1207
1208 Writing and deleting messages is not supported by the library, and
1209 therefore not by MailBox. Read access is enough to do folder
1210 conversions, for instance.
1211
1212 • Mail::Box::IMAP4 (partially)
1213
1214 The IMAP protocol is very complex. Some parts are implemented to
1215 create (sub-optimal but usable) IMAP clients. Besides, there are
1216 also some parts for IMAP servers present. The most important
1217 lacking feature is support for encrypted connections.
1218
1219 • Mail::Box::Maildir
1220
1221 Maildir folders have a directory for each folder. A folder
1222 directory contains "tmp", "new", and "cur" sub-directories, each
1223 containing messages with a different purpose. Files with new
1224 messages are created in "tmp", then moved to "new" (ready to be
1225 accepted). Later, they are moved to the "cur" directory
1226 (accepted). Each message is one file with a name starting with
1227 timestamp. The name also contains flags about the status of the
1228 message.
1229
1230 Maildir folders can not be used on Windows by reason of file-name
1231 limitations on that platform.
1232
1233 • Mail::Box::Mbox
1234
1235 A folder type in which all related messages are stored in one file.
1236 This is a very common folder type for UNIX.
1237
1238 • Mail::Box::MH
1239
1240 This folder creates a directory for each folder, and a message is
1241 one file inside that directory. The message files are numbered
1242 sequentially on order of arrival. A special ".mh_sequences" file
1243 maintains flags about the messages.
1244
1245 • Mail::Box::POP3 (read/delete only)
1246
1247 POP3 is a protocol which can be used to retrieve messages from a
1248 remote system. After the connection to a POP server is made, the
1249 messages can be looked at and removed as if they are on the local
1250 system.
1251
1252 • Mail::Box::Netzwert
1253
1254 The Netzwert folder type is optimized for mailbox handling on a
1255 cluster of systems with a shared NFS storage. The code is not
1256 released under GPL (yet)
1257
1258 Other folder types are on the (long) wishlist to get implemented.
1259 Please, help implementing more of them.
1260
1261 Folder class implementation
1262 The class structure of folders is very close to that of messages. For
1263 instance, a Mail::Box::File::Message relates to a Mail::Box::File
1264 folder. The folder types are:
1265
1266 Mail::Box::Netzwert
1267 Mail::Box::Mbox | Mail::Box::Maildir Mail::Box::POP3
1268 | Mail::Box::Dbx | | Mail::Box::MH | Mail::Box::IMAP4
1269 | | | | | | |
1270 | | | | | | |
1271 Mail::Box::File Mail::Box::Dir Mail::Box::Net
1272 | | |
1273 `--------------. | .---------------'
1274 | | |
1275 Mail::Box
1276 |
1277 |
1278 Mail::Reporter (general base class)
1279
1280 By far most folder features are implemented in Mail::Box, so available
1281 to all folder types. Sometimes, features which appear in only some of
1282 the folder types are simulated for folders that miss them, like sub-
1283 folder support for MBOX.
1284
1286 Warning: Changes not written to read-only folder $self.
1287 You have opened the folder read-only --which is the default set by
1288 new(access)--, made modifications, and now want to close it. Set
1289 close(force) if you want to overrule the access mode, or close the
1290 folder with close(write) set to "NEVER".
1291
1292 Error: Copying failed for one message.
1293 For some reason, for instance disc full, removed by external
1294 process, or read-protection, it is impossible to copy one of the
1295 messages. Copying will proceed for the other messages.
1296
1297 Error: Destination folder $name is not writable.
1298 The folder where the messages are copied to is not opened with
1299 write access (see new(access)). This has no relation with write
1300 permission to the folder which is controlled by your operating
1301 system.
1302
1303 Warning: Different messages with id $msgid
1304 The message id is discovered more than once within the same folder,
1305 but the content of the message seems to be different. This should
1306 not be possible: each message must be unique.
1307
1308 Error: Folder $name is opened read-only
1309 You can not write to this folder unless you have opened the folder
1310 to write or append with new(access), or the "force" option is set
1311 true.
1312
1313 Error: Folder $name not deleted: not writable.
1314 The folder must be opened with write access via new(access),
1315 otherwise removing it will be refused. So, you may have write-
1316 access according to the operating system, but that will not
1317 automatically mean that this "delete" method permits you to. The
1318 reverse remark is valid as well.
1319
1320 Error: Invalid timespan '$timespan' specified.
1321 The string does not follow the strict rules of the time span syntax
1322 which is permitted as parameter.
1323
1324 Warning: Message-id '$msgid' does not contain a domain.
1325 According to the RFCs, message-ids need to contain a unique random
1326 part, then an "@", and then a domain name. This is made to avoid
1327 the creation of two messages with the same id. The warning emerges
1328 when the "@" is missing from the string.
1329
1330 Error: No folder name specified.
1331 You did not specify the name of a folder to be opened. Use the
1332 new(folder) option or set the "MAIL" environment variable.
1333
1334 Error: Package $package does not implement $method.
1335 Fatal error: the specific package (or one of its superclasses) does
1336 not implement this method where it should. This message means that
1337 some other related classes do implement this method however the
1338 class at hand does not. Probably you should investigate this and
1339 probably inform the author of the package.
1340
1341 Error: Unable to create subfolder $name of $folder.
1342 The copy includes the subfolders, but for some reason it was not
1343 possible to copy one of these. Copying will proceed for all other
1344 sub-folders.
1345
1346 Error: Writing folder $name failed
1347 For some reason (you probably got more error messages about this
1348 problem) it is impossible to write the folder, although you should
1349 because there were changes made.
1350
1352 This module is part of Mail-Box distribution version 3.009, built on
1353 August 18, 2020. Website: http://perl.overmeer.net/CPAN/
1354
1356 Copyrights 2001-2020 by [Mark Overmeer]. For other contributors see
1357 ChangeLog.
1358
1359 This program is free software; you can redistribute it and/or modify it
1360 under the same terms as Perl itself. See http://dev.perl.org/licenses/
1361
1362
1363
1364perl v5.32.1 2021-01-27 Mail::Box(3)