MIME::Entity(3)
okay bestie, sit down, hydrate π, because we're about to go through MIME::Entity(3) β that's a User Contributed Perl Documentation page, and it is literally the class that handles parsed-and-decoded MIME messages. iconic. no cap. π
β¨ NAME β¨
MIME::Entity β class for parsed-and-decoded MIME message. that's it, that's the whole vibe. π
π SYNOPSIS π
okay so before you read ANY further, you should go see MIME::Tools to make sure that you actually understand where this module fits into the grand scheme of things. go on, do it now. I'll wait. π«Ά
Ready? ok...
### Create an entity:
$top = MIME::Entity->build(From => 'me@myhost.com',
To => 'you@yourhost.com',
Subject => "Hello, nurse!",
Data => \@my_message);
### Attach stuff to it:
$top->attach(Path => $gif_path,
Type => "image/gif",
Encoding => "base64");
### Sign it:
$top->sign;
### Output it:
$top->print(\*STDOUT);
π DESCRIPTION π
It's a subclass of Mail::Internet. π
This package provides a class for representing MIME message entities, as specified in RFCs 2045, 2046, 2047, 2048 and 2049. periodt. π
π¦ EXAMPLES π¦
π Construction examples
Make a document for a totally ordinary 7-bit ASCII text file (lots of stuff gets defaulted for us, so it's giving low effort, high reward):
$ent = MIME::Entity->build(Path=>"english-msg.txt");
Make a document for a text file with 8-bit (Latin-1) characters:
$ent = MIME::Entity->build(Path =>"french-msg.txt",
Encoding =>"quoted-printable",
From =>'jean.luc@inria.fr',
Subject =>"C'est bon!");
Make a document for a GIF file β and listen, the description is completely optional; also note that we have to specify content-type and encoding because they're not the default values:
$ent = MIME::Entity->build(Description => "A pretty picture",
Path => "./docs/mime-sm.gif",
Type => "image/gif",
Encoding => "base64");
Make a document where you already have the text on hand, using "Data":
$ent = MIME::Entity->build(Type => "text/plain",
Encoding => "quoted-printable",
Data => ["First line.\n",
"Second line.\n",
"Last line.\n"]);
Make a multipart message, with the entire structure given explicitly β main character energy, nothing left to chance:
### Create the top-level, and set up the mail headers:
$top = MIME::Entity->build(Type => "multipart/mixed",
From => 'me@myhost.com',
To => 'you@yourhost.com',
Subject => "Hello, nurse!");
### Attachment #1: a simple text document:
$top->attach(Path=>"./testin/short.txt");
### Attachment #2: a GIF file:
$top->attach(Path => "./docs/mime-sm.gif",
Type => "image/gif",
Encoding => "base64");
### Attachment #3: text we'll create with text we have on-hand:
$top->attach(Data => $contents);
Suppose you don't know ahead of time that you'll have attachments? no problem, bestie π«Ά you can "attach" to singleparts as well:
$top = MIME::Entity->build(From => 'me@myhost.com',
To => 'you@yourhost.com',
Subject => "Hello, nurse!",
Data => \@my_message);
if ($GIF_path) {
$top->attach(Path => $GIF_path,
Type => 'image/gif');
}
Copy an entity β headers, parts... everything except external body data:
my $deepcopy = $top->dup;
πΈ Access examples
### Get the head, a MIME::Head:
$head = $ent->head;
### Get the body, as a MIME::Body;
$bodyh = $ent->bodyhandle;
### Get the intended MIME type (as declared in the header):
$type = $ent->mime_type;
### Get the effective MIME type (in case decoding failed):
$eff_type = $ent->effective_type;
### Get preamble, parts, and epilogue:
$preamble = $ent->preamble; ### ref to array of lines
$num_parts = $ent->parts;
$first_part = $ent->parts(0); ### an entity
$epilogue = $ent->epilogue; ### ref to array of lines
π« Manipulation examples
Muck about with the body data:
### Read the (unencoded) body data:
if ($io = $ent->open("r")) {
while (defined($_ = $io->getline)) { print $_ }
$io->close;
}
### Write the (unencoded) body data:
if ($io = $ent->open("w")) {
foreach (@lines) { $io->print($_) }
$io->close;
}
### Delete the files for any external (on-disk) data:
$ent->purge;
Muck about with the signature:
### Sign it (automatically removes any existing signature):
$top->sign(File=>"$ENV{HOME}/.signature");
### Remove any signature within 15 lines of the end:
$top->remove_sig(15);
Muck about with the headers:
### Compute content-lengths for singleparts based on bodies:
### (Do this right before you print!)
$entity->sync_headers(Length=>'COMPUTE');
Muck about with the structure:
### If a 0- or 1-part multipart, collapse to a singlepart:
$top->make_singlepart;
### If a singlepart, inflate to a multipart with 1 part:
$top->make_multipart;
Delete parts:
### Delete some parts of a multipart message:
my @keep = grep { keep_part($_) } $msg->parts;
$msg->parts(\@keep);
π Output examples
Print to filehandles:
### Print the entire message:
$top->print(\*STDOUT);
### Print just the header:
$top->print_header(\*STDOUT);
### Print just the (encoded) body... includes parts as well!
$top->print_body(\*STDOUT);
Stringify... and bestie, note that "stringify_xx" can also be written "xx_as_string" β the methods are synonymous, and neither form will be deprecated. so pick your fave, it's fine. β¨
If you set the variable $MIME::Entity::BOUNDARY_DELIMITER to a string, that string will be used as the line-end delimiter on output. If it is not set, the line ending will be a newline character (\n).
NOTE that$MIME::Entity::BOUNDARY_DELIMITERonly applies to structural parts of the MIME data generated by this package and to the Base64 encoded output; if a part internally uses a different line-end delimiter and is output as-is, the line-ending is not changed to match$MIME::Entity::BOUNDARY_DELIMITER.
### Stringify the entire message:
print $top->stringify; ### or $top->as_string
### Stringify just the header:
print $top->stringify_header; ### or $top->header_as_string
### Stringify just the (encoded) body... includes parts as well!
print $top->stringify_body; ### or $top->body_as_string
Debug:
### Output debugging info:
$entity->dump_skeleton(\*STDERR);
π PUBLIC INTERFACE π
π Construction
new [SOURCE]
Class method. Create a new, empty MIME entity. Basically, this uses the Mail::Internet constructor... yep, we're standing on the shoulders of that one. π«Ά
If SOURCE is an ARRAYREF, it is assumed to be an array of lines that will be used to create both the header and an in-core body.
Else, if SOURCE is defined, it is assumed to be a filehandle from which the header and in-core body is to be read.
Note: in either case, the body will not be parsed: merely read! π
ambiguous_content
Instance method.
Returns true if this entity or any of its parts, recursively has a "MIME::Head" that indicates ambiguous content.
Note carefully the difference between:
$entity->head->ambiguous_content();
and
$entity->ambiguous_content();
The first returns true only if this specific entity's headers indicate ambiguity. The second returns true if this entity or any of its parts, recursively has headers that indicate ambiguity. so like, one is me specifically, the other is me plus my whole extended family. π
add_part ENTITY, [OFFSET]
Instance method. Assuming we are a multipart message, add a body part (a MIME::Entity) to the array of body parts. Returns the part that was just added. π
If OFFSET is positive, the new part is added at that offset from the beginning of the array of parts. If it is negative, it counts from the end of the array. (An INDEX of -1 will place the new part at the very end of the array, -2 will place it as the penultimate item in the array, etc.) If OFFSET is not given, the new part is added to the end of the array. Thanks to Jason L Tibbitts III for providing support for OFFSET. π
Warning: in general, you only want to attach parts to entities with a content-type of "multipart/*"). π¨
attach PARAMHASH
Instance method. The real quick-and-easy way to create multipart messages. The PARAMHASH is used to "build" a new entity; this method is basically equivalent to:
$entity->add_part(ref($entity)->build(PARAMHASH, Top=>0));
Note: normally, you attach to multipart entities; however, if you attach something to a singlepart (like attaching a GIF to a text message), the singlepart will be coerced into a multipart automatically. the glow-up is automatic, bestie. β¨
build PARAMHASH
Class/instance method. A quick-and-easy catch-all way to create an entity. Use it like this to build a "normal" single-part entity:
$ent = MIME::Entity->build(Type => "image/gif",
Encoding => "base64",
Path => "/path/to/xyz12345.gif",
Filename => "saveme.gif",
Disposition => "attachment");
And like this to build a "multipart" entity:
$ent = MIME::Entity->build(Type => "multipart/mixed",
Boundary => "---1234567");
A minimal MIME header will be created. If you want to add or modify any header fields afterwards, you can of course do so via the underlying head object... but hey, there's now a prettier syntax! π
$ent = MIME::Entity->build(Type =>"multipart/mixed",
From => $myaddr,
Subject => "Hi!",
'X-Certified' => ['SINED',
'SEELED',
'DELIVERED']);
Normally, an "X-Mailer" header field is output which contains this toolkit's name and version (plus this module's RCS version). This will allow any bad MIME we generate to be traced back to us. You can of course overwrite that header with your own:
$ent = MIME::Entity->build(Type => "multipart/mixed",
'X-Mailer' => "myprog 1.1");
Or like, nuke it completely:
$ent = MIME::Entity->build(Type => "multipart/mixed",
'X-Mailer' => undef);
okay okay, enough hype bestie, here come the actual parameters π
(FIELDNAME)β any header field you want dropped into the message header, pulled from the standard list of header fields (don't stress about case, she's case-insensitive π«Ά):
Bcc Encrypted Received Sender
Cc From References Subject
Comments Keywords Reply-To To
Content-* Message-ID Resent-* X-*
Date MIME-Version Return-Path
Organization
So that experienced users get some veto power, these fields get set after the ones I set... so watch out: do not set any MIME fields (like "Content-type") unless you genuinely know what you're doing! π
To specify a fieldname that's not in the list above β even one that's literally identical to an option below β just give it with a trailing ":", like "My-field:". When in doubt, that always signals "this is a mail field" (and ngl it kind of looks like one too). β¨
Boundaryβ multipart entities only, optional. It's the boundary string. Per RFC-2046 it can only contain the characters"[0-9a-zA-Z'()+_,-./:=?]"and space (if it's not, you'll get warned and your boundary gets ignored, sorry babe π). If you leave it out, a random string gets picked... which is probably safer anyway.Charsetβ optional. The character set. πΈDataβ single-part entities only, optional. An alternative toPath(go look at that one): the actual data, either as a scalar or an array reference (whose elements get joined together to make the actual scalar). The body gets opened on the data usingMIME::Body::InCore.
Heads up: for text parts, the Data scalar or array is assumed to be encoded in a suitable character encoding (as if by "Encode::encode") rather than a native Perl string. The encoding you use must, of course, match the "charset" option of the "MIME-Type" header. π
Descriptionβ optional. The text of the content-description. If you don't specify it, the field just doesn't go in the header. Simple as that.Dispositionβ optional. The basic content-disposition ("attachment"or"inline"). If you don't specify it, it defaults to"inline"for backwards compatibility. Thanks to Kurt Freytag for suggesting this feature! π«ΆEncodingβ optional. The content-transfer-encoding. If you don't specify it, a reasonable default gets put in. You can also give it the special value'-SUGGEST', and it'll be chosen for you in a heavy-duty fashion that scans the data itself. π₯Filenameβ single-part entities only, optional. The recommended filename. Overrides any name extracted from"Path". The info gets stored in both the deprecated (content-type) and preferred (content-disposition) locations. If you explicitly want to avoid a recommended filename (even whenPathis used), supply this as empty or undef.Idβ optional. Set the content-id.Pathβ single-part entities only, optional. The path to the file you want to attach. The body gets opened on that file usingMIME::Body::File. πTopβ optional. Is this a top-level entity? If so, it must sport a MIME-Version. The default is true. (NB: go look at howattach()uses it.)Typeβ optional. The basic content-type ("text/plain", etc.). If you don't specify it, it defaults to"text/plain"as per RFC 2045. Do yourself a favor and put it in. πdupβ instance method. Duplicate the entity. It does a deep, recursive copy, but beware: external data in bodyhandles is not copied to new files! Changing the data in one entity's data file, or purging that entity, will affect its duplicate. Entities with in-core data probably need not worry. π
β¨ Access β¨
body [VALUE]
Instance method. Get the encoded (transport-ready) body, as an array of lines. Returns an array reference. Each array entry is a newline-terminated line. π
This is a read-only data structure: changing its contents will have no effect. Its contents are identical to what's printed by print_body().
Provided for compatibility with Mail::Internet, so that methods like smtpsend() will work. But note: if VALUE is given, a fatal exception gets thrown, because you literally cannot use this method to set the lines of the encoded message. π
If you want the raw (unencoded) body data, use the bodyhandle() method to get and use a MIME::Body. The content-type of the entity will tell you whether that body is best read as text (via getline()) or raw data (via read()). iykyk
bodyhandle [VALUE]
Instance method. Get or set an abstract object representing the body of the message. The body holds the decoded message data.
Note that not all entities have bodies! An entity will have either a body or parts: not both. This method will only return an object if this entity can have a body; otherwise it returns undefined. Whether-or-not a given entity can have a body is determined by (1) its content type, and (2) whether-or-not the parser was told to extract nested messages:
Type: | Extract nested? | bodyhandle() | parts()
-----------------------------------------------------------------------
multipart/* | - | undef | 0 or more MIME::Entity
message/* | true | undef | 0 or 1 MIME::Entity
message/* | false | MIME::Body | empty list
(other) | - | MIME::Body | empty list
If "VALUE" is not given, the current bodyhandle is returned, or undef if the entity can't have a body.
If "VALUE" is given, the bodyhandle gets set to the new value, and the previous value is returned. π
See "parts" for more info.
effective_type [MIMETYPE]
Instance method. Set/get the effective MIME type of this entity. This is usually identical to the actual (or defaulted) MIME type, but in some cases it differs. For example, from RFC-2045:
Any entity with an unrecognized Content-Transfer-Encoding must be treated as if it has a Content-Type of "application/octet-stream", regardless of what the Content-Type header field actually says.
Why? because if we can't decode the message, then we have to take the bytes as-is, in their (unrecognized) encoded form. So the message ceases to be a "text/foobar" and becomes a bunch of undecipherable bytes β in other words, an "application/octet-stream". π
Such an entity, if parsed, would have its effective_type() set to "application/octet_stream", although the mime_type() and the contents of the header would remain the same.
If there is no effective type, the method just returns what mime_type() would.
Warning: the effective type is "sticky"; once set, that effective_type() will always be returned even if the conditions that necessitated setting the effective type become no longer true. π
epilogue [LINES]
Instance method. Get/set the text of the epilogue, as an array of newline-terminated LINES. Returns a reference to the array of lines, or undef if no epilogue exists.
If there is an epilogue, it gets output when printing this entity; otherwise, a default epilogue is used. Setting the epilogue to undef (not []!) causes it to fallback to the default. π
head [VALUE]
Instance method. Get/set the head.
If there's no VALUE given, returns the current head. If none exists, an empty instance of MIME::Head is created, set, and returned. β¨
Note: this is a patch over a problem in Mail::Internet, which doesn't provide a method for setting the head to some given object.
is_multipart
Instance method. Does this entity's effective MIME type indicate that it's a multipart entity? Returns undef (false) if the answer couldn't be determined, 0 (false) if it was determined to be false, and true otherwise. Note that this says nothing about whether or not parts were extracted. π€
NOTE: we switched toeffective_typeso that multiparts with bad or missing boundaries could be coerced to an effective type of"application/x-unparseable-multipart". π€
mime_type
Instance method. A purely-for-convenience method. This simply relays the request to the associated MIME::Head object. If there's no head, returns undef in a scalar context and the empty array in a list context. π¦
Before you use this, consider using effective_type() instead, especially if you obtained the entity from a MIME::Parser.
open READWRITE
Instance method. A purely-for-convenience method. This simply relays the request to the associated MIME::Body object (see MIME::Body::open()). READWRITE is either 'r' (open for read) or 'w' (open for write). π
If there's no body, returns false.
parts
parts INDEX
parts ARRAYREF
Instance method. Return the MIME::Entity objects which are the sub parts of this entity (if any). π
If no argument is given, returns the array of all sub parts, returning the empty array if there are none (e.g., if this is a single part message, or a degenerate multipart). In a scalar context, this hands you the number of parts.
If an integer INDEX is given, return the INDEXed part, or undef if it doesn't exist. π
If an ARRAYREF to an array of parts is given, then this method sets the parts to a copy of that array, and returns the parts. This can be used to delete parts, like this:
### Delete some parts of a multipart message:
$msg->parts([ grep { keep_part($_) } $msg->parts ]);
Note: for multipart messages, the preamble and epilogue are not considered parts. If you need them, use the preamble() and epilogue() methods. π
Heads up bestie: there are ways of parsing with aMIME::Parserthat make certain message parts (like the ones typed"message/rfc822") get "reparsed" into pseudo-multipart entities. Read those options' docs carefully β it is possible for a diddled entity to not be multipart but still have parts attached to it. π Wild, I know.
See "bodyhandle" for a whole discussion of parts vs. bodies.
parts_DFS
Instance method. Returns the list of every single MIME::Entity object inside the entity, starting with the entity itself, in depth-first-search order. If the entity has no parts, then it's just lonely little it getting returned. π¦
Thanks to Xavier Armengou for suggesting this method. π«Ά
preamble [LINES]
Instance method. Get/set the text of the preamble, as an array of newline-terminated LINES. Returns a reference to the array of lines, or undef if no preamble exists (e.g., if this is a single-part entity).
If there is a preamble, it gets output when printing this entity; otherwise a default preamble is used. Setting the preamble to undef (not []!) causes it to fallback to the default. π
π Manipulation π
make_multipart [SUBTYPE], OPTSHASH...
Instance method. Force the entity to be a multipart, if it isn't already. We do this by replacing the original [singlepart] entity with a new multipart that has the same non-MIME headers ("From", "Subject", etc.), but all-new MIME headers ("Content-type", etc.). Then we create a copy of the original singlepart, strip out the non-MIME headers from that, and make it a part of the new multipart. So this:
From: me
To: you
Content-type: text/plain
Content-length: 12
Hello there!
Becomes something like this:
From: me
To: you
Content-type: multipart/mixed; boundary="----abc----"
------abc----
Content-type: text/plain
Content-length: 12
Hello there!
------abc------
The actual type of the new top-level multipart will be "multipart/SUBTYPE" (default SUBTYPE is "mixed").
Returns 'DONE' if we really did inflate a singlepart to a multipart. Returns 'ALREADY' (and does nothing) if entity is already multipart and Force was not chosen.
If OPTSHASH contains Force=>1, then we always bump the top-level's content and content-headers down to a subpart of this entity, even if this entity is already a multipart. This is apparently of use to people who are tweaking messages after parsing them. π οΈ
make_singlepart
Instance method. If the entity is a multipart message with one part, this tries hard to rewrite it as a singlepart, by replacing the content (and content headers) of the top level with those of the part. Also crunches 0-part multiparts into singleparts.
Returns 'DONE' if we really did collapse a multipart to a singlepart. Returns 'ALREADY' (and does nothing) if entity is already a singlepart. Returns '0' (and does nothing) if it can't be made into a singlepart.
purge
Instance method. Recursively purge (e.g., unlink) all external (e.g., on-disk) body parts in this message. See MIME::Body::purge() for details.
Note: this does not delete the directories that those body parts are contained in; only the actual message data files are deleted. This is because some parsers may be customized to create intermediate directories while others are not, and it's impossible for this class to know what directories are safe to remove. Only your application program truly knows that. π«‘
If you really want to "clean everything up", one good way is to use MIME::Parser::file_under(), and then do this before parsing your next message:
$parser->filer->purge();
I wouldn't attempt to read those body files after you do this, for obvious reasons. As of MIME-tools 4.x, each body's path is undefined after this operation. I warned you I might do this; truly I did. π
Thanks to Jason L. Tibbitts III for suggesting this method.
remove_sig [NLINES]
Instance method, override. Attempts to remove a user's signature from the body of a message.
It does this by looking for a line matching /^-- $/ within the last NLINES of the message. If found then that line and all lines after it will be removed. If NLINES is not given, a default value of 10 will be used. This would be of most use in auto-reply scripts. π€
For MIME entity, this method is reasonably cautious: it will only attempt to un-sign a message with a content-type of "text/*".
If you send remove_sig() to a multipart entity, it will relay it to the first part (the others usually being the "attachments").
Warning: currently slurps the whole message-part into core as an array of lines, so you probably don't want to use this on extremely long messages. π¬
Returns truth on success, false on error.
sign PARAMHASH
Instance method, override. Append a signature to the message. The params are:
Attachβ Instead of appending the text, add it to the message as an attachment. The disposition will be"inline", and the description will indicate that it is a signature. The default behavior is to append the signature to the text of the message (or the text of its first part if multipart). MIME-specific; new in this subclass. β¨Fileβ Use the contents of this file as the signature. Fatal error if it can't be read. As per superclass method.Forceβ Sign it even if the content-type isn't"text/*". Useful for non-standard types like"x-foobar", but be careful! MIME-specific; new in this subclass. β οΈRemoveβ Normally, we attempt to strip out any existing signature. If true, this gives us the NLINES parameter of theremove_sigcall. If zero but defined, tells us not to remove any existing signature. If undefined, removal is done with the default of10lines. New in this subclass.Signatureβ Use this text as the signature. You can supply it as either a scalar, or as a ref to an array of newline-terminated scalars. As per superclass method.
For MIME messages, this method is reasonably cautious: it will only attempt to sign a message with a content-type of "text/*", unless "Force" is specified.
If you send this message to a multipart entity, it will relay it to the first part (the others usually being the "attachments").
Warning: currently slurps the whole message-part into core as an array of lines, so you probably don't want to use this on extremely long messages. π
Returns true on success, false otherwise.
suggest_encoding
Instance method. Based on the effective content type, return a good suggested encoding.
"text" and "message" types have their bodies scanned line-by-line for 8-bit characters and long lines; lack of either means that the message is 7bit-ok. Other types are chosen independent of their body:
Major type: 7bit ok? Suggested encoding:
-----------------------------------------------------------
text yes 7bit
text no quoted-printable
message yes 7bit
message no binary
multipart * binary (in case some parts are bad)
image, etc... * base64
sync_headers OPTIONS
Instance method. This method does a variety of activities which ensure that the MIME headers of an entity "tree" are in-synch with the body parts they describe. It can be as expensive an operation as printing if it involves pre-encoding the body parts; however, the aim is to produce fairly clean MIME. You will usually only need to invoke this if processing and re-sending MIME from an outside source. π
The OPTIONS is a hash, which describes what is to be done.
Lengthβ One of the "official unofficial" MIME fields is"Content-Length". Normally, one doesn't care a whit about this field; however, if you are preparing output destined for HTTP, you may. The value of this option dictates what will be done:COMPUTEmeans to set a"Content-Length"field for every non-multipart part in the entity, and to blank that field out for every multipart part in the entity.ERASEmeans that"Content-Length"fields will all be blanked out. This is fast, painless, and safe. π- Any false value (the default) means to take no action.
Nonstandardβ Any header field beginning with"Content-"is, according to the RFC, a MIME field. However, some are non-standard, and may cause problems with certain MIME readers which interpret them in different ways.ERASEmeans that all such fields will be blanked out. This is done before the Length option (q.v.) is examined and acted upon.- Any false value (the default) means to take no action.
Returns a true value if everything went okay, a false value otherwise.
tidy_body
Instance method, override. Currently unimplemented for MIME messages. Does nothing, returns false. π (Iconic behaviour, honestly.)
πΈ Output πΈ
dump_skeleton [FILEHANDLE]
Instance method. Dump the skeleton of the entity to the given FILEHANDLE, or to the currently-selected one if none given.
Each entity is output with an appropriate indentation level, the following selection of attributes:
Content-type: multipart/mixed
Effective-type: multipart/mixed
Body-file: NONE
Subject: Hey there!
Num-parts: 2
This is really just useful for debugging purposes; I make no guarantees about the consistency of the output format over time. π«Ά
print [OUTSTREAM]
Instance method, override. Print the entity to the given OUTSTREAM, or to the currently-selected filehandle if none given. OUTSTREAM can be a filehandle, or any object that responds to a print() message.
The entity is output as a valid MIME stream! This means that the header is always output first, and the body data (if any) will be encoded if the header says that it should be. For example, your output may look like this:
Subject: Greetings
Content-transfer-encoding: base64
SGkgdGhlcmUhCkJ5ZSB0aGVyZSEK
If this entity's MIME type is "multipart/*", bestie, then the preamble, the parts, AND the epilogue all get output, with those cute little boundaries doing their job separating each one π
. Any bodyhandle? Yeah, it gets straight-up ignored:
Content-type: multipart/mixed; boundary="*----*"
Content-transfer-encoding: 7bit
[Preamble]
--*----*
[Entity: Part 0]
--*----*
[Entity: Part 1]
--*----*--
[Epilogue]
Now if this entity has a single-part MIME type with no parts attached? That's just a normal singlepart entity, no drama πΈ. The body gets output according to whatever encoding the header says, periodt. And if there's no body at all? You get a warning, and the body is treated as empty. It's giving "oops, nothing here":
Content-type: image/gif
Content-transfer-encoding: base64
[Encoded body]
But okay, plot twist: if this entity has a single-part MIME type AND it also has parts? Then we're probably looking at a "re-parsed" singlepart β usually one of type "message/*". iykyk, you can get entities like this if you set the parse_nested_messages(NEST) option on the parser to true π. In this case, the parts are output with single blank lines separating each, and any bodyhandle is ignored:
Content-type: message/rfc822
Content-transfer-encoding: 7bit
[Entity: Part 0]
[Entity: Part 1]
And in literally ALL of these cases, when this method outputs a "part" of the entity, it invokes itself recursively π. Yes bestie, it's recursive, it's iconic, it's doing the most.
Note: the output is very likely not going to be identical to any input you parsed to get this entity. So if you're building some sort of email handler, it's up to you to save this information. No cap. π
print_body [OUTSTREAM] π«Ά
Instance method, override. It prints the body of the entity to the given OUTSTREAM, or to the currently-selected filehandle if you didn't give it one. OUTSTREAM can be a filehandle, or honestly any object that responds to a print() message β¨.
The body gets output so it fits into a valid MIME stream β which means the body data will be encoded if the header says it should be. Slay.
Note: by "body", we mean "the stuff following the header". A printed multipart body includes the printed representations of its subparts. It's giving very inclusive π.
Note: the body is stored in an un-encoded form; however, the idea is that the transfer encoding is used to determine how it should be output. This means theprint()method is always guaranteed to get you a sendmail-ready stream whose body is consistent with its head π₯. If you want the raw body data to be output, you can either read it from thebodyhandleyourself, or use:
$ent->bodyhandle->print($outstream);
which uses read() calls to extract the information, and thus will work with both text AND binary bodies. Versatile queen π
.
Warning: Please supply an OUTSTREAM. This override method differs from Mail::Internet's behavior, which outputs to the STDOUT if no filehandle is given β and that may lead to confusion π. Don't do that to yourself.
print_header [OUTSTREAM] π
Instance method, inherited. Output the header to the given OUTSTREAM. And fr fr, you really should supply the OUTSTREAM. Just do it bestie πΈ.
stringify β
Instance method. Return the entity as a string, exactly as print would print it. The body will be encoded as necessary, and it'll contain any subparts. You can also use as_string(). Same vibe, different name π.
stringify_body π¦
Instance method. Return the encoded message body as a string, exactly as print_body would print it. You can also use body_as_string().
If you want the unencoded body, and you're dealing with a singlepart message (like a "text/plain"), use bodyhandle() instead:
if ($ent->bodyhandle) {
$unencoded_data = $ent->bodyhandle->as_string;
}
else {
### this message has no body data (but it might have parts!)
}
See how we said "but it might have parts"? Read the comment, bestie, it's important π.
stringify_header π
Instance method. Return the header as a string, exactly as print_header would print it. You can also use header_as_string(). That's it, that's the whole thing π.
π NOTES π
okay bestie, before we dip, here's the lore you need to know about how this whole thing works under the hood. no cap π«Ά
π§ Under the hood π οΈ
A MIME::Entity is composed of the following elements:
- A head β a reference to a
MIME::Headobject containing the header information. iconic. - A bodyhandle β a reference to a
MIME::Bodyobject containing the decoded body data. This is only defined if the message is a"singlepart"type:
application/*
audio/*
image/*
text/*
video/*
- An array of parts β where each part is a
MIME::Entityobject. The number of parts will only be nonzero if the content-type is not one of the"singlepart"types:
message/* (should have exactly one part)
multipart/* (should have one or more parts)
π The "two-body problem" π΅βπ«
MIME::Entity and Mail::Internet see message bodies differently, and this can cause confusion and some inconvenience. Sadly, I can't change the behavior of MIME::Entity without breaking lots of code already out there. But let's open up the floor for a few questions... periodt π
What is the difference between a "message" and an "entity"?
A message is the actual data being sent or received; usually this means a stream of newline-terminated lines. An entity is the representation of a message as an object.
This means that you get a "message" when you print an "entity" to a filehandle, and you get an "entity" when you parse a message from a filehandle. it's giving object-oriented realness β¨
What is a message body?
Mail::Internet: The portion of the printed message after the header.MIME::Entity: The portion of the printed message after the header.
How is a message body stored in an entity?
Mail::Internet: As an array of lines.MIME::Entity: It depends on the content-type of the message. For "container" types ("multipart/*","message/*"), we store the contained entities as an array of"parts", accessed via theparts()method, where each part is a completeMIME::Entity. For "singlepart" types ("text/*","image/*", etc.), the unencoded body data is referenced via aMIME::Bodyobject, accessed via thebodyhandle()method:
bodyhandle() parts()
Content-type: returns: returns:
------------------------------------------------------------
application/* MIME::Body empty
audio/* MIME::Body empty
image/* MIME::Body empty
message/* undef MIME::Entity list (usually 1)
multipart/* undef MIME::Entity list (usually >0)
text/* MIME::Body empty
video/* MIME::Body empty
x-*/* MIME::Body empty
As a special case, "message/*" is currently ambiguous: depending on the parser, a "message/*" might be treated as a singlepart, with a MIME::Body and no parts. Use bodyhandle() as the final arbiter. don't skip this part π¨
What does the body() method return?
Mail::Internet: As an array of lines, ready for sending.MIME::Entity: As an array of lines, ready for sending.
What's the best way to get at the body data?
Mail::Internet: Use thebody()method.MIME::Entity: Depends on what you want... the encoded data (as it is transported), or the unencoded data? Keep reading... iykyk π
How do I get the "encoded" body data?
Mail::Internet: Use thebody()method.MIME::Entity: Use thebody()method. You can also use:
$entity->print_body()
$entity->stringify_body() ### a.k.a. $entity->body_as_string()
How do I get the "unencoded" body data?
Mail::Internet: Use thebody()method.MIME::Entity: Use thebodyhandle()method! Ifbodyhandle()method returns true, then that value is aMIME::Bodywhich can be used to access the data via itsopen()method. Ifbodyhandle()method returns an undefined value, then the entity is probably a"container"that has no real body data of its own (e.g., a"multipart"message): in this case, you should access the components via theparts()method. Like this:
if ($bh = $entity->bodyhandle) {
$io = $bh->open;
...access unencoded data via $io->getline or $io->read...
$io->close;
}
else {
foreach my $part (@parts) {
...do something with the part...
}
}
You can also use:
if ($bh = $entity->bodyhandle) {
$unencoded_data = $bh->as_string;
}
else {
...do stuff with the parts...
}
What does the body() method return?
Mail::Internet: The transport-encoded message body, as an array of lines.MIME::Entity: The transport-encoded message body, as an array of lines.
What does print_body() print?
Mail::Internet: Exactly whatbody()would return to you.MIME::Entity: Exactly whatbody()would return to you.
Say I have an entity which might be either singlepart or multipart. How do I print out just "the stuff after the header"?
Mail::Internet: Useprint_body().MIME::Entity: Useprint_body().
Why is MIME::Entity so different from Mail::Internet?
- Because MIME streams are expected to have non-textual data... possibly, quite a lot of it, such as a tar file.
- Because MIME messages can consist of multiple parts, which are most-easily manipulated as
MIME::Entityobjects themselves. - Because in the simpler world of
Mail::Internet, the data of a message and its printed representation are identical... and in the MIME world, they're not. - Because parsing multipart bodies on-the-fly, or formatting multipart bodies for output, is a non-trivial task.
This is confusing. Can the two classes be made more compatible?
Not easily; their implementations are necessarily quite different. Mail::Internet is a simple, efficient way of dealing with a "black box" mail message... one whose internal data you don't care much about. MIME::Entity, in contrast, cares very much about the message contents: that's its job! main character energy π
π¨ Design issues π
π« Some things just can't be ignored π«£
In multipart messages, the "preamble" is the portion that precedes the first encapsulation boundary, and the "epilogue" is the portion that follows the last encapsulation boundary.
According to RFC 2046:
There appears to be room for additional information prior to the first encapsulation boundary and following the final boundary. These areas should generally be left blank, and implementations must ignore anything that appears before the first boundary or after the last one. NOTE: These "preamble" and "epilogue" areas are generally not used because of the lack of proper typing of these parts and the lack of clear semantics for handling these areas at gateways, particularly X.400 gateways. However, rather than leaving the preamble area blank, many MIME implementations have found this to be a convenient place to insert an explanatory note for recipients who read the message with pre-MIME software, since such notes will be ignored by MIME-compliant software.
In the world of standards-and-practices, that's the standard. Now for the practice:
Some "MIME" mailers may incorrectly put a "part" in the preamble. Since we have to parse over the stuff anyway, in the future I may allow the parser option of creating special MIME::Entity objects for the preamble and epilogue, with bogus MIME::Head objects.
For now, though, we're MIME-compliant, so I probably won't change how we work. respect the standard π
π SEE ALSO π
MIME::ToolsMIME::HeadMIME::BodyMIME::DecoderMail::Internet
π AUTHOR π
Eryq (eryq@zeegee.com), ZeeGee Software Inc (http://www.zeegee.com). Dianne Skoll (dianne@skoll.ca)
All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
This page came from perl v5.42.0, dated 2026-02-11, and it's MIME::Entity(3). Stay iconic, bestie π
β¨
π¦ where this page comes from
- fedora 44: perl-MIME-tools 5.517-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