Mail::Message(3)
β¨ NAME β¨
Mail::Message β general message object. Yep, that's the Mail::Message(3) page, you're in the right place bestie π«Ά
π INHERITANCE π
Mail::Message has extra code in
Mail::Message::ConstructMail::Message::Construct::BounceMail::Message::Construct::BuildMail::Message::Construct::ForwardMail::Message::Construct::ReadMail::Message::Construct::RebuildMail::Message::Construct::ReplyMail::Message::Construct::Text
Mail::Message is a Mail::Reporter
Mail::Message is extended by
Mail::Box::MessageMail::Message::DummyMail::Message::PartMail::Message::Replace::MailInternet
π¦ SYNOPSIS π¦
use Mail::Box::Manager;
my $mgr = Mail::Box::Manager->new;
my $folder = $mgr->open(folder => 'INBOX');
my $msg = $folder->message(2); # $msg is a Mail::Message
my $subject = $msg->subject; # The message's subject
my @cc = $msg->cc; # List of Mail::Address'es
my $head = $msg->head; # Mail::Message::Head
my $body = $msg->decoded; # Mail::Message::Body
$msg->decoded->print($outfile);
# Send a simple email
Mail::Message->build(
To => 'you@example.com',
From => 'me@example.com',
Subject => "My subject",
data => "Some plain text content"
)->send(via => 'postfix');
my $msg = Mail::Message->read(\@lines);
my $reply_msg = $msg->reply(...);
my $frwd_msg = $msg->forward(...);
my $bounce = $msg->bounce(...);
π DESCRIPTION π
A Mail::Message object is literally just a container for MIME-encoded message info, exactly as RFC2822 defines it. Everything that isn't specifically about storing messages inside mailboxes (folders) lives in this class. The folder-related stuff? That's implemented over in the Mail::Box::Message extension. iykyk π
The main character methods here are get(), which pulls info out of a message header field, and decoded(), which hands you the actual intended content of a message. But there are so many more that can help your program out, fr fr.
Complex message handling β think constructing replies and forwards β lives in separate packages that get autoloaded into this class. Which means you can just call those methods like they're part of this class, no extra work. Those packages add functionality to all kinds of message objects.
Extends "DESCRIPTION" in Mail::Reporter.
π METHODS π
Extends "METHODS" in Mail::Reporter.
π Constructors π
Extends "Constructors" in Mail::Reporter.
$obj->clone(%options)
Makes a copy of this message. What you get back is a Mail::Message object. The head and the body get taken along. Labels get copied with the message, but the delete and modified flags do not.
β οΈ BE WARNED: the clone of any kind of message (or a message part) will always be aMail::Messageobject. Like, for example, aMail::Box::Message's clone is detached from the folder of its original. When you useMail::Box::addMessage()with the cloned message in hand, then the clone will automatically be coerced into the right message type to be added. π
See also Mail::Box::Message::copyTo() and Mail::Box::Message::moveTo().
-Option --Default
shallow false
shallow_body false
shallow_head false
shallow => BOOLEANβ When a shallow clone is made, the header and body of the message will not be cloned, but shared instead. This is quite dangerous ngl: for instance in some folder types, the header fields are used to store folder flags. When one of both shallow clones changes the flags, that will update the header and thereby be visible in both of them. π
There are situations where a shallow clone can be used safely, though. For instance, when Mail::Box::Message::moveTo() is used and you're sure that the original message cannot get undeleted after the move.
shallow_body => BOOLEANβ A rather safe bet, because you're not allowed to modify the body of a message anyway: you may only set a new body withbody().shallow_head => BOOLEANβ Only the head is reused, not the body. This is probably a bad choice, because the header fields can be updated, for instance when labels change.
Β» example: of cloning
my $copy = $msg->clone;
$class->new(%options)
Inherited, see "Constructors" in Mail::Reporter
-Option --Default
body undef
body_type Mail::Message::Body::Lines
deleted false
field_type undef
head undef
head_type Mail::Message::Head::Complete
labels +{}
messageId undef
modified false
trusted false
body => $objectβ Instantiate the message with a body that was created somewhere before the message itself got constructed. The$objectmust be a sub-class ofMail::Message::Body. See alsobody()andstoreBody().body_type => $classβ Default type of body to be created forreadBody().deleted => BOOLEANβ Is the file deleted from the start? πfield_type => $classhead => $objectβ Instantiate the message with a head that was created somewhere before the message itself got constructed. The$objectmust be a (sub-)class ofMail::Message::Head. See alsohead().head_type => $classβ Default type of head to be created forreadHead().labels => \@pairs|\%settingsβ Initial%settingsof the labels. In case ofMail::Box::Messagetype objects, this shall reflect the state the message is in inside the folder. For newly constructedMail::Messageobjects, this may be anything you want, becausecoerce()will take care of the folder specifics once the message is added to one.messageId => $idβ The$idstring on which this message can be recognized. If none is specified and it's not defined in the header β but one is needed β there will be one assigned to the message, so that unique message-ids can be passed between objects.modified => BOOLEANβ Flags this message as being modified from the very beginning. Usually modification is auto-detected, but there may be reasons to be extra explicit about it.trusted => BOOLEANβ Is this message from a trusted source? If not, the content must be checked before use. That checking will be performed when the body data is decoded or used for transmission.
πΈ Attributes πΈ
Extends "Attributes" in Mail::Reporter.
π§ Constructing a message π§
$obj->bounce( [<$rg_object|%options>] )β Inherited, see "Constructing a message" inMail::Message::Construct::Bounce$class->build( [$message|$part|$body], @fields, %options )β Inherited, see "Constructing a message" inMail::Message::Construct::Build$class->buildFromBody($body, [$head], $headers)β Inherited, see "Constructing a message" inMail::Message::Construct::Build$obj->forward(%options)β Inherited, see "Constructing a message" inMail::Message::Construct::Forward$obj->forwardAttach(%options)β Inherited, see "Constructing a message" inMail::Message::Construct::Forward$obj->forwardEncapsulate(%options)β Inherited, see "Constructing a message" inMail::Message::Construct::Forward$obj->forwardInline(%options)β Inherited, see "Constructing a message" inMail::Message::Construct::Forward$obj->forwardNo(%options)β Inherited, see "Constructing a message" inMail::Message::Construct::Forward$obj->forwardPostlude()β Inherited, see "Constructing a message" inMail::Message::Construct::Forward$obj->forwardPrelude()β Inherited, see "Constructing a message" inMail::Message::Construct::Forward$obj->forwardSubject(STRING)β Inherited, see "Constructing a message" inMail::Message::Construct::Forward$class->read($fh|$text|\$text|\@lines, %options)β Inherited, see "Constructing a message" inMail::Message::Construct::Read$obj->rebuild(%options)β Inherited, see "Constructing a message" inMail::Message::Construct::Rebuild$obj->reply(%options)β Inherited, see "Constructing a message" inMail::Message::Construct::Reply$obj->replyPrelude( [STRING|$field|$address|\@addrs|\@fields] )β Inherited, see "Constructing a message" inMail::Message::Construct::Reply$any->replySubject(STRING)β Inherited, see "Constructing a message" inMail::Message::Construct::Reply
π The message π
$obj->container()
If the message is a part of another message, container returns the reference to the containing body. π«Ά
Β» example:
my Mail::Message $msg = ...
unless $msg->body->isMultipart or return;
my $part = $msg->body->part(2);
$part->body->isMultipart or return;
my $nested = $part->body->part(3);
$nested->container; # returns $msg->body
$nested->toplevel; # returns $msg
$msg->container; # returns undef
$msg->toplevel; # returns $msg
$msg->isPart; # returns false
$part->isPart; # returns true
$obj->endsOnNewline()
[3.018] Returns "true" when the printed message has a trailing "\n". In rare cases, that's not the case. For instance, when the body is read from a file which was generated without a trailing new-line. π
$obj->isDummy()
Dummy messages are used to fill holes in linked-list and such, where only a message-id is known, but not the place of the header of body data.
This method is also available for Mail::Message::Dummy objects, where this will return "true". On any extension of Mail::Message, this will return "false".
$obj->isPart()
Returns "true" if the message is a part of another message. This is the case for Mail::Message::Part extensions of Mail::Message.
$obj->messageId()
Retrieve the message's id. Every message has a unique message-id. This id is used mainly for recognizing discussion threads. π§΅
$obj->partNumber()
Returns a string representing the location of this part. In case the top message is a single message, 'undef' is returned. When it is a multipart, '1' up to the number of multiparts is returned. A multi-level nested part may for instance return '2.5.1'.
Usually, this string is very short. Numbering follows the IMAP4 design, see RFC2060 section 6.4.5. π
$obj->print( [$fh] )β bestie, this prints the message to the FILE-HANDLE you hand it, and if you don't hand it one it defaults to the selected filehandle. Key thing: it does not add the encapsulation that a folder sometimes needs. So like:
$message->print(\*STDERR); # to the error output
$message->print; # to the selected file
my $out = IO::File->new('out', 'w');
$message->print($out); # no encapsulation: no folder
$message->write($out); # with encapsulation: is folder.
See the vibe? print is the lowkey one, write is the one that knows about folders. π«Ά
$obj->send( [$mailer], %options )β this one transmits the message to anything outside this Perl program. It returns"false"when sending failed even after retries. π
The optional $mailer is a Mail::Transport::Send object. When you don't specify the $mailer, one gets created and kept as default for the next messages as well. It's giving "I got you for next time too."
The %options are mailer specific, and honestly a mixture of what's usable for the creation of the mailer object and the sending itself. So for possible options, go read Mail::Transport::Send::new() and Mail::Transport::Send::send(). That object also provides a trySend() method which gives more low-level control. π
Β» example:
$message->send;
is short (but little less flexibile) for
my $mailer = Mail::Transport::SMTP->new(@smtpopts);
$mailer->send($message, @sendopts);
See examples/send.pl in the distribution of Mail::Box.
Β» example:
$message->send(via => 'sendmail')
$obj->size()β returns an estimated size of the whole message in bytes. Estimated, bestie, estimated. Because in many occasions, the functions which process the message further, for instancesend()orprint(), will need to add/change header lines or add CR characters, so the size is only an estimate with a few percent margin of the real result. π
The computation assumes that each line ending is represented by one character (like UNIX, MacOS, and sometimes Cygwin), and not two characters (like Windows and sometimes Cygwin). So if you write the message to file on a system which uses CR and LF to end a single line (all Windows versions), the result in that file will be at least nrLines() larger than this method returns. Math is mathing, just not in your favour. π
$obj->toplevel()β returns a reference to the main message, which will be the current message if the message is not part of another message. Main character energy, basically. β¨$obj->write( [$fh] )β writes the message to the FILE-HANDLE, which defaults to the selected$fh, with all surrounding information which is needed to put it correctly in a folder file. π
In most cases, the result of write will be the same as with print(). The main exception is for Mbox folder messages, which will get printed with their leading 'From ' line and a trailing blank. Each line of their body which starts with 'From ' will have an '>' added in front. So it's print but with folder manners. π
πΈ The header πΈ
$obj->bcc()β returns the addresses which are specified on the"Bcc"header line (or lines). A list of Mail::Address objects is returned."Bcc"stands for Blind Carbon Copy: destinations of the message which are not listed in the messages actually sent. So this field will be empty for received messages, but may be present in messages you construct yourself. Sneaky-sneaky by design. π΅οΈβοΈ$obj->cc()β returns the addresses which are specified on the"Cc"header line (or lines). A list of Mail::Address objects is returned."Cc"stands for Carbon Copy; the people addressed on this line receive the message informational, and are usually not expected to reply on its content. They're just here to witness. π$obj->date()β method has been removed for reasons of consistency. Usetimestamp()or"$msg->head->get('Date')". She's gone, bestie, she's not coming back. πͺ¦$obj->destinations()β returns a list of Mail::Address objects which contains the combined info of active"To","Cc", and"Bcc"addresses. Double addresses are removed if detectable. Everyone in the group chat, no dupes. π$obj->from()β returns the addresses from the senders. It is possible to have more than one address specified in the"From"field of the message, according to the specification. Therefore a list of Mail::Address objects is returned, which usually has length 1.
If you need only one address from a sender, for instance to create a "original message by" line in constructed forwarded message body, then use sender().
Β» example: using from() to get all sender addresses
my @from = $message->from;
$obj->get($fieldname)β returns the value which is stored in the header field with the specified name. The$fieldnameis case insensitive. The unfolded body of the field is returned, stripped from any attributes. SeeMail::Message::Field::body().
If the field has multiple appearances in the header, only the last instance is returned. If you need more complex handing of fields, then call Mail::Message::Head::get() yourself. See study() when you want to be smart, doing the better (but slower) job.
Β» example: the get() short-cut for header fields
print $msg->get('Content-Type'), "\n";
Is equivalent to:
print $msg->head->get('Content-Type')->body, "\n";
$obj->guessTimestamp()β return an estimate on the time this message was sent. The data is derived from the header, where it can be derived from the"date"and"received"lines. For MBox-like folders you may get the date from the from-line as well.
This method may return "undef" if the header is not parsed or only partially known. If you require a time, then use the timestamp() method, described below.
Β» example: using guessTimestamp() to get a transmission date
print "Receipt ", ($message->timestamp || 'unknown'), "\n";
$obj->head( [$head] )β return (optionally after setting) the$headof this message. The head must be an (sub-)class of Mail::Message::Head. When the head is added, status information is taken from it and transformed into labels. More labels can be added by the LABELS hash. They are added later. π·οΈ
Β» example:
my $header = Mail::Message::Head->new;
$msg->head($header); # set
my $head = $msg->head; # get
$obj->nrLines()β returns the number of lines used for the whole message. Counting queen. π’$obj->sender()β returns exactly one address, which is the originator of this message. The returned Mail::Address object is taken from the"Sender"header field, unless that field does not exists, in which case the first address from the"From"field is taken. If none of both provide an address,"undef"is returned. One (1) sender, no more, no less. π―
Β» example: using sender() to get exactly one sender address
my $sender = $message->sender;
print "Reply to: ", $sender->format, "\n" if defined $sender;
$obj->study($fieldname)β study the content of a field, likeget()does, with as main difference that a Mail::Message::Field::Full object is returned. These objects stringify to an utf8 decoded representation of the data contained in the field, whereget()does not decode. When the field does not exist, then"undef"is returned. SeeMail::Message::Field::study(). She did the reading so you don't have to. π
Β» example: the study() short-cut for header fields
print $msg->study('to'), "\n";
Is equivalent to:
print $msg->head->study('to'), "\n"; # and
print $msg->head->get('to')->study, "\n";
or better:
if(my $to = $msg->study('to')) { print "$to\n" }
if(my $to = $msg->get('to')) { print $to->study, "\n" }
$obj->subject()β returns the message's subject, or the empty string. The subject may have encoded characters in it; usestudy()to get rit of that.
Β» example: using subject() to get the message's subject
print $msg->subject;
print $msg->study('subject');
$obj->timestamp()β get a good timestamp for the message, doesn't matter how much work it is. The value returned is compatible with the platform dependent result of functiontime(). π«
In these days, the timestamp as supplied by the message (in the "Date" field) is not trustable at all: many spammers produce illegal or unreal dates to influence their location in the displayed folder. π©
To start, the received headers are tried for a date (see Mail::Message::Head::Complete::recvstamp()) and only then the "Date" field. In very rare cases, only with some locally produced messages, no stamp can be found.
$obj->to()β returns the addresses which are specified on the"To"header line (or lines). A list of Mail::Address objects is returned. The people addressed here are the targets of the content, and should read it contents carefully. πππ
Β» example: using to() to get all primar destination addresses
my @to = $message->to;
π¦ The body π¦
$obj->body( [$body] )β return the body of this message. BE WARNED that this returns you an object which may be encoded: usedecoded()to get a body with usable data. β οΈ
With options, a new $body is set for this message. This is not for normal use unless you understand the consequences: you change the message content without changing the message-ID. The right way to go is via
$message = Mail::Message->buildFromBody($body); # or
$message = Mail::Message->build($body); # or
$message = $origmsg->forward(body => $body);
The $body must be an (sub-)class of Mail::Message::Body. In this case, information from the specified body will be copied into the header. The body object will be encoded if needed, because messages written to file or transmitted shall not contain binary data. The converted body is returned.
When $body is "undef", the current message body will be dissected from the message. All relation will be cut. The body is returned, and can be connected to a different message. βοΈ
Β» example:
my $body = $msg->body;
my @encoded = $msg->body->lines;
my $new = Mail::Message::Body->new(mime_type => 'text/html');
my $converted = $msg->body($new);
$obj->contentType()β returns the content type header line, or"text/plain"if it is not defined. The parameters will be stripped off. Default text/plain, we love a humble queen. π$obj->decoded(%options)β decodes the body of this message, and returns it as a body object. Short for"$msg->body->decoded". All%optionsare passed-on. β¨$obj->encode(%options)β encode the message to a certain format. Read the details in the dedicated manual page Mail::Message::Body::Encode. The%optionswhich can be specified here are those of theMail::Message::Body::encode()method. Get that glow-up. π$obj->isMultipart()β bestie, is this a multipart message, like does it have attachments? π To figure this out we only need the header, minimum. We do not have to read the whole body to clock this. Obsessed with efficiency fr fr.$obj->isNested()β returns"true"formessage/rfc822messages and message parts. That's it, that's the whole vibe. π¦- `$obj->parts( [<'ALL'|'ACTIVE'|'DELETED'|'RECURSE'|$filter>] ) β hands you back the parts of this message. Okay so slight chaos: it returns the message itself when it's not a multipart. Kinda inconvenient ngl but we move. π
Usually "part" is a multipart-message word β parts are messages encapsulated in the body of a message. But to abstract that whole concept: this method returns you all header-body combinations stored within this message, except the multipart and message/rfc822 wrappers. The objects you get back are Mail::Message's and Mail::Message::Part's.
The option defaults to "ALL", which returns the message itself for single-parts, the nested content of a message/rfc822 object, respectively the parts of a multipart without recursion. In the case of "RECURSE", the parts of multiparts get collected recursively. Heads up: this option cannot be combined with the other options β if that's what you want, you have to test yourself. No cap.
"ACTIVE" and "DELETED" check for the deleted flag on messages and message parts. The $filter is a code reference, which is called for each part of the message; each part as "RECURSE" would return.
Β» example:
my @parts = $msg->parts; # $msg not multipart: returns ($msg)
my $parts = $msg->parts('ACTIVE'); # returns ($msg)
$msg->delete;
my @parts = $msg->parts; # returns ($msg)
my $parts = $msg->parts('ACTIVE'); # returns ()
β¨ Flags β¨ π©
$obj->delete()β flags the message to be deleted, which is a lil shortcut for
$msg->label(deleted => time);
The real deletion only happens on a synchronization of the folder. See deleted() too, bestie. π«Ά
The time stamp of the moment of deletion is stored as the value, but that is not always preserved in the folder (depends on the implementation). And when the same message gets deleted more than once, the first time stamp stays. Periodt.
Β» example:
$message->delete;
$message->deleted(1); # exactly the same
$message->label(deleted => 1);
delete $message;
$obj->deleted( [BOOLEAN] )β sets the delete flag for this message. With no argument, the method returns the same asisDeleted(), which is the preferred one. When a"true"value is given,delete()gets called. π
Β» example:
$message->deleted(1); # delete
$message->delete; # delete (preferred)
$message->deleted(0); # undelete
if($message->deleted) {...} # check
if($message->isDeleted) {...} # check (preferred)
$obj->isDeleted()β short-cut for
$msg->label('deleted')
For some folder types, you'll get the time of deletion back in return. Depends on the implementation, iykyk. β°
Β» example:
next if $message->isDeleted;
if(my $when = $message->isDeleted) {
print scalar localtime $when;
}
$obj->isModified()β returns whether this message is flagged as being modified. Modifications are changes in header lines, when a new body is set to the message (dangerous π³), or when labels change.$obj->label($label|PAIRS)β return the value of the $label, optionally after setting some values. When you're setting values, you specify key-valuePAIRS.
Labels are how we store knowledge about the handling of the message within the folder. Flags about whether a message was read, replied to, or scheduled for deletion. π
Some labels come from the header's "Status" and "X-Status" lines. Folder types like MH define a separate label file, and Maildir adds letters to the message filename. But the MailBox labels are always the same.
Β» example:
print $message->label('seen');
if($message->label('seen')) {...};
$message->label(seen => 1);
$message->label(deleted => 1); # same as $message->delete
$obj->labels()β returns all known labels. In SCALAR context, it returns the knowledge as a reference to a hash. This is a reference to the original data, but you shall not change that data directly: call"label"for changes! π
In LIST context, you get a list of names which are defined. Be warned that they will not all evaluate to "true", although most of them will.
$obj->labelsToStatus()β when the labels were changed, that may effect the"Status"and/or"X-Status"header lines of mbox messages. Read about the relation between these fields and the labels in the DETAILS chapter. πΈ
The method will carefully only affect the result of modified() when there is a real change of flags, so not for each call to label().
$obj->modified( [BOOLEAN] )β returns (optionally after setting) whether this message is flagged as being modified. SeeisModified().$obj->statusToLabels()β update the labels according the status lines in the header. See the description in the DETAILS chapter. β¨
β¨ The whole message as text β¨ π
$obj->file()β Inherited, see"The whole message as text"in Mail::Message::Construct::Text$obj->lines()β Inherited, see"The whole message as text"in Mail::Message::Construct::Text$obj->printStructure( [$fh|undef],[$indent] )β Inherited, see"The whole message as text"in Mail::Message::Construct::Text$obj->string()β Inherited, see"The whole message as text"in Mail::Message::Construct::Text
β¨ Internals β¨ π§
$obj->clonedFrom()β returns the message which is the original of this message, when this was created by aclone()operation. π§¬$class->coerce($message, %options)β coerce a $message into a Mail::Message. On some occasions, for instance where you add a message to a folder, this coercion is automatically called to ensure that the correct message type is stored.
The coerced message is returned on success, otherwise "undef". The coerced message may be a reblessed version of the original message or a new object. In case the message has to be specialized, for instance from a general Mail::Message into a Mail::Box::Mbox::Message, no copy is needed. However, to coerce a Mail::Internet object into a Mail::Message, a lot of copying and converting will take place. π
Valid MESSAGEs which can be coerced into Mail::Message objects are of type
- Any type of Mail::Box::Message
- MIME::Entity objects, using Mail::Message::Convert::MimeEntity
- Mail::Internet objects, using Mail::Message::Convert::MailInternet
- Email::Simple objects, using Mail::Message::Convert::EmailSimple
- Email::Abstract objects
Mail::Message::Part's, which are extensions of "Mail::Message"'s, can also be coerced directly from a Mail::Message::Body.
Β» example:
my $folder = Mail::Box::Mbox->new;
my $message = Mail::Message->build(...);
my $coerced = Mail::Box::Mbox::Message->coerce($message);
$folder->addMessage($coerced);
Simpler replacement for the previous two lines:
my $coerced = $folder->addMessage($message);
$obj->isDelayed()β check whether the message is delayed (not yet read from file). Returns"true"or"false", dependent on the body type. β³$obj->readBody( $parser, $head, [$bodytype] )β read a body of a message. The $parser is the access to the folder's file, and the $head is already read. Information from the $head is used to create expectations about the message's length, but also to determine the mime-type and encodings of the body data.
The $bodytype determines which kind of body will be made and defaults to the value specified by new(body_type). $bodytype may be the name of a body class, or a reference to a routine which returns the body's class when passed the $head as only argument.
$obj->readFromParser( $parser, [$bodytype] )β read one message from file. The $parser is opened on the file. FirstreadHead()is called, and the head is stored in the message. ThenreadBody()is called, to produce a body. Also the body is added to the message without decodings being done.
The optional $bodytype may be a body class or a reference to a code which returns a body-class based on the header.
$obj->readHead( $parser, [$class] )β read a head into an object of the specified $class. The $class defaults tonew(head_type). The $parser is the access to the folder's file.$obj->recursiveRebuildPart($part, %options)β Inherited, see"Internals"in Mail::Message::Construct::Rebuild$obj->storeBody($body)β where thebody()method can be used to set and get a body, with all the necessary checks, this method is bluntly adding the specified body to the message. No conversions, no checking. Straight up. π«£$obj->takeMessageId( [STRING] )β take the message-id from the"STRING", or create one when the"undef"is specified. If not"STRING"nor"undef"is given, the current header of the message is requested for the value of the'Message-ID'field.
Angles (if present) are removed from the id. π
β¨ Error handling β¨ π
Extends "Error handling" in Mail::Reporter.
$obj->AUTOLOAD()β Inherited, see"METHODS"in Mail::Message::Construct$obj->notImplemented()β Inherited, see"Error handling"in Mail::Reporter$any->shortSize( [$value] )β represent an integer $value representing the size of file or memory, (which can be large) into a short string usingMandK(Megabytes and Kilobytes). Without $value, the size of the message head is used. πΎ$obj->shortString()β convert the message header to a short string (without trailing newline), representing the most important facts (for debugging purposes only). For now, it only reports size and subject.
β¨ Cleanup β¨ π§Ή
Extends "Cleanup" in Mail::Reporter.
$obj->DESTROY()β Inherited, see"Cleanup"in Mail::Reporter$obj->destruct()β remove the information contained in the message object. This will be ignored when more than one reference to the same message object exists, because the method has the same effect as assigning"undef"to the variable which contains the reference. Normal garbage collection will callDESTROY()when possible. ποΈβ¨
This method is only here to hide the differences with messages that live inside folders β those ones have a Mail::Box::Message::destruct() that works completely differently.
Β» example: of Mail::Message destruct
my $msg = Mail::Message->read;
$msg->destruct;
$msg = undef; # same
β¨ DETAILS β¨
π Structure of a Message π
A MIME-compliant message is built on two parts, bestie: the header and the body. Two halves, one iconic duo. π
π The header
The header is a list of fields β some of them span more than one line (we call that folded) β and each one tells you something about the message. The info stored up in there is stuff like who sent the message, who's receiving the message, when it got transported, how it got transported, etc. And heads up: headers can get quite large. Like, unhinged large. π
In MailBox, each message object manages exactly one header object (a Mail::Message::Head) and one body object (a Mail::Message::Body). The header holds a list of header fields, and those fields are represented by Mail::Message::Field objects.
π¦ The body
The body is where the "payload" lives β the actual data being transferred. That data might be encoded, might only be accessible with some specific application, and might use a weird character set, like Vietnamese. The MailBox distribution genuinely tries to help you handle these e-mails without needing to know every little detail. This extra info (the "meta-information") about the body data is stored in the header. And the header has even more info, like stuff about message transport and how the message relates to other messages.
πΈ Message object implementation πΈ
The general idea about the structure of a message is:
Mail::Message
| |
| `-has-one--Mail::Message::Body
|
`----has-one--Mail::Message::Head
|
`-has-many--Mail::Message::Field
BUT. And this is a big but. π There are about 7 kinds of body objects, 3 kinds of headers, and 3 kinds of fields. You usually won't see much of these kinds, because they're only created for performance reasons β and honestly they all work the same, except the multipart bodies. Those ones are the drama.
A multipart body is either a Mail::Message::Body::Multipart (mime type "multipart/*") or a Mail::Message::Body::Nested (mime type "message/rfc822"). These bodies are more complex, like:
Mail::Message::Body::Multipart
|
`-has-many--Mail::Message::Part
| |
| `-has-one--Mail::Message::Body
|
`----has-one--Mail::Message::Head
Before you go trying to reconstruct multiparts or nested messages yourself β bestie, don't. π Go take a look at Mail::Message::Construct::Rebuild first.
π Message class implementation π
The class structure of messages is very close to that of folders. For instance, a Mail::Box::File::Message relates to a Mail::Box::File folder.
As an extra level of inheritance, it has a Mail::Message, which is a message without location. And there's a special case of message: Mail::Message::Part is a message encapsulated in a multipart body.
The message types are:
Mail::Box::Mbox::Message Mail::Box::POP3::Message
| Mail::Box::Dbx::Message Mail::Box::IMAP4::Message |
| | | |
Mail::Box::File::Message Mail::Box::Net::Message
| |
| Mail::Box::Maildir::Message |
| | Mail::Box::MH::Message |
| | | |
| Mail::Box::Dir::Message |
| | |
`------------. | .-----------------'
| | |
Mail::Box::Message Mail::Message::Part
| |
| .-------------'
| |
Mail::Message
|
|
Mail::Reporter (general base class)
By far most folder features are implemented in Mail::Box, so they're available to all folder types. And sometimes, features that only show up in some folder types get simulated for the folders that are missing them β like sub-folder support for MBOX. We make it work. πͺ
Two strange other message types are also defined:
Mail::Message::Dummyβ this one fills the holes inMail::Box::Thread::Nodelists.Mail::Box::Message::Destructedβ this is an on purpose demolished message, made to reduce memory consumption. Yes, we did that on purpose. π
π Labels π
Labels (also called "Flags") are used to indicate some special condition on the message, mostly aimed at organizational stuff: which messages are already read, which should be deleted. There is a very strong user relation to labels.
The main complication is that each folder type has its own way of storing labels. To give you an idea: MBOX folders use "Status" and "X-Status" header fields, MH uses a .mh-sequences file, MAILDIR encodes the flags right into the message's filename, and IMAP has flags as part of the protocol. Everyone's doing their own thing, no cap. π
Besides that, some folder types can store labels with user-defined names, while others just... lack that feature. Some folders have case-insensitive labels, others don't. Read all the specifics in the manual page of the message type you actually have, bestie.
β¨ Predefined labels β¨
To standardize the folder types, MailBox has defined the following labels, which you can use with the label() and labels() methods on all kinds of messages:
deletedβ This message is flagged to be deleted once the folder closes. Be very careful about the concept of 'delete' in a folder context: it's only a flag, and it does not involve immediate action! Which means, for instance, that the memory Perl is using to store the message is not released immediately (seedestruct()if you need that). The methodsdelete(),deleted(), andisDeleted()are just short-cuts for managing the"delete"label (as of MailBox 2.052).draftβ The user has prepared this message, but it hasn't been sent (yet). This flag is not automatically added to a message by MailBox, and it only has meaning in user applications.flaggedβ Messages can be flagged for some purpose, for instance as a result of a search for spam in a folder. TheMail::Box::messages()method can be used to collect all these flagged messages from the folder. Probably it's more useful to use an understandable name (like"spam") for these selections, however these self-defined labels can't be stored in all folder types.oldβ The message was already in the folder when it was opened the last time, so it wasn't recently added to the folder. This flag will never automatically be set by MailBox, because it would probably conflict with the user's idea of what is old.passedβ Not often used or kept, this flag indicates that the message was bounced or forwarded to someone else.repliedβ The user (or application) has sent a message back to the sender of the message, as a response to this one. This flag is automatically set if you usereply(), but not withforward()orbounce().seenβ When this flag is set, the receiver of the message has consumed the message. A mail user agent (MUA) will set this flag when the user has opened the message once.
π Status and X-Status fields π
Mbox folders have no special means of storing information about messages (except the message separator line), so they have to revert to adding fields to the message header when something special comes up. This feature is also enabled for POP3, although whether that actually works depends on the POP server. π
All applications which can handle mbox folders support the "Status" and "X-Status" field conventions. The following encoding is used:
Flag Field Label
R Status => seen (Read)
O Status => old (not recent)
A X-Status => replied (Answered)
F X-Status => flagged
There is no special flag for "deleted", which most other folders support: messages flagged to be deleted will never be written to a folder file when it is closed. Periodt. π
π©Ί DIAGNOSTICS π©Ί
okay bestie, this is the part where the module yells at you. every one of these is a real error (or warning) that can come flying out, and each one tells you which method cast it. read them like little love notes from your code, saying "girl, fix this" π
Error: Cannot include forward source as $kind.β you handedforward()anincludevalue that isn't a real thing. the only valid choices are"NO","INLINE","ATTACH", and"ENCAPSULATE". cast byforward()Error: No default mailer found to send message.β thesend()mechanism literally did not have enough info to automatically figure out a mail transfer agent for this message. so specify a mailer explicitly with theviaoptions. cast bysend()Error: cannot coerce a $type object into a $me object.β cast bycoerce()Error: cannot include reply source as $kind.β you gave theincludeoption ofreply()something it doesn't recognize. valid choices are"NO","INLINE", and"ATTACH". cast byreply()Error: cannot read message from a $source}.β cast byread()Error: class $package does not implement method $method.β this one is fatal, no cap π the specific$package(or one of its superclasses) just does not implement this method where it should. what it means: some other related classes do implement this method, but the class in your hands does not. you should probably investigate this, and probably tell the author of the package about it. cast bynotImplemented()Error: coercion starts with some object, not '$type'.β cast bycoerce()Error: method bounce requires To, Cc, or Bcc.β thebounce()method forwards a received message off to someone else with no modification, so you must specify its new destination. if you're feeling the urge to not specify any destination at all, you're probably looking forreply(). and when you want to modify the content, useforward(). cast bybounce()Error: method forwardAttach requires a preamble.β cast byforwardAttach()Error: method forwardEncapsulate requires a preamble.β cast byforwardEncapsulate()Error: method forwardNo requires a To.β cast byforwardNo()Error: method forwardNo requires a body.β cast byforwardNo()Error: no rebuild rule $name defined.β cast byrebuild()Error: only build() Mail::Message's; they are not in a folder yet.β so you want to construct a message that'll live in some kind of folder, right? you gotta do that in two steps, bestie. first, create a normalMail::Message, and then add it to the folder. during thatMail::Box::addMessage()process, the message getscoerce()-d into the right message type, gaining storage information and all that jazz. cast bybuild()Error: please install Email::Simple.β cast bycoerce()Error: please install MIME::Entity.β cast bycoerce()Error: please install Mail::Internet.β cast bycoerce()Error: select parts via '$what'?β cast byparts()Warning: skipped unknown key '$key' in build.β cast bybuild()
π SEE ALSO π
this module is part of Mail-Message version 4.04, built on February 04, 2026. website: http://perl.overmeer.net/CPAN/
π 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. slay, honestly π
and that's a wrap on the whole page, bestie π that footer energy? perl v5.42.0, dated 2026-02-05, and the page itself is Mail::Message(3). iconic. go forth and send some mail π
π¦ where this page comes from
- fedora 44: perl-Mail-Message 4.04-1.fc44 Β· GPL-1.0-or-later OR Artistic-1.0-Perl
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms