{
    "mode": "perldoc",
    "parameter": "MIME::Entity",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/MIME%3A%3AEntity/json",
    "generated": "2026-06-09T11:53:29Z",
    "synopsis": "Before reading further, you should see MIME::Tools to make sure that you understand where this\nmodule fits into the grand scheme of things. Go on, do it now. I'll wait.\nReady? Ok...\n### Create an entity:\n$top = MIME::Entity->build(From    => 'me@myhost.com',\nTo      => 'you@yourhost.com',\nSubject => \"Hello, nurse!\",\nData    => \\@mymessage);\n### Attach stuff to it:\n$top->attach(Path     => $gifpath,\nType     => \"image/gif\",\nEncoding => \"base64\");\n### Sign it:\n$top->sign;\n### Output it:\n$top->print(\\*STDOUT);",
    "sections": {
        "NAME": {
            "content": "MIME::Entity - class for parsed-and-decoded MIME message\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "Before reading further, you should see MIME::Tools to make sure that you understand where this\nmodule fits into the grand scheme of things. Go on, do it now. I'll wait.\n\nReady? Ok...\n\n### Create an entity:\n$top = MIME::Entity->build(From    => 'me@myhost.com',\nTo      => 'you@yourhost.com',\nSubject => \"Hello, nurse!\",\nData    => \\@mymessage);\n\n### Attach stuff to it:\n$top->attach(Path     => $gifpath,\nType     => \"image/gif\",\nEncoding => \"base64\");\n\n### Sign it:\n$top->sign;\n\n### Output it:\n$top->print(\\*STDOUT);\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "A subclass of Mail::Internet.\n\nThis package provides a class for representing MIME message entities, as specified in RFCs 2045,\n2046, 2047, 2048 and 2049.\n",
            "subsections": []
        },
        "EXAMPLES": {
            "content": "",
            "subsections": [
                {
                    "name": "Construction examples",
                    "content": "Create a document for an ordinary 7-bit ASCII text file (lots of stuff is defaulted for us):\n\n$ent = MIME::Entity->build(Path=>\"english-msg.txt\");\n\nCreate a document for a text file with 8-bit (Latin-1) characters:\n\n$ent = MIME::Entity->build(Path     =>\"french-msg.txt\",\nEncoding =>\"quoted-printable\",\nFrom     =>'jean.luc@inria.fr',\nSubject  =>\"C'est bon!\");\n\nCreate a document for a GIF file (the description is completely optional; note that we have to\nspecify content-type and encoding since they're not the default values):\n\n$ent = MIME::Entity->build(Description => \"A pretty picture\",\nPath        => \"./docs/mime-sm.gif\",\nType        => \"image/gif\",\nEncoding    => \"base64\");\n\nCreate a document that you already have the text for, using \"Data\":\n\n$ent = MIME::Entity->build(Type        => \"text/plain\",\nEncoding    => \"quoted-printable\",\nData        => [\"First line.\\n\",\n\"Second line.\\n\",\n\"Last line.\\n\"]);\n\nCreate a multipart message, with the entire structure given explicitly:\n\n### Create the top-level, and set up the mail headers:\n$top = MIME::Entity->build(Type     => \"multipart/mixed\",\nFrom     => 'me@myhost.com',\nTo       => 'you@yourhost.com',\nSubject  => \"Hello, nurse!\");\n\n### Attachment #1: a simple text document:\n$top->attach(Path=>\"./testin/short.txt\");\n\n### Attachment #2: a GIF file:\n$top->attach(Path        => \"./docs/mime-sm.gif\",\nType        => \"image/gif\",\nEncoding    => \"base64\");\n\n### Attachment #3: text we'll create with text we have on-hand:\n$top->attach(Data => $contents);\n\nSuppose you don't know ahead of time that you'll have attachments? No problem: you can \"attach\"\nto singleparts as well:\n\n$top = MIME::Entity->build(From    => 'me@myhost.com',\nTo      => 'you@yourhost.com',\nSubject => \"Hello, nurse!\",\nData    => \\@mymessage);\nif ($GIFpath) {\n$top->attach(Path     => $GIFpath,\nType     => 'image/gif');\n}\n\nCopy an entity (headers, parts... everything but external body data):\n\nmy $deepcopy = $top->dup;\n"
                },
                {
                    "name": "Access examples",
                    "content": "### Get the head, a MIME::Head:\n$head = $ent->head;\n\n### Get the body, as a MIME::Body;\n$bodyh = $ent->bodyhandle;\n\n### Get the intended MIME type (as declared in the header):\n$type = $ent->mimetype;\n\n### Get the effective MIME type (in case decoding failed):\n$efftype = $ent->effectivetype;\n\n### Get preamble, parts, and epilogue:\n$preamble   = $ent->preamble;          ### ref to array of lines\n$numparts  = $ent->parts;\n$firstpart = $ent->parts(0);          ### an entity\n$epilogue   = $ent->epilogue;          ### ref to array of lines\n"
                },
                {
                    "name": "Manipulation examples",
                    "content": "Muck about with the body data:\n\n### Read the (unencoded) body data:\nif ($io = $ent->open(\"r\")) {\nwhile (defined($ = $io->getline)) { print $ }\n$io->close;\n}\n\n### Write the (unencoded) body data:\nif ($io = $ent->open(\"w\")) {\nforeach (@lines) { $io->print($) }\n$io->close;\n}\n\n### Delete the files for any external (on-disk) data:\n$ent->purge;\n\nMuck about with the signature:\n\n### Sign it (automatically removes any existing signature):\n$top->sign(File=>\"$ENV{HOME}/.signature\");\n\n### Remove any signature within 15 lines of the end:\n$top->removesig(15);\n\nMuck about with the headers:\n\n### Compute content-lengths for singleparts based on bodies:\n###   (Do this right before you print!)\n$entity->syncheaders(Length=>'COMPUTE');\n\nMuck about with the structure:\n\n### If a 0- or 1-part multipart, collapse to a singlepart:\n$top->makesinglepart;\n\n### If a singlepart, inflate to a multipart with 1 part:\n$top->makemultipart;\n\nDelete parts:\n\n### Delete some parts of a multipart message:\nmy @keep = grep { keeppart($) } $msg->parts;\n$msg->parts(\\@keep);\n"
                },
                {
                    "name": "Output examples",
                    "content": "Print to filehandles:\n\n### Print the entire message:\n$top->print(\\*STDOUT);\n\n### Print just the header:\n$top->printheader(\\*STDOUT);\n\n### Print just the (encoded) body... includes parts as well!\n$top->printbody(\\*STDOUT);\n\nStringify... note that \"stringifyxx\" can also be written \"xxasstring\"; the methods are\nsynonymous, and neither form will be deprecated.\n\nIf you set the variable $MIME::Entity::BOUNDARYDELIMITER to a string, that string will be used\nas the line-end delimiter on output. If it is not set, the line ending will be a newline\ncharacter (\\n)\n\nNOTE that $MIME::Entity::BOUNDARYDELIMITER only applies to structural parts of the MIME data\ngenerated by this package and to the Base64 encoded output; if a part internally uses a\ndifferent line-end delimiter and is output as-is, the line-ending is not changed to match\n$MIME::Entity::BOUNDARYDELIMITER.\n\n### Stringify the entire message:\nprint $top->stringify;              ### or $top->asstring\n\n### Stringify just the header:\nprint $top->stringifyheader;       ### or $top->headerasstring\n\n### Stringify just the (encoded) body... includes parts as well!\nprint $top->stringifybody;         ### or $top->bodyasstring\n\nDebug:\n\n### Output debugging info:\n$entity->dumpskeleton(\\*STDERR);\n"
                }
            ]
        },
        "PUBLIC INTERFACE": {
            "content": "",
            "subsections": [
                {
                    "name": "Construction",
                    "content": "new [SOURCE]\n*Class method.* Create a new, empty MIME entity. Basically, this uses the Mail::Internet\nconstructor...\n\nIf SOURCE is an ARRAYREF, it is assumed to be an array of lines that will be used to create\nboth the header and an in-core body.\n\nElse, if SOURCE is defined, it is assumed to be a filehandle from which the header and\nin-core body is to be read.\n\nNote: in either case, the body will not be *parsed:* merely read!\n\naddpart ENTITY, [OFFSET]\n*Instance method.* Assuming we are a multipart message, add a body part (a MIME::Entity) to\nthe array of body parts. Returns the part that was just added.\n\nIf OFFSET is positive, the new part is added at that offset from the beginning of the array\nof parts. If it is negative, it counts from the end of the array. (An INDEX of -1 will place\nthe new part at the very end of the array, -2 will place it as the penultimate item in the\narray, etc.) If OFFSET is not given, the new part is added to the end of the array. *Thanks\nto Jason L Tibbitts III for providing support for OFFSET.*\n\nWarning: in general, you only want to attach parts to entities with a content-type of\n\"multipart/*\").\n\nattach PARAMHASH\n*Instance method.* The real quick-and-easy way to create multipart messages. The PARAMHASH\nis used to \"build\" a new entity; this method is basically equivalent to:\n\n$entity->addpart(ref($entity)->build(PARAMHASH, Top=>0));\n\nNote: normally, you attach to multipart entities; however, if you attach something to a\nsinglepart (like attaching a GIF to a text message), the singlepart will be coerced into a\nmultipart automatically.\n\nbuild PARAMHASH\n*Class/instance method.* A quick-and-easy catch-all way to create an entity. Use it like\nthis to build a \"normal\" single-part entity:\n\n$ent = MIME::Entity->build(Type     => \"image/gif\",\nEncoding => \"base64\",\nPath     => \"/path/to/xyz12345.gif\",\nFilename => \"saveme.gif\",\nDisposition => \"attachment\");\n\nAnd like this to build a \"multipart\" entity:\n\n$ent = MIME::Entity->build(Type     => \"multipart/mixed\",\nBoundary => \"---1234567\");\n\nA minimal MIME header will be created. If you want to add or modify any header fields\nafterwards, you can of course do so via the underlying head object... but hey, there's now a\nprettier syntax!\n\n$ent = MIME::Entity->build(Type          =>\"multipart/mixed\",\nFrom          => $myaddr,\nSubject       => \"Hi!\",\n'X-Certified' => ['SINED',\n'SEELED',\n'DELIVERED']);\n\nNormally, an \"X-Mailer\" header field is output which contains this toolkit's name and\nversion (plus this module's RCS version). This will allow any bad MIME we generate to be\ntraced back to us. You can of course overwrite that header with your own:\n\n$ent = MIME::Entity->build(Type        => \"multipart/mixed\",\n'X-Mailer'  => \"myprog 1.1\");\n\nOr remove it entirely:\n\n$ent = MIME::Entity->build(Type       => \"multipart/mixed\",\n'X-Mailer' => undef);\n\nOK, enough hype. The parameters are:\n\n(FIELDNAME)\nAny field you want placed in the message header, taken from the standard list of header\nfields (you don't need to worry about case):\n\nBcc           Encrypted     Received      Sender\nCc            From          References    Subject\nComments      Keywords      Reply-To      To\nContent-*     Message-ID    Resent-*      X-*\nDate          MIME-Version  Return-Path\nOrganization\n\nTo give experienced users some veto power, these fields will be set *after* the ones I\nset... so be careful: *don't set any MIME fields* (like \"Content-type\") unless you know\nwhat you're doing!\n\nTo specify a fieldname that's *not* in the above list, even one that's identical to an\noption below, just give it with a trailing \":\", like \"My-field:\". When in doubt, that\n*always* signals a mail field (and it sort of looks like one too).\n\nBoundary\n*Multipart entities only. Optional.* The boundary string. As per RFC-2046, it must\nconsist only of the characters \"[0-9a-zA-Z'()+,-./:=?]\" and space (you'll be warned,\nand your boundary will be ignored, if this is not the case). If you omit this, a random\nstring will be chosen... which is probably safer.\n\nCharset\n*Optional.* The character set.\n\nData\n*Single-part entities only. Optional.* An alternative to Path (q.v.): the actual data,\neither as a scalar or an array reference (whose elements are joined together to make the\nactual scalar). The body is opened on the data using MIME::Body::InCore.\n\nDescription\n*Optional.* The text of the content-description. If you don't specify it, the field is\nnot put in the header.\n\nDisposition\n*Optional.* The basic content-disposition (\"attachment\" or \"inline\"). If you don't\nspecify it, it defaults to \"inline\" for backwards compatibility. *Thanks to Kurt Freytag\nfor suggesting this feature.*\n\nEncoding\n*Optional.* The content-transfer-encoding. If you don't specify it, a reasonable default\nis put in. You can also give the special value '-SUGGEST', to have it chosen for you in\na heavy-duty fashion which scans the data itself.\n\nFilename\n*Single-part entities only. Optional.* The recommended filename. Overrides any name\nextracted from \"Path\". The information is stored both the deprecated (content-type) and\npreferred (content-disposition) locations. If you explicitly want to *avoid* a\nrecommended filename (even when Path is used), supply this as empty or undef.\n\nId  *Optional.* Set the content-id.\n\nPath\n*Single-part entities only. Optional.* The path to the file to attach. The body is\nopened on that file using MIME::Body::File.\n\nTop *Optional.* Is this a top-level entity? If so, it must sport a MIME-Version. The default\nis true. (NB: look at how \"attach()\" uses it.)\n\nType\n*Optional.* The basic content-type (\"text/plain\", etc.). If you don't specify it, it\ndefaults to \"text/plain\" as per RFC 2045. *Do yourself a favor: put it in.*\n\ndup *Instance method.* Duplicate the entity. Does a deep, recursive copy, *but beware:* external\ndata in bodyhandles is *not* copied to new files! Changing the data in one entity's data\nfile, or purging that entity, *will* affect its duplicate. Entities with in-core data\nprobably need not worry.\n"
                },
                {
                    "name": "Access",
                    "content": "body [VALUE]\n*Instance method.* Get the *encoded* (transport-ready) body, as an array of lines. Returns\nan array reference. Each array entry is a newline-terminated line.\n\nThis is a read-only data structure: changing its contents will have no effect. Its contents\nare identical to what is printed by printbody().\n\nProvided for compatibility with Mail::Internet, so that methods like \"smtpsend()\" will work.\nNote however that if VALUE is given, a fatal exception is thrown, since you cannot use this\nmethod to *set* the lines of the encoded message.\n\nIf you want the raw (unencoded) body data, use the bodyhandle() method to get and use a\nMIME::Body. The content-type of the entity will tell you whether that body is best read as\ntext (via getline()) or raw data (via read()).\n\nbodyhandle [VALUE]\n*Instance method.* Get or set an abstract object representing the body of the message. The\nbody holds the decoded message data.\n\nNote that not all entities have bodies! An entity will have either a body or parts: not\nboth. This method will *only* return an object if this entity can have a body; otherwise, it\nwill return undefined. Whether-or-not a given entity can have a body is determined by (1)\nits content type, and (2) whether-or-not the parser was told to extract nested messages:\n\nType:        | Extract nested? | bodyhandle() | parts()\n-----------------------------------------------------------------------\nmultipart/*  | -               | undef        | 0 or more MIME::Entity\nmessage/*    | true            | undef        | 0 or 1 MIME::Entity\nmessage/*    | false           | MIME::Body   | empty list\n(other)      | -               | MIME::Body   | empty list\n\nIf \"VALUE\" *is not* given, the current bodyhandle is returned, or undef if the entity cannot\nhave a body.\n\nIf \"VALUE\" *is* given, the bodyhandle is set to the new value, and the previous value is\nreturned.\n\nSee \"parts\" for more info.\n\neffectivetype [MIMETYPE]\n*Instance method.* Set/get the *effective* MIME type of this entity. This is *usually*\nidentical to the actual (or defaulted) MIME type, but in some cases it differs. For example,\nfrom RFC-2045:\n\nAny entity with an unrecognized Content-Transfer-Encoding must be\ntreated as if it has a Content-Type of \"application/octet-stream\",\nregardless of what the Content-Type header field actually says.\n\nWhy? because if we can't decode the message, then we have to take the bytes as-is, in their\n(unrecognized) encoded form. So the message ceases to be a \"text/foobar\" and becomes a bunch\nof undecipherable bytes -- in other words, an \"application/octet-stream\".\n\nSuch an entity, if parsed, would have its effectivetype() set to\n\"application/octetstream\", although the mimetype() and the contents of the header would\nremain the same.\n\nIf there is no effective type, the method just returns what mimetype() would.\n\nWarning: the effective type is \"sticky\"; once set, that effectivetype() will always be\nreturned even if the conditions that necessitated setting the effective type become no\nlonger true.\n\nepilogue [LINES]\n*Instance method.* Get/set the text of the epilogue, as an array of newline-terminated\nLINES. Returns a reference to the array of lines, or undef if no epilogue exists.\n\nIf there is a epilogue, it is output when printing this entity; otherwise, a default\nepilogue is used. Setting the epilogue to undef (not []!) causes it to fallback to the\ndefault.\n\nhead [VALUE]\n*Instance method.* Get/set the head.\n\nIf there is no VALUE given, returns the current head. If none exists, an empty instance of\nMIME::Head is created, set, and returned.\n\nNote: This is a patch over a problem in Mail::Internet, which doesn't provide a method for\nsetting the head to some given object.\n\nismultipart\n*Instance method.* Does this entity's effective MIME type indicate that it's a multipart\nentity? Returns undef (false) if the answer couldn't be determined, 0 (false) if it was\ndetermined to be false, and true otherwise. Note that this says nothing about whether or not\nparts were extracted.\n\nNOTE: we switched to effectivetype so that multiparts with bad or missing boundaries could\nbe coerced to an effective type of \"application/x-unparseable-multipart\".\n\nmimetype\n*Instance method.* A purely-for-convenience method. This simply relays the request to the\nassociated MIME::Head object. If there is no head, returns undef in a scalar context and the\nempty array in a list context.\n\nBefore you use this, consider using effectivetype() instead, especially if you obtained the\nentity from a MIME::Parser.\n\nopen READWRITE\n*Instance method.* A purely-for-convenience method. This simply relays the request to the\nassociated MIME::Body object (see MIME::Body::open()). READWRITE is either 'r' (open for\nread) or 'w' (open for write).\n\nIf there is no body, returns false.\n\nparts\nparts INDEX\nparts ARRAYREF\n*Instance method.* Return the MIME::Entity objects which are the sub parts of this entity\n(if any).\n\n*If no argument is given,* returns the array of all sub parts, returning the empty array if\nthere are none (e.g., if this is a single part message, or a degenerate multipart). In a\nscalar context, this returns you the number of parts.\n\n*If an integer INDEX is given,* return the INDEXed part, or undef if it doesn't exist.\n\n*If an ARRAYREF to an array of parts is given,* then this method *sets* the parts to a copy\nof that array, and returns the parts. This can be used to delete parts, as follows:\n\n### Delete some parts of a multipart message:\n$msg->parts([ grep { keeppart($) } $msg->parts ]);\n\nNote: for multipart messages, the preamble and epilogue are *not* considered parts. If you\nneed them, use the \"preamble()\" and \"epilogue()\" methods.\n\nNote: there are ways of parsing with a MIME::Parser which cause certain message parts (such\nas those of type \"message/rfc822\") to be \"reparsed\" into pseudo-multipart entities. You\nshould read the documentation for those options carefully: it *is* possible for a diddled\nentity to not be multipart, but still have parts attached to it!\n\nSee \"bodyhandle\" for a discussion of parts vs. bodies.\n\npartsDFS\n*Instance method.* Return the list of all MIME::Entity objects included in the entity,\nstarting with the entity itself, in depth-first-search order. If the entity has no parts, it\nalone will be returned.\n\n*Thanks to Xavier Armengou for suggesting this method.*\n\npreamble [LINES]\n*Instance method.* Get/set the text of the preamble, as an array of newline-terminated\nLINES. Returns a reference to the array of lines, or undef if no preamble exists (e.g., if\nthis is a single-part entity).\n\nIf there is a preamble, it is output when printing this entity; otherwise, a default\npreamble is used. Setting the preamble to undef (not []!) causes it to fallback to the\ndefault.\n"
                },
                {
                    "name": "Manipulation",
                    "content": "makemultipart [SUBTYPE], OPTSHASH...\n*Instance method.* Force the entity to be a multipart, if it isn't already. We do this by\nreplacing the original [singlepart] entity with a new multipart that has the same non-MIME\nheaders (\"From\", \"Subject\", etc.), but all-new MIME headers (\"Content-type\", etc.). We then\ncreate a copy of the original singlepart, *strip out* the non-MIME headers from that, and\nmake it a part of the new multipart. So this:\n\nFrom: me\nTo: you\nContent-type: text/plain\nContent-length: 12\n\nHello there!\n\nBecomes something like this:\n\nFrom: me\nTo: you\nContent-type: multipart/mixed; boundary=\"----abc----\"\n\n------abc----\nContent-type: text/plain\nContent-length: 12\n\nHello there!\n------abc------\n\nThe actual type of the new top-level multipart will be \"multipart/SUBTYPE\" (default SUBTYPE\nis \"mixed\").\n\nReturns 'DONE' if we really did inflate a singlepart to a multipart. Returns 'ALREADY' (and\ndoes nothing) if entity is *already* multipart and Force was not chosen.\n\nIf OPTSHASH contains Force=>1, then we *always* bump the top-level's content and\ncontent-headers down to a subpart of this entity, even if this entity is already a\nmultipart. This is apparently of use to people who are tweaking messages after parsing them.\n\nmakesinglepart\n*Instance method.* If the entity is a multipart message with one part, this tries hard to\nrewrite it as a singlepart, by replacing the content (and content headers) of the top level\nwith those of the part. Also crunches 0-part multiparts into singleparts.\n\nReturns 'DONE' if we really did collapse a multipart to a singlepart. Returns 'ALREADY' (and\ndoes nothing) if entity is already a singlepart. Returns '0' (and does nothing) if it can't\nbe made into a singlepart.\n\npurge\n*Instance method.* Recursively purge (e.g., unlink) all external (e.g., on-disk) body parts\nin this message. See MIME::Body::purge() for details.\n\nNote: this does *not* delete the directories that those body parts are contained in; only\nthe actual message data files are deleted. This is because some parsers may be customized to\ncreate intermediate directories while others are not, and it's impossible for this class to\nknow what directories are safe to remove. Only your application program truly knows that.\n\nIf you really want to \"clean everything up\", one good way is to use\n\"MIME::Parser::fileunder()\", and then do this before parsing your next message:\n\n$parser->filer->purge();\n\nI wouldn't attempt to read those body files after you do this, for obvious reasons. As of\nMIME-tools 4.x, each body's path *is* undefined after this operation. I warned you I might\ndo this; truly I did.\n\n*Thanks to Jason L. Tibbitts III for suggesting this method.*\n\nremovesig [NLINES]\n*Instance method, override.* Attempts to remove a user's signature from the body of a\nmessage.\n\nIt does this by looking for a line matching \"/^-- $/\" within the last \"NLINES\" of the\nmessage. If found then that line and all lines after it will be removed. If \"NLINES\" is not\ngiven, a default value of 10 will be used. This would be of most use in auto-reply scripts.\n\nFor MIME entity, this method is reasonably cautious: it will only attempt to un-sign a\nmessage with a content-type of \"text/*\".\n\nIf you send removesig() to a multipart entity, it will relay it to the first part (the\nothers usually being the \"attachments\").\n\nWarning: currently slurps the whole message-part into core as an array of lines, so you\nprobably don't want to use this on extremely long messages.\n\nReturns truth on success, false on error.\n\nsign PARAMHASH\n*Instance method, override.* Append a signature to the message. The params are:\n\nAttach\nInstead of appending the text, add it to the message as an attachment. The disposition\nwill be \"inline\", and the description will indicate that it is a signature. The default\nbehavior is to append the signature to the text of the message (or the text of its first\npart if multipart). *MIME-specific; new in this subclass.*\n\nFile\nUse the contents of this file as the signature. Fatal error if it can't be read. *As per\nsuperclass method.*\n\nForce\nSign it even if the content-type isn't \"text/*\". Useful for non-standard types like\n\"x-foobar\", but be careful! *MIME-specific; new in this subclass.*\n\nRemove\nNormally, we attempt to strip out any existing signature. If true, this gives us the\nNLINES parameter of the removesig call. If zero but defined, tells us *not* to remove\nany existing signature. If undefined, removal is done with the default of 10 lines. *New\nin this subclass.*\n\nSignature\nUse this text as the signature. You can supply it as either a scalar, or as a ref to an\narray of newline-terminated scalars. *As per superclass method.*\n\nFor MIME messages, this method is reasonably cautious: it will only attempt to sign a\nmessage with a content-type of \"text/*\", unless \"Force\" is specified.\n\nIf you send this message to a multipart entity, it will relay it to the first part (the\nothers usually being the \"attachments\").\n\nWarning: currently slurps the whole message-part into core as an array of lines, so you\nprobably don't want to use this on extremely long messages.\n\nReturns true on success, false otherwise.\n\nsuggestencoding\n*Instance method.* Based on the effective content type, return a good suggested encoding.\n\n\"text\" and \"message\" types have their bodies scanned line-by-line for 8-bit characters and\nlong lines; lack of either means that the message is 7bit-ok. Other types are chosen\nindependent of their body:\n\nMajor type:      7bit ok?    Suggested encoding:\n-----------------------------------------------------------\ntext             yes         7bit\ntext             no          quoted-printable\nmessage          yes         7bit\nmessage          no          binary\nmultipart        *           binary (in case some parts are bad)\nimage, etc...    *           base64\n\nsyncheaders OPTIONS\n*Instance method.* This method does a variety of activities which ensure that the MIME\nheaders of an entity \"tree\" are in-synch with the body parts they describe. It can be as\nexpensive an operation as printing if it involves pre-encoding the body parts; however, the\naim is to produce fairly clean MIME. You will usually only need to invoke this if processing\nand re-sending MIME from an outside source.\n\nThe OPTIONS is a hash, which describes what is to be done.\n\nLength\nOne of the \"official unofficial\" MIME fields is \"Content-Length\". Normally, one doesn't\ncare a whit about this field; however, if you are preparing output destined for HTTP,\nyou may. The value of this option dictates what will be done:\n\nCOMPUTE means to set a \"Content-Length\" field for every non-multipart part in the\nentity, and to blank that field out for every multipart part in the entity.\n\nERASE means that \"Content-Length\" fields will all be blanked out. This is fast,\npainless, and safe.\n\nAny false value (the default) means to take no action.\n\nNonstandard\nAny header field beginning with \"Content-\" is, according to the RFC, a MIME field.\nHowever, some are non-standard, and may cause problems with certain MIME readers which\ninterpret them in different ways.\n\nERASE means that all such fields will be blanked out. This is done *before* the Length\noption (q.v.) is examined and acted upon.\n\nAny false value (the default) means to take no action.\n\nReturns a true value if everything went okay, a false value otherwise.\n\ntidybody\n*Instance method, override.* Currently unimplemented for MIME messages. Does nothing,\nreturns false.\n"
                },
                {
                    "name": "Output",
                    "content": "dumpskeleton [FILEHANDLE]\n*Instance method.* Dump the skeleton of the entity to the given FILEHANDLE, or to the\ncurrently-selected one if none given.\n\nEach entity is output with an appropriate indentation level, the following selection of\nattributes:\n\nContent-type: multipart/mixed\nEffective-type: multipart/mixed\nBody-file: NONE\nSubject: Hey there!\nNum-parts: 2\n\nThis is really just useful for debugging purposes; I make no guarantees about the\nconsistency of the output format over time.\n\nprint [OUTSTREAM]\n*Instance method, override.* Print the entity to the given OUTSTREAM, or to the\ncurrently-selected filehandle if none given. OUTSTREAM can be a filehandle, or any object\nthat responds to a print() message.\n\nThe entity is output as a valid MIME stream! This means that the header is always output\nfirst, and the body data (if any) will be encoded if the header says that it should be. For\nexample, your output may look like this:\n\nSubject: Greetings\nContent-transfer-encoding: base64\n\nSGkgdGhlcmUhCkJ5ZSB0aGVyZSEK\n\n*If this entity has MIME type \"multipart/*\",* the preamble, parts, and epilogue are all\noutput with appropriate boundaries separating each. Any bodyhandle is ignored:\n\nContent-type: multipart/mixed; boundary=\"*----*\"\nContent-transfer-encoding: 7bit\n\n[Preamble]\n--*----*\n[Entity: Part 0]\n--*----*\n[Entity: Part 1]\n--*----*--\n[Epilogue]\n\n*If this entity has a single-part MIME type with no attached parts,* then we're looking at a\nnormal singlepart entity: the body is output according to the encoding specified by the\nheader. If no body exists, a warning is output and the body is treated as empty:\n\nContent-type: image/gif\nContent-transfer-encoding: base64\n\n[Encoded body]\n\n*If this entity has a single-part MIME type but it also has parts,* then we're probably\nlooking at a \"re-parsed\" singlepart, usually one of type \"message/*\" (you can get entities\nlike this if you set the \"parsenestedmessages(NEST)\" option on the parser to true). In\nthis case, the parts are output with single blank lines separating each, and any bodyhandle\nis ignored:\n\nContent-type: message/rfc822\nContent-transfer-encoding: 7bit\n\n[Entity: Part 0]\n\n[Entity: Part 1]\n\nIn all cases, when outputting a \"part\" of the entity, this method is invoked recursively.\n\nNote: the output is very likely *not* going to be identical to any input you parsed to get\nthis entity. If you're building some sort of email handler, it's up to you to save this\ninformation.\n\nprintbody [OUTSTREAM]\n*Instance method, override.* Print the body of the entity to the given OUTSTREAM, or to the\ncurrently-selected filehandle if none given. OUTSTREAM can be a filehandle, or any object\nthat responds to a print() message.\n\nThe body is output for inclusion in a valid MIME stream; this means that the body data will\nbe encoded if the header says that it should be.\n\nNote: by \"body\", we mean \"the stuff following the header\". A printed multipart body includes\nthe printed representations of its subparts.\n\nNote: The body is *stored* in an un-encoded form; however, the idea is that the transfer\nencoding is used to determine how it should be *output.* This means that the \"print()\"\nmethod is always guaranteed to get you a sendmail-ready stream whose body is consistent with\nits head. If you want the *raw body data* to be output, you can either read it from the\nbodyhandle yourself, or use:\n\n$ent->bodyhandle->print($outstream);\n\nwhich uses read() calls to extract the information, and thus will work with both text and\nbinary bodies.\n\nWarning: Please supply an OUTSTREAM. This override method differs from Mail::Internet's\nbehavior, which outputs to the STDOUT if no filehandle is given: this may lead to confusion.\n\nprintheader [OUTSTREAM]\n*Instance method, inherited.* Output the header to the given OUTSTREAM. You really should\nsupply the OUTSTREAM.\n\nstringify\n*Instance method.* Return the entity as a string, exactly as \"print\" would print it. The\nbody will be encoded as necessary, and will contain any subparts. You can also use\n\"asstring()\".\n\nstringifybody\n*Instance method.* Return the *encoded* message body as a string, exactly as \"printbody\"\nwould print it. You can also use \"bodyasstring()\".\n\nIf you want the *unencoded* body, and you are dealing with a singlepart message (like a\n\"text/plain\"), use \"bodyhandle()\" instead:\n\nif ($ent->bodyhandle) {\n$unencodeddata = $ent->bodyhandle->asstring;\n}\nelse {\n### this message has no body data (but it might have parts!)\n}\n\nstringifyheader\n*Instance method.* Return the header as a string, exactly as \"printheader\" would print it.\nYou can also use \"headerasstring()\".\n"
                }
            ]
        },
        "NOTES": {
            "content": "",
            "subsections": [
                {
                    "name": "Under the hood",
                    "content": "A MIME::Entity is composed of the following elements:\n\n*   A *head*, which is a reference to a MIME::Head object containing the header information.\n\n*   A *bodyhandle*, which is a reference to a MIME::Body object containing the decoded body\ndata. This is only defined if the message is a \"singlepart\" type:\n\napplication/*\naudio/*\nimage/*\ntext/*\nvideo/*\n\n*   An array of *parts*, where each part is a MIME::Entity object. The number of parts will only\nbe nonzero if the content-type is *not* one of the \"singlepart\" types:\n\nmessage/*        (should have exactly one part)\nmultipart/*      (should have one or more parts)\n\nThe \"two-body problem\"\nMIME::Entity and Mail::Internet see message bodies differently, and this can cause confusion and\nsome inconvenience. Sadly, I can't change the behavior of MIME::Entity without breaking lots of\ncode already out there. But let's open up the floor for a few questions...\n\nWhat is the difference between a \"message\" and an \"entity\"?\nA message is the actual data being sent or received; usually this means a stream of\nnewline-terminated lines. An entity is the representation of a message as an object.\n\nThis means that you get a \"message\" when you print an \"entity\" *to* a filehandle, and you\nget an \"entity\" when you parse a message *from* a filehandle.\n\nWhat is a message body?\nMail::Internet: The portion of the printed message after the header.\n\nMIME::Entity: The portion of the printed message after the header.\n\nHow is a message body stored in an entity?\nMail::Internet: As an array of lines.\n\nMIME::Entity: It depends on the content-type of the message. For \"container\" types\n(\"multipart/*\", \"message/*\"), we store the contained entities as an array of \"parts\",\naccessed via the \"parts()\" method, where each part is a complete MIME::Entity. For\n\"singlepart\" types (\"text/*\", \"image/*\", etc.), the unencoded body data is referenced via a\nMIME::Body object, accessed via the \"bodyhandle()\" method:\n\nbodyhandle()   parts()\nContent-type:     returns:       returns:\n------------------------------------------------------------\napplication/*     MIME::Body     empty\naudio/*           MIME::Body     empty\nimage/*           MIME::Body     empty\nmessage/*         undef          MIME::Entity list (usually 1)\nmultipart/*       undef          MIME::Entity list (usually >0)\ntext/*            MIME::Body     empty\nvideo/*           MIME::Body     empty\nx-*/*             MIME::Body     empty\n\nAs a special case, \"message/*\" is currently ambiguous: depending on the parser, a\n\"message/*\" might be treated as a singlepart, with a MIME::Body and no parts. Use\nbodyhandle() as the final arbiter.\n\nWhat does the body() method return?\nMail::Internet: As an array of lines, ready for sending.\n\nMIME::Entity: As an array of lines, ready for sending.\n\nWhat's the best way to get at the body data?\nMail::Internet: Use the body() method.\n\nMIME::Entity: Depends on what you want... the *encoded* data (as it is transported), or the\n*unencoded* data? Keep reading...\n\nHow do I get the \"encoded\" body data?\nMail::Internet: Use the body() method.\n\nMIME::Entity: Use the body() method. You can also use:\n\n$entity->printbody()\n$entity->stringifybody()   ### a.k.a. $entity->bodyasstring()\n\nHow do I get the \"unencoded\" body data?\nMail::Internet: Use the body() method.\n\nMIME::Entity: Use the *bodyhandle()* method! If bodyhandle() method returns true, then that\nvalue is a MIME::Body which can be used to access the data via its open() method. If\nbodyhandle() method returns an undefined value, then the entity is probably a \"container\"\nthat has no real body data of its own (e.g., a \"multipart\" message): in this case, you\nshould access the components via the parts() method. Like this:\n\nif ($bh = $entity->bodyhandle) {\n$io = $bh->open;\n...access unencoded data via $io->getline or $io->read...\n$io->close;\n}\nelse {\nforeach my $part (@parts) {\n...do something with the part...\n}\n}\n\nYou can also use:\n\nif ($bh = $entity->bodyhandle) {\n$unencodeddata = $bh->asstring;\n}\nelse {\n...do stuff with the parts...\n}\n\nWhat does the body() method return?\nMail::Internet: The transport-encoded message body, as an array of lines.\n\nMIME::Entity: The transport-encoded message body, as an array of lines.\n\nWhat does printbody() print?\nMail::Internet: Exactly what body() would return to you.\n\nMIME::Entity: Exactly what body() would return to you.\n\nSay I have an entity which might be either singlepart or multipart. How do I print out just \"the\nstuff after the header\"?\nMail::Internet: Use printbody().\n\nMIME::Entity: Use printbody().\n\nWhy is MIME::Entity so different from Mail::Internet?\nBecause MIME streams are expected to have non-textual data... possibly, quite a lot of it,\nsuch as a tar file.\n\nBecause MIME messages can consist of multiple parts, which are most-easily manipulated as\nMIME::Entity objects themselves.\n\nBecause in the simpler world of Mail::Internet, the data of a message and its printed\nrepresentation are *identical*... and in the MIME world, they're not.\n\nBecause parsing multipart bodies on-the-fly, or formatting multipart bodies for output, is a\nnon-trivial task.\n\nThis is confusing. Can the two classes be made more compatible?\nNot easily; their implementations are necessarily quite different. Mail::Internet is a\nsimple, efficient way of dealing with a \"black box\" mail message... one whose internal data\nyou don't care much about. MIME::Entity, in contrast, cares *very much* about the message\ncontents: that's its job!\n"
                },
                {
                    "name": "Design issues",
                    "content": "Some things just can't be ignored\nIn multipart messages, the *\"preamble\"* is the portion that precedes the first encapsulation\nboundary, and the *\"epilogue\"* is the portion that follows the last encapsulation boundary.\n\nAccording to RFC 2046:\n\nThere appears to be room for additional information prior\nto the first encapsulation boundary and following the final\nboundary.  These areas should generally be left blank, and\nimplementations must ignore anything that appears before the\nfirst boundary or after the last one.\n\nNOTE: These \"preamble\" and \"epilogue\" areas are generally\nnot used because of the lack of proper typing of these parts\nand the lack of clear semantics for handling these areas at\ngateways, particularly X.400 gateways.  However, rather than\nleaving the preamble area blank, many MIME implementations\nhave found this to be a convenient place to insert an\nexplanatory note for recipients who read the message with\npre-MIME software, since such notes will be ignored by\nMIME-compliant software.\n\nIn the world of standards-and-practices, that's the standard. Now for the practice:\n\n*Some \"MIME\" mailers may incorrectly put a \"part\" in the preamble*. Since we have to parse\nover the stuff *anyway*, in the future I *may* allow the parser option of creating special\nMIME::Entity objects for the preamble and epilogue, with bogus MIME::Head objects.\n\nFor now, though, we're MIME-compliant, so I probably won't change how we work.\n"
                }
            ]
        },
        "SEE ALSO": {
            "content": "MIME::Tools, MIME::Head, MIME::Body, MIME::Decoder, Mail::Internet\n",
            "subsections": []
        },
        "AUTHOR": {
            "content": "Eryq (eryq@zeegee.com), ZeeGee Software Inc (http://www.zeegee.com). Dianne Skoll\n(dfs@roaringpenguin.com) http://www.roaringpenguin.com\n\nAll rights reserved. This program is free software; you can redistribute it and/or modify it\nunder the same terms as Perl itself.\n",
            "subsections": []
        }
    },
    "summary": "MIME::Entity - class for parsed-and-decoded MIME message",
    "flags": [],
    "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    => \\@mymessage);",
        "if ($GIFpath) {",
        "$top->attach(Path     => $GIFpath,",
        "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->mimetype;",
        "### Get the effective MIME type (in case decoding failed):",
        "$efftype = $ent->effectivetype;",
        "### Get preamble, parts, and epilogue:",
        "$preamble   = $ent->preamble;          ### ref to array of lines",
        "$numparts  = $ent->parts;",
        "$firstpart = $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->removesig(15);",
        "Muck about with the headers:",
        "### Compute content-lengths for singleparts based on bodies:",
        "###   (Do this right before you print!)",
        "$entity->syncheaders(Length=>'COMPUTE');",
        "Muck about with the structure:",
        "### If a 0- or 1-part multipart, collapse to a singlepart:",
        "$top->makesinglepart;",
        "### If a singlepart, inflate to a multipart with 1 part:",
        "$top->makemultipart;",
        "Delete parts:",
        "### Delete some parts of a multipart message:",
        "my @keep = grep { keeppart($) } $msg->parts;",
        "$msg->parts(\\@keep);",
        "Print to filehandles:",
        "### Print the entire message:",
        "$top->print(\\*STDOUT);",
        "### Print just the header:",
        "$top->printheader(\\*STDOUT);",
        "### Print just the (encoded) body... includes parts as well!",
        "$top->printbody(\\*STDOUT);",
        "Stringify... note that \"stringifyxx\" can also be written \"xxasstring\"; the methods are",
        "synonymous, and neither form will be deprecated.",
        "If you set the variable $MIME::Entity::BOUNDARYDELIMITER to a string, that string will be used",
        "as the line-end delimiter on output. If it is not set, the line ending will be a newline",
        "character (\\n)",
        "NOTE that $MIME::Entity::BOUNDARYDELIMITER only applies to structural parts of the MIME data",
        "generated by this package and to the Base64 encoded output; if a part internally uses a",
        "different line-end delimiter and is output as-is, the line-ending is not changed to match",
        "$MIME::Entity::BOUNDARYDELIMITER.",
        "### Stringify the entire message:",
        "print $top->stringify;              ### or $top->asstring",
        "### Stringify just the header:",
        "print $top->stringifyheader;       ### or $top->headerasstring",
        "### Stringify just the (encoded) body... includes parts as well!",
        "print $top->stringifybody;         ### or $top->bodyasstring",
        "Debug:",
        "### Output debugging info:",
        "$entity->dumpskeleton(\\*STDERR);"
    ],
    "see_also": []
}