MboxParser::Mail(3pm)
π MboxParser::Mail(3pm) π
okay bestie, welcome to the User Contributed Perl Documentation page for Mail::MboxParser::Mail β¨. This is part 1 of 2, so we are absolutely not done yet β more parts follow. Grab a boba, because we are reading the whole thing together, no skips, no cap. π
β¨ NAME β¨
Mail::MboxParser::Mail β Provide mail-objects and methods upon
πΈ SYNOPSIS πΈ
See Mail::MboxParser for an outline on usage. Examples however are also provided in this manpage further below.
π¦ DESCRIPTION π¦
Mail::MboxParser::Mail objects are usually not created directly though, in theory, they could be. A description of the provided methods can be found in Mail::MboxParser.
However, go on reading if you want to use methods from MIME::Entity and learn about overloading. Overloading? We love a little plot twist. π
π METHODS π
new(header, body)
This is usually not called directly but instead by get_messages(). You could however create a mail-object manually providing the header and body each as either one string or as an array-ref representing the lines. DIY energy, but make it Perl.
Here is a common scenario: Retrieving mails from a remote POP-server using Mail::POP3Client and directly feeding each mail to Mail::MboxParser::Mail->new:
use Mail::POP3Client;
use Mail::MboxParser::Mail;
my $pop = new Mail::POP3Client (...);
for my $i (1 .. $pop->Count) {
my $msg = Mail::MboxParser::Mail->new( [ $pop->Head($i) ],
[ $pop->Body($i) ] );
$msg->store_all_attachments( path => '/home/user/dump' );
}
The above effectively behaves like an attachment-only retriever. It is giving very βjust the attachments, maβam.β π
header
Returns the mail-header as a hash-ref with header-fields as keys. All keys are turned to lower-case, so $header{Subject} has to be written as $header{subject}. Case-sensitivity is not the vibe here.
If a header-field occurs more than once in the header, the value of the key is an array_ref. Example:
my $field = $msg->header->{field};
print $field->[0]; # first occurance of 'field'
print $field->[1]; # second one
...
from_line
Returns the "From "-line of the message. Short, sweet, iconic. π
trace
This method returns the "Received: "-lines of the message as a list. Receipts, literally. π§
body / body(n)
Returns a Mail::MboxParser::Mail::Body object. For methods upon that see further below. When called with the argument n, the n-th body of the message is retrieved. That is, the body of the n-th entity. N-th entity? We love an indexed queen.
Sets $mail->error if something went wrong.
find_body
This will return an index number that represents what Mail::MboxParser::Mail considers to be the actual (main)-body of an email. This is useful if you don't know about the structure of a message but want to retrieve the message's signature for instance:
$signature = $msg->body($msg->find_body)->signature;
Changes are good that find_body does what it is supposed to do. We stan an optimistic method. π«Ά
make_convertable
Returns a Mail::MboxParser::Mail::Convertable object. For details on what you can do with it, read Mail::MboxParser::Mail::Convertable. Go read that one too, bestie.
get_field(headerfield)
Returns the specified raw field from the message header, that is: the fieldname is not stripped off nor is any decoding done. Returns multiple lines as needed if the field is "Received" or another multi-line field. Not case sensitive. Raw and unfiltered β very main character. π₯
get_field() always returns one string regardless of how many times the field occured in the header. Multiple occurances are separated by a newline and multiple whitespaces squeezed to one. That means you can process each occurance of the field thusly:
for my $field ( split /\n/, $msg->get_field('received') ) {
# do something with $field
}
Sets $mail->error if the field was not found in which case get_field() returns undef. Not found? Sheβs not here, bestie. π
from
Returns a hash-ref with the two fields 'name' and 'email'. Returns undef if empty. The name-field does not necessarily contain a value either. Example:
print $mail->from->{email};
On behalf of suggestions I received from users, from() tries to be smart when 'name'is empty and 'email' has the form 'first.name@host.com'. In this case, 'name' is set to "First Name". Smart, not rude. π
to
Returns an array of hash-references of all to-fields in the mail-header. Fields are the same as those of $mail->from. Example:
for my $recipient ($mail->to) {
print $recipient->{name} || "<no name>", "\n";
print $recipient->{email};
}
The same 'name'-smartness applies here as described under from(). Consistency? We love to see it.
cc
Identical with to() but returning the hash-refed "Cc: "-line.
The same 'name'-smartness applies here as described under from(). Cc: keeping everyone in the loop, periodt. β¨
id
Returns the message-id of a message cutting off the leading and trailing '<' and '>' respectively. Trimmed and snatched. π
num_entities
Returns the number of MIME-entities. That is, the number of sub-entitities actually. If 0 is returned and you think this is wrong, check $mail->log. Zero? Suspicious. Check the log, bestie. π
get_entities / get_entities(n)
Either returns an array of all MIME::Entity objects or one particular if called with a number. If no entity whatsoever could be found, an empty list is returned. Empty list? We hate that for you. π
$mail->log instantly called after get_entities will give you some information of what internally may have failed. If set, this will be an error raised by MIME::Entity but you don't need to worry about it at all. It's just for the record. For the record, literally.
get_entity_body(n)
Returns the body of the n-th MIME::Entity as a single string, undef otherwise in which case you could check $mail->error. Undef? Check the error. Sheβll tell you.
store_entity_body(n, handle => FILEHANDLE)
Stores the stringified body of n-th entity to the specified filehandle. That's basically the same as:
my $body = $mail->get_entity_body(0);
print FILEHANDLE $body;
and could be shortened to this:
$mail->store_entity_body(0, handle => \*FILEHANDLE);
It returns a true value on success and undef on failure. In this case, examine the value of $mail->error since the entity you specified with 'n' might not exist. Failure? Look at the error, no guessing. π
store_attachment(n) / store_attachment(n, options)
It is really just a call to store_entity_body but it will take care that the n-th entity really is a saveable attachment. That is, it wont save anything with a MIME-type of, say, text/html or so. No random HTML files, thank you.
Unless further 'options' have been given, an attachment (if found) is stored into the current directory under the recommended filename given in the MIME-header. 'options' are specified in key/value pairs:
path(default:".") β relative or absolute path; directory to store attachmentencodeβ encoding suitable forEncode::encode; some platforms store files in e.g. UTF-8. Specify the appropriate encoding here and and the filename will be en- coded accordingly.store_onlyβ a compiled regex-pattern; store only files whose file names match this patterncodeβ an anonym subroutine; first argument will be the$msg-object, second one the index-number of the current MIME-part; should return a filename for the attachmentprefixβ prefix for filenames; all filenames are prefixed with this valueargsβ additional arguments as array-ref; this array-ref will be passed on to the 'code' subroutine as a dereferenced array
Example:
$msg->store_attachment(1,
path => "/home/ethan/",
code => sub {
my ($msg, $n, @args) = @_;
return $msg->id."+$n";
},
args => [ "Foo", "Bar" ]);
This will save the attachment found in the second entity under the name that consists of the message-ID and the appendix "+1" since the above code works on the second entity (that is, with index = 1). 'args' isn't used in this example but should demonstrate how to pass additional arguments. Inside the 'code' sub, @args equals ("Foo", "Bar"). Custom filename energy? We love a subroutine moment. π§
If 'path' does not exist, it will try to create the directory for you. Helpful, not helpless.
You can specify to save only files matching a certain pattern. To do that, use the store-only switch:
$msg->store_attachment(1, path => "/home/ethan/",
store_only => qr/\.jpg$/i);
The above will only save files that end on '.jpg', not case-sensitive. You could also use a non-compiled pattern if you want, but that would make for instance case-insensitive matching a little cumbersome:
store_only => '(?i)\.jpg$'
If you are working on a platform that requires a certain encoding for filenames on disk, you can use the 'encode' option. This becomes necessary for instance on Mac OS X which internally is UTF-8 based. If the filename contains 8bit characters (like the German umlauts or French accented characters as in 'Γ©'), storing the attachment under a non-encoded name will most likely fail. In this case, use something like this:
$msg->store_attachment(1, path => '/tmp', encode => 'utf-8');
See Encode::Supported for a list of encodings that you may use. Encoding? Do not skip this, bestie.
Returns the filename under which the attachment has been saved. undef is returned in case the entity did not contain a saveable attachment, there was no such entity at all or there was something wrong with the 'path' you specified. Check $mail->error to find out which of these possibilities apply. Undef is giving βmystery,β so check the error. Periodt. π
store_all_attachmentsstore_all_attachments(options)
okay bestie, this one is the β¨ save everything β¨ button. It walks through a whole entire mail and stores all the apparent attachments it can find. The options you pass? Literally exactly the same as in store_attachment(), and if you pass none, the behaviour is the same too. No notes. π
It returns a list of the files that got successfully saved, and an empty list if it couldn't extract a single attachment. empty list = no crumbs found, bestie.
And if things go wrong, $mail->error will tell you the possible failures plus a lil explanation for each. π«Ά
get_attachmentsget_attachments(file)
This one gives you a mapping from attachment-names (as long as those names are saveable) over to the index-numbers of the MIME-part that represents that attachment. It hands you back a hash-reference, where the file-names are the key and the index is the value. it's giving lookup table energy:
my $mapping = $msg->get_attachments;
for my $filename (keys %$mapping) {
print "$filename => $mapping->{$filename}\n";
}
If you call it with a string as the argument, it tries to look up that filename. If it can't find it, undef comes back. And in that case you should also have an error-message patiently awaiting you in the return value of $mail->error. π
Now listen β even though it looks tempting, do NOT do this:
# BAD!
for my $file (qw/file1.ext file2.ext file3.ext file4.ext/) {
print "$file is in message ", $msg->id, "\n"
if defined $msg->get_attachments($file);
}
The reason? get_attachments() is currently not optimized to cache the filename mapping. So every single time you call it on a message β even the same message β it will scan it from beginning to end. Every. Time. π That's not main character energy, that's just wasted cycles.
The better way, bestie:
# GOOD!
my $mapping = $msg->get_attachments;
for my $file (qw/file1.ext file2.ext file3.ext file4.ext/) {
print "$file is in message ", $msg->id, "\n"
if exists $mapping->{$file};
}
as_string
Returns the message as one single string. This is the method that string overloading depends on, so these two are literally the same thing:
print $msg;
print $msg->as_string;
β¨ EXTERNAL METHODS β¨
Mail::MboxParser::Mail implements an autoloader that will do the appropriate type-casts for you whenever you invoke methods from external modules. Heads up though: right now this only works with MIME::Entity. Support for other modules will follow. π
Example time:
my $mb = Mail::MboxParser->new("/home/user/Mail/received");
for my $msg ($mb->get_messages) {
print $msg->effective_type, "\n";
}
effective_type() is not implemented by Mail::MboxParser::Mail, so the corresponding method of MIME::Entity gets automatically called instead. slay, autoloader. π¦
And if you wanna know what methods might be useful to you, you should go read the "Access"-part of the section "PUBLIC INTERFACE" in the MIME::Entity manpage. It may become handy if you have mails with a lot of MIME-parts and you don't just wanna handle binary-attachments but literally any kind of MIME-data. iykyk π
π OVERLOADING π
Mail::MboxParser::Mail overloads the " " operator. Overloading operators is a fancy lil feature of Perl (and some other languages β C++ for instance) that changes the behaviour of an object when one of those overloaded operators gets applied onto it. So here, you get the stringified mail when you write $mail, whereas otherwise you'd get the stringified reference instead: Mail::MboxParser::Mail=HASH(...). iconic behaviour honestly πΈ
β VERSION β
This is version 0.55. periodt.
π AUTHOR AND COPYRIGHT π
Tassilo von Parseval <tassilo.von.parseval@rwth-aachen.de>
Copyright (c) 2001-2005 Tassilo von Parseval. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
π¦ SEE ALSO π¦
MIME::EntityMail::MboxParser,Mail::MboxParser::Mail::Body,Mail::MboxParser::Mail::Convertable
and that's a wrap on the whole page, bestie π«Ά this lil doc lives in perl v5.34.0 and got its last glow-up on 2022-06-15 under the MboxParser::Mail(3pm) name. go forth and parse those mailboxes, you absolute icon πβ¨
π¦ where this page comes from
- debian bookworm: libmail-mboxparser-perl 0.55-5 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- debian trixie: libmail-mboxparser-perl 0.55-5 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu noble: libmail-mboxparser-perl 0.55-5 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu resolute: libmail-mboxparser-perl 0.55-5 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libmail-mboxparser-perl 0.55-5 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms