The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

MIME::Entity - class for parsed-and-decoded MIME message

SYNOPSIS

    # Create an entity:
    $top = build MIME::Entity 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

A subclass of Mail::Internet.

This package provides a class for representing MIME message entities, as specified in RFC 1521, Multipurpose Internet Mail Extensions.

EXAMPLES

Construction examples

Create a document for an ordinary 7-bit ASCII text file (lots of stuff is defaulted for us):

    $ent = build MIME::Entity Path=>"english-msg.txt";

Create a document for a text file with 8-bit (Latin-1) characters:

    $ent = build MIME::Entity 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 = build MIME::Entity 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 = build MIME::Entity 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',
                     Encoding    => '-SUGGEST');
    }

Copy an entity (headers, parts... everything but 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 actual MIME type, in the header:
    $type = $ent->mime_type;

    # Get the effective MIME type (for dealing with nonstandard encodings):
    $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;

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... 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);

PUBLIC INTERFACE

Construction

new [SOURCE]

Class method. Create a new, empty MIME entity. Basically, this uses the Mail::Internet constructor...

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!

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.

Warning: in general, you only want to attach parts to entities with a content-type of multipart/*).

Thanks to Jason L Tibbitts III for providing support for OFFSET.

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.

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 = build MIME::Entity Type     => "image/gif",
                             Encoding => "base64",
                             Path     => "/path/to/xyz12345.gif",
                             Filename => "saveme.gif",
                             Disposition => "attachment";

And like this to build a "multipart" entity:

   $ent = build MIME::Entity 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 = build MIME::Entity 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 = build MIME::Entity  Type        => "multipart/mixed",
                              'X-Mailer'  => "myprog 1.1";

Or remove it entirely:

   $ent = build MIME::Entity Type       => "multipart/mixed",
                             'X-Mailer' => undef;

OK, enough hype. The parameters are:

(FIELDNAME)

Any field you want placed in the message header, taken from the standard list of header fields (you don't need to worry about case):

    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).

Boundary

Multipart entities only. Optional. The boundary string. As per RFC-1521, it must consist only of the characters [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.

Charset

Optional. The character set.

Data

Single-part entities only. Optional. An alternative to Path (q.v.): the actual data, either as a scalar or an array reference (whose elements are joined together to make the actual scalar). The body is opened on the data using MIME::Body::Scalar.

Description

Optional. The text of the content-description. If you don't specify it, the field is not put in the header.

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, the field is not put in the header... which means that the encoding implicitly defaults to "7bit" as per RFC-1521. Do yourself a favor: put it in. You can also give the special value '-SUGGEST', to have it chosen for you.

Filename

Single-part entities only. Optional. The recommended filename. Overrides any name extracted from 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.

Path

Single-part entities only. Optional. The path to the file to attach. The body is opened on that file using MIME::Body::File.

Top

Optional. Is this a top-level entity? If so, it must sport a MIME-Version. The default is true. (NB: look at how attach() 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-1521. Do yourself a favor: put it in.

dup

Instance method. Duplicate the entity. 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 or set the body, as an array of lines. This should be regarded as a read-only data structure: changing its contents will have unpredictable results (you can, of course, make your own copy, and work with that).

Provided for compatibility with Mail::Internet, and it might not be as efficient as you'd like. Also, it's somewhat silly/wrongheaded for binary bodies, like GIFs and tar files. Instead, 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()).

bodyhandle [VALUE]

Instance method. Get or set an abstract object representing the body.

If VALUE is not given, the current bodyhandle is returned. If VALUE is given, the bodyhandle is set to the new value, and the previous value is returned.

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 known 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 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.

head [VALUE]

Instance method. Get/set the head.

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.

is_multipart

Instance method. Does this entity's 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.

mime_type

Instance method. A purely-for-convenience method. This simply relays the request to the associated MIME::Head object. If there is no head, returns undef in a scalar context and the empty array in a list context.

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 is 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 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.

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!

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 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.

Manipulation

make_multipart [SUBTYPE]

Instance method. Force the entity to be a multipart, if it isn't already. The content headers from the top-level are bumped down to the demoted part. The actual type 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.

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.

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 the remove_sig call. If zero but defined, tells us not to remove any existing signature. If undefined, removal is done with the default of 10 lines. 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 not ok)
    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:

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.

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.

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.

tidy_body

Instance method, override. Currently unimplemented for MIME messages. Does nothing, returns false.

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.

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 reponds 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 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.

Instance method, override. Print the body of the entity to the given OUTSTREAM, or to the currently-selected filehandle if none given. OUTSTREAM can be a filehandle, or any object that reponds to a 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.

Instance method, inherited. Output the header to the given OUTSTREAM. You really should supply the OUTSTREAM.

stringify

Instance method. Return the entity as a string, exactly as print would print it: the body will be encoded as necessary, and will contain any subparts. You can also use as_string.

stringify_body

Instance method. Return the body as a string, exactly as print_body would print it: the body will be encoded as necessary, and will not contain any subparts. You can also use body_as_string.

If you want the unencoded body, use $ent-body->as_string>.

stringify_header

Instance method. Return the header as a string, exactly as print_header would print it. You can also use header_as_string.

NOTES

Under the hood

A MIME::Entity is composed of the following elements:

  • A head, which is a reference to a MIME::Head object containing the header information.

  • A bodyhandle, which is a reference a MIME::Body object containing the decoded body data. (In pre-2.0 releases, this was accessed via body, which was a path to a file containing the decoded body. Integration with Mail::Internet has forced this to change.)

  • A list of zero or more parts, each of which is a MIME::Entity object. The number of parts will only be nonzero if the content-type is some subtype of "multipart".

    Note that a multipart entity does not have a body. Of course, any/all of its component parts can have bodies.

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...

How are message bodies stored?

Mail::Internet: As an array of lines.

MIME::Entity: As a MIME::Body object, where the data may reside on disk or in-core, may be large, and may be binary (not line-oriented).

Do messages generally have bodies?

Mail::Internet: Almost certainly yes.

MIME::Entity: Yes if this is a singlepart message, and NO if it's a multipart message... since for multiparts the message "body" is stored as the parsed collection of "parts" (each of which is also a MIME::Entity).

If an entity has a body, does it have a soul as well?

The soul does not exist in a corporeal sense, the way the body does; it is not a solid [Perl] object. Rather, it is a virtual object which is only visible when you print() an entity to a file... in other words, the "soul" it is all that is left after the body is DESTROY'ed.

What's the best way to get at the body data?

Mail::Internet: Use the body() method.

MIME::Entity: Use the bodyhandle() method, or the brand-new open() method. The open() method returns a filehandle-like object to you, which gives you methods like getline() and read(). Use methods only for portability; don't make any assumptions about what you've been handed.

What does the body() method return?

Mail::Internet: The body, as an array of lines.

MIME::Entity: The body, as an array of lines... but only for a singlepart messages. It returns nothing for a multipart message, since multiparts by definition do not have bodies of their own. It's also somewhat inappropriate for non-textual bodies, like GIFs.

What does print_body() print?

Mail::Internet: Exactly what body() would return to you.

MIME::Entity: The encoded representation of "all the stuff following the header", using the Content-transfer-encoding in the MIME header. This includes the encoded representation of any parts as well. Put simply, print_body() doesn't just "print the body": it prints a flattened representation of the entire entity, including subparts. This is generally what people seem to expect.

Assuming I have a singlepart, isn't the data from body() identical to the stuff printed by print_body()?

Mail::Internet: Yes.

MIME::Entity: Not likely. If the original message held a base64-encoded GIF file, the body() data will be the actual, decoded, binary GIF data... which is not the same as that base64-encoded stream of ASCII output by print_body().

Conceptually, what's the difference between what's returned by body() and what's printed by print_body()?

Mail::Internet: None.

MIME::Entity: Method body() refers to the actual body data of the entity in question. Method print_body() (and stringify_body()) refers to the complete printed representation of that entity.

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: Use print_body().

MIME::Entity: Use print_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::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.

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!

Here's an example:

Suppose you wanted me to rewrite MIME::Entity so that you could properly set any body -- even a multipart body -- by giving its lines to body(). After all, I can just parse the lines you give me, right?

Not quite. In order to parse that data, I need to have a header which tells me whether it's singlepart or multipart. I need to know the encoding, too. So MIME::Entity will enforces a sequence of events on how you set things up, unlike Mail::Internet -- which doesn't care about message contents.

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-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.

AUTHOR

Eryq (eryq@zeegee.com), ZeeGee Software Inc (http://www.zeegee.com).

All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

VERSION

$Revision: 4.116 $ $Date: 1999/02/09 03:32:37 $