MIME::Entity - class for parsed-and-decoded MIME message |
MIME::Entity - class for parsed-and-decoded MIME message
Before reading further, you should see the MIME::Tools manpage to make sure that you 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);
A subclass of Mail::Internet.
This package provides a class for representing MIME message entities, as specified in RFC 1521, Multipurpose Internet Mail Extensions.
Create a document for an ordinary 7-bit ASCII text file (lots of stuff is defaulted for us):
$ent = MIME::Entity->build(Path=>"english-msg.txt");
Create 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!");
Create a document for a GIF file (the description is completely optional; note that we have to specify content-type and encoding since they're not the default values):
$ent = MIME::Entity->build(Description => "A pretty picture", Path => "./docs/mime-sm.gif", Type => "image/gif", Encoding => "base64");
Create a document that you already have the text for, using ``Data'':
$ent = MIME::Entity->build(Type => "text/plain", Encoding => "quoted-printable", Data => ["First line.\n", "Second line.\n", "Last line.\n"]);
Create a multipart message, with the entire structure given explicitly:
### 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: 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 but external body data):
my $deepcopy = $top->dup;
### 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
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);
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... note that stringify_xx
can also be written xx_as_string
;
the methods are synonymous, and neither form will be deprecated:
### 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);
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!
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/*
).
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.
$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 remove it entirely:
$ent = MIME::Entity->build(Type => "multipart/mixed", 'X-Mailer' => undef);
OK, enough hype. The parameters are:
Bcc Encrypted Received Sender Cc From References Subject Comments Keywords Reply-To To Content-* Message-ID Resent-* X-* Date MIME-Version Return-Path Organization
To give experienced users some veto power, these fields will be set
after the ones I set... so be careful: don't set any MIME fields
(like Content-type
) unless you know what you're doing!
To specify a fieldname that's not in the above list, even one that's
identical to an option below, just give it with a trailing ":"
,
like "My-field:"
. When in doubt, that always signals a mail
field (and it sort of looks like one too).
[0-9a-zA-Z'()+_,-./:=?]
and space (you'll be
warned, and your boundary will be ignored, if this is not the case).
If you omit this, a random string will be chosen... which is probably
safer.
"attachment"
or "inline"
).
If you don't specify it, it defaults to ``inline'' for backwards
compatibility. Thanks to Kurt Freytag for suggesting this feature.
Path
.
The information is stored both the deprecated (content-type) and
preferred (content-disposition) locations. If you explicitly want to
avoid a recommended filename (even when Path is used), supply this
as empty or undef.
attach()
uses it.)
"text/plain"
, etc.).
If you don't specify it, it defaults to "text/plain"
as per RFC-1521. Do yourself a favor: put it in.
Provided for compatibility with Mail::Internet, so that methods
like smtpsend()
will work. Note however that if VALUE is given,
a fatal exception is thrown, since you 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()).
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 will return 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 cannot have a body.
If VALUE
is given, the bodyhandle is set to the new value,
and the previous value is returned.
See parts for more info.
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.
If there is a epilogue, it is output when printing this entity; otherwise, a default epilogue is used. Setting the epilogue to undef (not []!) causes it to fallback to the default.
If there is 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.
NOTE: we switched to effective_type so that multiparts with
bad or missing boundaries could be coerced to an effective type
of application/x-unparseable-multipart
.
Before you use this, consider using effective_type()
instead,
especially if you obtained the entity from a MIME::Parser.
If there is no body, returns false.
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 returns 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, as follows:
### 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.
Note: there are ways of parsing with a MIME::Parser which cause
certain message parts (such as those of type message/rfc822
)
to be ``reparsed'' into pseudo-multipart entities. You should read the
documentation for those options carefully: it is possible for
a diddled entity to not be multipart, but still have parts attached to it!
See bodyhandle for a discussion of parts vs. bodies.
Thanks to Xavier Armengou for suggesting this method.
If there is a preamble, it is output when printing this entity; otherwise, a default preamble is used. Setting the preamble to undef (not []!) causes it to fallback to the default.
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.
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.
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.
B<If you really want to "clean everything up",> one good way is to use C<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.
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.
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.
text/*
. Useful for
non-standard types like x-foobar
, but be careful!
MIME-specific; new in this subclass.
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.
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
The OPTIONS is a hash, which describes what is to be done.
COMPUTE means 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.
ERASE means 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.
ERASE means 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.
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()
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 has MIME type ``multipart/*'', the preamble, parts, and epilogue are all output with appropriate boundaries separating each. Any bodyhandle is ignored:
Content-type: multipart/mixed; boundary="*----*" Content-transfer-encoding: 7bit
[Preamble] --*----* [Entity: Part 0] --*----* [Entity: Part 1] --*----*-- [Epilogue]
If this entity has a single-part MIME type with no attached parts, then we're looking at a normal singlepart entity: the body is output according to the encoding specified by the header. If no body exists, a warning is output and the body is treated as empty:
Content-type: image/gif Content-transfer-encoding: base64
[Encoded body]
If this entity has a single-part MIME type but it also has parts,
then we're probably looking at a ``re-parsed'' singlepart, usually one
of type message/*
(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]
In all cases, when outputting a ``part'' of the entity, this method is invoked recursively.
Note: the output is very likely not going to be identical to any input you parsed to get this entity. If you're building some sort of email handler, it's up to you to save this information.
print()
message.
The body is output for inclusion in a valid MIME stream; this means that the body data will be encoded if the header says that it should be.
Note: by ``body'', we mean ``the stuff following the header''. A printed multipart body includes the printed representations of its subparts.
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 that the print()
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
the bodyhandle yourself, or use:
$ent->bodyhandle->print($outstream);
which uses read()
calls to extract the information, and thus will
work with both text and binary bodies.
Warning: Please supply an OUTSTREAM. This override method differs from Mail::Internet's behavior, which outputs to the STDOUT if no filehandle is given: this may lead to confusion.
print
would print it.
The body will be encoded as necessary, and will contain any subparts.
You can also use as_string()
.
print_body
would print it. You can also use body_as_string()
.
If you want the unencoded body, and you are 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!) }
print_header
would print it.
You can also use header_as_string()
.
A MIME::Entity is composed of the following elements:
application/* audio/* image/* text/* video/*
message/* (should have exactly one part) multipart/* (should have one or more parts)
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...
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.
MIME::Entity: The portion of the printed message after the header.
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 the parts()
method, where each part is a complete MIME::Entity.
For ``singlepart'' types (text/*
, image/*
, etc.), the unencoded
body data is referenced via a MIME::Body object, accessed via
the bodyhandle()
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.
body()
method return?MIME::Entity: As an array of lines, ready for sending.
print()
an entity to a file... in other
words, the ``soul'' it is all that is left after the body is DESTROY'ed.
body()
method.
MIME::Entity: Depends on what you want... the encoded data (as it is transported), or the unencoded data? Keep reading...
body()
method.
MIME::Entity:
Use the body()
method. You can also use:
$entity->print_body() $entity->stringify_body() ### a.k.a. $entity->body_as_string()
body()
method.
MIME::Entity:
Use the bodyhandle() method!
If bodyhandle()
method returns true, then that value is a
MIME::Body which can be used to access the data via
its open()
method. If bodyhandle()
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 the parts()
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... }
body()
method return?MIME::Entity: The transport-encoded message body, as an array of lines.
print_body()
print?body()
would return to you.
MIME::Entity:
Exactly what body()
would return to you.
MIME::Entity: Use print_body().
Because MIME messages can consist of multiple parts, which are most-easily manipulated as MIME::Entity objects 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.
According to RFC-1521:
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.
Eryq (eryq@zeegee.com), ZeeGee Software Inc (http://www.zeegee.com). David F. Skoll (dfs@roaringpenguin.com) http://www.roaringpenguin.com
All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
$Revision: 1.10 $ $Date: 2005/01/13 19:23:15 $
MIME::Entity - class for parsed-and-decoded MIME message |