The OpenNET Project / Index page

[ новости /+++ | форум | теги | ]

Интерактивная система просмотра системных руководств (man-ов)

 ТемаНаборКатегория 
 
 [Cписок руководств | Печать]

MIME::Entity (3)
  • >> MIME::Entity (3) ( Разные man: Библиотечные вызовы )
  •  

    NAME

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

    SYNOPSIS

    Before reading further, you should see MIME::Tools 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);
    
    
     

    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 = 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;
    
    
     

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

     

    Globals

    $BOUNDARY_DELIMITER
    This is the end-of-line sequence output at the end of a multipart boundary when you're printing a MIME::Entity. It defaults to ``\n''. I strongly suggest that you local'ize your overrides if possible:

        sub do_stuff {
            local $MIME::Entity::BOUNDARY_DELIMITER = "\r\n";
            ...
            $entity->print;
        }
    
    
     

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

    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 remove it entirely:

       $ent = MIME::Entity->build(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::InCore.
    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, a reasonable default is put in. You can also give the special value '-SUGGEST', to have it chosen for you in a heavy-duty fashion which scans the data itself.
    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.
    Id
    Optional. Set the content-id.
    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 the encoded (transport-ready) body, as an array of lines. This is a read-only data structure: changing its contents will have no effect. Its contents are identical to what is printed by print_body().

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

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

    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 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 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 to effective_type so 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 is 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 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. 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.

    parts_DFS
    Instance method. Return the list of all MIME::Entity objects included in the entity, starting with the entity itself, in depth-first-search order. If the entity has no parts, it alone will be 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 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], 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.). We then 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.
    Charset
    Explicitly declare the character set of the signed text if using ``Attach''. Default is to leave it undeclared.
    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 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:

    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
        Content-encoding: 7bit
        Body-location: IN CORE
        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 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.

    print_body [OUTSTREAM]
    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.

    print_header [OUTSTREAM]
    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 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 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!)
        }
    
    
    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 to a MIME::Body object 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::Entity object. 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...
    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.

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

    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.

    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: Depends on what you want... the encoded data (as it is transported), or the unencoded data? Keep reading...

    How do I get the encoded body data?
    Mail::Internet: Use the 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()
    
    
    How do I get the unencoded body data?
    Mail::Internet: Use the 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...
        }
    
    
    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 what body() would return to you.

    MIME::Entity: Exactly what body() 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: 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!
     

    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: 6.109 $ $Date: 2003/06/27 17:54:30 $


     

    Index

    NAME
    SYNOPSIS
    DESCRIPTION
    EXAMPLES
    Construction examples
    Access examples
    Manipulation examples
    Output examples
    PUBLIC INTERFACE
    Globals
    Construction
    Access
    Manipulation
    Output
    NOTES
    Under the hood
    The two-body problem
    Design issues
    AUTHOR
    VERSION


    Поиск по тексту MAN-ов: 




    Партнёры:
    PostgresPro
    Inferno Solutions
    Hosting by Hoster.ru
    Хостинг:

    Закладки на сайте
    Проследить за страницей
    Created 1996-2024 by Maxim Chirkov
    Добавить, Поддержать, Вебмастеру