{
    "content": [
        {
            "type": "text",
            "text": "# MIME::Head (perldoc)\n\n## NAME\n\nMIME::Head - MIME message header (a subclass of Mail::Header)\n\n## SYNOPSIS\n\nBefore 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\n## DESCRIPTION\n\nA class for parsing in and manipulating RFC-822 message headers, with some methods geared\ntowards standard (and not so standard) MIME fields as specified in the various *Multipurpose\nInternet Mail Extensions* RFCs (starting with RFC 2045)\n\n## Sections\n\n- **NAME**\n- **SYNOPSIS** (6 subsections)\n- **DESCRIPTION**\n- **PUBLIC INTERFACE** (1 subsections)\n- **NOTES**\n- **SEE ALSO**\n- **AUTHOR**\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "MIME::Head",
        "section": "",
        "mode": "perldoc",
        "summary": "MIME::Head - MIME message header (a subclass of Mail::Header)",
        "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...",
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [],
        "see_also": [],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "SYNOPSIS",
                "lines": 5,
                "subsections": [
                    {
                        "name": "Construction",
                        "lines": 12
                    },
                    {
                        "name": "Output",
                        "lines": 7
                    },
                    {
                        "name": "Getting field contents",
                        "lines": 16
                    },
                    {
                        "name": "Setting field contents",
                        "lines": 3
                    },
                    {
                        "name": "Manipulating field contents",
                        "lines": 6
                    },
                    {
                        "name": "Getting high-level MIME information",
                        "lines": 17
                    }
                ]
            },
            {
                "name": "DESCRIPTION",
                "lines": 4,
                "subsections": []
            },
            {
                "name": "PUBLIC INTERFACE",
                "lines": 1,
                "subsections": [
                    {
                        "name": "Creation, input, and output",
                        "lines": 286
                    }
                ]
            },
            {
                "name": "NOTES",
                "lines": 65,
                "subsections": []
            },
            {
                "name": "SEE ALSO",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "AUTHOR",
                "lines": 9,
                "subsections": []
            }
        ],
        "sections": {
            "NAME": {
                "content": "MIME::Head - MIME message header (a subclass of Mail::Header)\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",
                "subsections": [
                    {
                        "name": "Construction",
                        "content": "### Create a new, empty header, and populate it manually:\n$head = MIME::Head->new;\n$head->replace('content-type', 'text/plain; charset=US-ASCII');\n$head->replace('content-length', $len);\n\n### Parse a new header from a filehandle:\n$head = MIME::Head->read(\\*STDIN);\n\n### Parse a new header from a file, or a readable pipe:\n$testhead = MIME::Head->fromfile(\"/tmp/test.hdr\");\n$abhead = MIME::Head->fromfile(\"cat a.hdr b.hdr |\");\n"
                    },
                    {
                        "name": "Output",
                        "content": "### Output to filehandle:\n$head->print(\\*STDOUT);\n\n### Output as string:\nprint STDOUT $head->asstring;\nprint STDOUT $head->stringify;\n"
                    },
                    {
                        "name": "Getting field contents",
                        "content": "### Is this a reply?\n$isreply = 1 if ($head->get('Subject') =~ /^Re: /);\n\n### Get receipt information:\nprint \"Last received from: \", $head->get('Received', 0);\n@allreceived = $head->get('Received');\n\n### Print the subject, or the empty string if none:\nprint \"Subject: \", $head->get('Subject',0);\n\n### Too many hops?  Count 'em and see!\nif ($head->count('Received') > 5) { ...\n\n### Test whether a given field exists\nwarn \"missing subject!\" if (! $head->count('subject'));\n"
                    },
                    {
                        "name": "Setting field contents",
                        "content": "### Declare this to be an HTML header:\n$head->replace('Content-type', 'text/html');\n"
                    },
                    {
                        "name": "Manipulating field contents",
                        "content": "### Get rid of internal newlines in fields:\n$head->unfold;\n\n### Decode any Q- or B-encoded-text in fields (DEPRECATED):\n$head->decode;\n"
                    },
                    {
                        "name": "Getting high-level MIME information",
                        "content": "### Get/set a given MIME attribute:\nunless ($charset = $head->mimeattr('content-type.charset')) {\n$head->mimeattr(\"content-type.charset\" => \"US-ASCII\");\n}\n\n### The content type (e.g., \"text/html\"):\n$mimetype     = $head->mimetype;\n\n### The content transfer encoding (e.g., \"quoted-printable\"):\n$mimeencoding = $head->mimeencoding;\n\n### The recommended name when extracted:\n$filename     = $head->recommendedfilename;\n\n### The boundary text, for multipart messages:\n$boundary      = $head->multipartboundary;\n"
                    }
                ]
            },
            "DESCRIPTION": {
                "content": "A class for parsing in and manipulating RFC-822 message headers, with some methods geared\ntowards standard (and not so standard) MIME fields as specified in the various *Multipurpose\nInternet Mail Extensions* RFCs (starting with RFC 2045)\n",
                "subsections": []
            },
            "PUBLIC INTERFACE": {
                "content": "",
                "subsections": [
                    {
                        "name": "Creation, input, and output",
                        "content": "new [ARG],[OPTIONS]\n*Class method, inherited.* Creates a new header object. Arguments are the same as those in\nthe superclass.\n\nfromfile EXPR,OPTIONS\n*Class or instance method*. For convenience, you can use this to parse a header object in\nfrom EXPR, which may actually be any expression that can be sent to open() so as to return a\nreadable filehandle. The \"file\" will be opened, read, and then closed:\n\n### Create a new header by parsing in a file:\nmy $head = MIME::Head->fromfile(\"/tmp/test.hdr\");\n\nSince this method can function as either a class constructor *or* an instance initializer,\nthe above is exactly equivalent to:\n\n### Create a new header by parsing in a file:\nmy $head = MIME::Head->new->fromfile(\"/tmp/test.hdr\");\n\nOn success, the object will be returned; on failure, the undefined value.\n\nThe OPTIONS are the same as in new(), and are passed into new() if this is invoked as a\nclass method.\n\nNote: This is really just a convenience front-end onto \"read()\", provided mostly for\nbackwards-compatibility with MIME-parser 1.0.\n\nread FILEHANDLE\n*Instance (or class) method.* This initializes a header object by reading it in from a\nFILEHANDLE, until the terminating blank line is encountered. A syntax error or end-of-stream\nwill also halt processing.\n\nSupply this routine with a reference to a filehandle glob; e.g., \"\\*STDIN\":\n\n### Create a new header by parsing in STDIN:\n$head->read(\\*STDIN);\n\nOn success, the self object will be returned; on failure, a false value.\n\nNote: in the MIME world, it is perfectly legal for a header to be empty, consisting of\nnothing but the terminating blank line. Thus, we can't just use the formula that \"no tags\nequals error\".\n\nWarning: as of the time of this writing, Mail::Header::read did not flag either syntax\nerrors or unexpected end-of-file conditions (an EOF before the terminating blank line).\nMIME::ParserBase takes this into account.\n\nGetting/setting fields\nThe following are methods related to retrieving and modifying the header fields. Some are\ninherited from Mail::Header, but I've kept the documentation around for convenience.\n\nadd TAG,TEXT,[INDEX]\n*Instance method, inherited.* Add a new occurrence of the field named TAG, given by TEXT:\n\n### Add the trace information:\n$head->add('Received',\n'from eryq.pr.mcs.net by gonzo.net with smtp');\n\nNormally, the new occurrence will be *appended* to the existing occurrences. However, if the\noptional INDEX argument is 0, then the new occurrence will be *prepended*. If you want to be\n*explicit* about appending, specify an INDEX of -1.\n\nWarning: this method always adds new occurrences; it doesn't overwrite any existing\noccurrences... so if you just want to *change* the value of a field (creating it if\nnecessary), then you probably don't want to use this method: consider using \"replace()\"\ninstead.\n\ncount TAG\n*Instance method, inherited.* Returns the number of occurrences of a field; in a boolean\ncontext, this tells you whether a given field exists:\n\n### Was a \"Subject:\" field given?\n$subjectwasgiven = $head->count('subject');\n\nThe TAG is treated in a case-insensitive manner. This method returns some false value if the\nfield doesn't exist, and some true value if it does.\n\ndecode [FORCE]\n*Instance method, DEPRECATED.* Go through all the header fields, looking for RFC 1522 / RFC\n2047 style \"Q\" (quoted-printable, sort of) or \"B\" (base64) encoding, and decode them\nin-place. Fellow Americans, you probably don't know what the hell I'm talking about.\nEuropeans, Russians, et al, you probably do. \":-)\".\n\nThis method has been deprecated. See \"decodeheaders\" in MIME::Parser for the full reasons.\nIf you absolutely must use it and don't like the warning, then provide a FORCE:\n\n\"INEEDTOFIXTHIS\"\nJust shut up and do it.  Not recommended.\nProvided only for those who need to keep old scripts functioning.\n\n\"IKNOWWHATIAMDOING\"\nJust shut up and do it.  Not recommended.\nProvided for those who REALLY know what they are doing.\n\nWhat this method does. For an example, let's consider a valid email header you might get:\n\nFrom: =?US-ASCII?Q?KeithMoore?= <moore@cs.utk.edu>\nTo: =?ISO-8859-1?Q?KeldJ=F8rnSimonsen?= <keld@dkuug.dk>\nCC: =?ISO-8859-1?Q?Andr=E9?= Pirard <PIRARD@vm1.ulg.ac.be>\nSubject: =?ISO-8859-1?B?SWYgeW91IGNhbiByZWFkIHRoaXMgeW8=?=\n=?ISO-8859-2?B?dSB1bmRlcnN0YW5kIHRoZSBleGFtcGxlLg==?=\n=?US-ASCII?Q?..cool!?=\n\nThat basically decodes to (sorry, I can only approximate the Latin characters with 7 bit\nsequences /o and 'e):\n\nFrom: Keith Moore <moore@cs.utk.edu>\nTo: Keld J/orn Simonsen <keld@dkuug.dk>\nCC: Andr'e  Pirard <PIRARD@vm1.ulg.ac.be>\nSubject: If you can read this you understand the example... cool!\n\nNote: currently, the decodings are done without regard to the character set: thus, the\nQ-encoding \"=F8\" is simply translated to the octet (hexadecimal \"F8\"), period. For\npiece-by-piece decoding of a given field, you want the array context of\n\"MIME::Words::decodemimewords()\".\n\nWarning: the CRLF+SPACE separator that splits up long encoded words into shorter sequences\n(see the Subject: example above) gets lost when the field is unfolded, and so decoding after\nunfolding causes a spurious space to be left in the field. *THEREFORE: if you're going to\ndecode, do so BEFORE unfolding!*\n\nThis method returns the self object.\n\n*Thanks to Kent Boortz for providing the idea, and the baseline RFC-1522-decoding code.*\n\ndelete TAG,[INDEX]\n*Instance method, inherited.* Delete all occurrences of the field named TAG.\n\n### Remove some MIME information:\n$head->delete('MIME-Version');\n$head->delete('Content-type');\n\nget TAG,[INDEX]\n*Instance method, inherited.* Get the contents of field TAG.\n\nIf a numeric INDEX is given, returns the occurrence at that index, or undef if not present:\n\n### Print the first and last 'Received:' entries (explicitly):\nprint \"First, or most recent: \", $head->get('received', 0);\nprint \"Last, or least recent: \", $head->get('received',-1);\n\nIf no INDEX is given, but invoked in a scalar context, then INDEX simply defaults to 0:\n\n### Get the first 'Received:' entry (implicitly):\nmy $mostrecent = $head->get('received');\n\nIf no INDEX is given, and invoked in an array context, then *all* occurrences of the field\nare returned:\n\n### Get all 'Received:' entries:\nmy @allreceived = $head->get('received');\n\nNOTE: The header(s) returned may end with a newline. If you don't want this, then chomp the\nreturn value.\n\ngetall FIELD\n*Instance method.* Returns the list of *all* occurrences of the field, or the empty list if\nthe field is not present:\n\n### How did it get here?\n@history = $head->getall('Received');\n\nNote: I had originally experimented with having \"get()\" return all occurrences when invoked\nin an array context... but that causes a lot of accidents when you get careless and do stuff\nlike this:\n\nprint \"\\u$field: \", $head->get($field);\n\nIt also made the intuitive behaviour unclear if the INDEX argument was given in an array\ncontext. So I opted for an explicit approach to asking for all occurrences.\n\nprint [OUTSTREAM]\n*Instance method, override.* Print the header out to the given OUTSTREAM, or the\ncurrently-selected filehandle if none. The OUTSTREAM may be a filehandle, or any object that\nresponds to a print() message.\n\nThe override actually lets you print to any object that responds to a print() method. This\nis vital for outputting MIME entities to scalars.\n\nAlso, it defaults to the *currently-selected* filehandle if none is given (not STDOUT!), so\n*please* supply a filehandle to prevent confusion.\n\nstringify\n*Instance method.* Return the header as a string. You can also invoke it as \"asstring\".\n\nIf you set the variable $MIME::Entity::BOUNDARYDELIMITER to a string, that string will be\nused as line-end delimiter. If it is not set, the line ending will be a newline character\n(\\n)\n\nunfold [FIELD]\n*Instance method, inherited.* Unfold (remove newlines in) the text of all occurrences of the\ngiven FIELD. If the FIELD is omitted, *all* fields are unfolded. Returns the \"self\" object.\n\nMIME-specific methods\nAll of the following methods extract information from the following fields:\n\nContent-type\nContent-transfer-encoding\nContent-disposition\n\nBe aware that they do not just return the raw contents of those fields, and in some cases they\nwill fill in sensible (I hope) default values. Use \"get()\" or \"mimeattr()\" if you need to grab\nand process the raw field text.\n\nNote: some of these methods are provided both as a convenience and for backwards-compatibility\nonly, while others (like recommendedfilename()) *really do have to be in MIME::Head to work\nproperly,* since they look for their value in more than one field. However, if you know that a\nvalue is restricted to a single field, you should really use the Mail::Field interface to get\nit.\n\nmimeattr ATTR,[VALUE]\nA quick-and-easy interface to set/get the attributes in structured MIME fields:\n\n$head->mimeattr(\"content-type\"         => \"text/html\");\n$head->mimeattr(\"content-type.charset\" => \"US-ASCII\");\n$head->mimeattr(\"content-type.name\"    => \"homepage.html\");\n\nThis would cause the final output to look something like this:\n\nContent-type: text/html; charset=US-ASCII; name=\"homepage.html\"\n\nNote that the special empty sub-field tag indicates the anonymous first sub-field.\n\nGiving VALUE as undefined will cause the contents of the named subfield to be deleted:\n\n$head->mimeattr(\"content-type.charset\" => undef);\n\nSupplying no VALUE argument just returns the attribute's value, or undefined if it isn't\nthere:\n\n$type = $head->mimeattr(\"content-type\");      ### text/html\n$name = $head->mimeattr(\"content-type.name\"); ### homepage.html\n\nIn all cases, the new/current value is returned.\n\nmimeencoding\n*Instance method.* Try *real hard* to determine the content transfer encoding (e.g.,\n\"base64\", \"binary\"), which is returned in all-lowercase.\n\nIf no encoding could be found, the default of \"7bit\" is returned I quote from RFC 2045\nsection 6.1:\n\nThis is the default value -- that is, \"Content-Transfer-Encoding: 7BIT\"\nis assumed if the Content-Transfer-Encoding header field is not present.\n\nI do one other form of fixup: \"7bit\", \"7-bit\", and \"7 bit\" are corrected to \"7bit\";\nlikewise for \"8bit\".\n\nmimetype [DEFAULT]\n*Instance method.* Try \"real hard\" to determine the content type (e.g., \"text/plain\",\n\"image/gif\", \"x-weird-type\", which is returned in all-lowercase. \"Real hard\" means that if\nno content type could be found, the default (usually \"text/plain\") is returned. From RFC\n2045 section 5.2:\n\nDefault RFC 822 messages without a MIME Content-Type header are\ntaken by this protocol to be plain text in the US-ASCII character\nset, which can be explicitly specified as:\n\nContent-type: text/plain; charset=us-ascii\n\nThis default is assumed if no Content-Type header field is specified.\n\nUnless this is a part of a \"multipart/digest\", in which case \"message/rfc822\" is the\ndefault. Note that you can also *set* the default, but you shouldn't: normally only the MIME\nparser uses this feature.\n\nmultipartboundary\n*Instance method.* If this is a header for a multipart message, return the \"encapsulation\nboundary\" used to separate the parts. The boundary is returned exactly as given in the\n\"Content-type:\" field; that is, the leading double-hyphen (\"--\") is *not* prepended.\n\nWell, *almost* exactly... this passage from RFC 2046 dictates that we remove any trailing\nspaces:\n\nIf a boundary appears to end with white space, the white space\nmust be presumed to have been added by a gateway, and must be deleted.\n\nReturns undef (not the empty string) if either the message is not multipart or if there is\nno specified boundary.\n\nrecommendedfilename\n*Instance method.* Return the recommended external filename. This is used when extracting\nthe data from the MIME stream. The filename is always returned as a string in Perl's\ninternal format (the UTF8 flag may be on!)\n\nReturns undef if no filename could be suggested.\n"
                    }
                ]
            },
            "NOTES": {
                "content": "Why have separate objects for the entity, head, and body?\nSee the documentation for the MIME-tools distribution for the rationale behind this\ndecision.\n\nWhy assume that MIME headers are email headers?\nI quote from Achim Bohnet, who gave feedback on v.1.9 (I think he's using the word \"header\"\nwhere I would use \"field\"; e.g., to refer to \"Subject:\", \"Content-type:\", etc.):\n\nThere is also IMHO no requirement [for] MIME::Heads to look\nlike [email] headers; so to speak, the MIME::Head [simply stores]\nthe attributes of a complex object, e.g.:\n\nnew MIME::Head type => \"text/plain\",\ncharset => ...,\ndisposition => ..., ... ;\n\nI agree in principle, but (alas and dammit) RFC 2045 says otherwise. RFC 2045 [MIME] headers\nare a syntactic subset of RFC-822 [email] headers.\n\nIn my mind's eye, I see an abstract class, call it MIME::Attrs, which does what Achim\nsuggests... so you could say:\n\nmy $attrs = new MIME::Attrs type => \"text/plain\",\ncharset => ...,\ndisposition => ..., ... ;\n\nWe could even make it a superclass of MIME::Head: that way, MIME::Head would have to\nimplement its interface, *and* allow itself to be initialized from a MIME::Attrs object.\n\nHowever, when you read RFC 2045, you begin to see how much MIME information is organized by\nits presence in particular fields. I imagine that we'd begin to mirror the structure of RFC\n2045 fields and subfields to such a degree that this might not give us a tremendous gain\nover just having MIME::Head.\n\nWhy all this \"occurrence\" and \"index\" jazz? Isn't every field unique?\nAaaaaaaaaahh....no.\n\nLooking at a typical mail message header, it is sooooooo tempting to just store the fields\nas a hash of strings, one string per hash entry. Unfortunately, there's the little matter of\nthe \"Received:\" field, which (unlike \"From:\", \"To:\", etc.) will often have multiple\noccurrences; e.g.:\n\nReceived: from gsfc.nasa.gov by eryq.pr.mcs.net  with smtp\n(Linux Smail3.1.28.1 #5) id m0tStZ7-0007X4C;\nThu, 21 Dec 95 16:34 CST\nReceived: from rhine.gsfc.nasa.gov by gsfc.nasa.gov\n(5.65/Ultrix3.0-C) id AA13596;\nThu, 21 Dec 95 17:20:38 -0500\nReceived: (from eryq@localhost) by rhine.gsfc.nasa.gov\n(8.6.12/8.6.12) id RAA28069;\nThu, 21 Dec 1995 17:27:54 -0500\nDate: Thu, 21 Dec 1995 17:27:54 -0500\nFrom: Eryq <eryq@rhine.gsfc.nasa.gov>\nMessage-Id: <199512212227.RAA28069@rhine.gsfc.nasa.gov>\nTo: eryq@eryq.pr.mcs.net\nSubject: Stuff and things\n\nThe \"Received:\" field is used for tracing message routes, and although it's not generally\nused for anything other than human debugging, I didn't want to inconvenience anyone who\nactually wanted to get at that information.\n\nI also didn't want to make this a special case; after all, who knows what other fields could\nhave multiple occurrences in the future? So, clearly, multiple entries had to somehow be\nstored multiple times... and the different occurrences had to be retrievable.\n",
                "subsections": []
            },
            "SEE ALSO": {
                "content": "Mail::Header, Mail::Field, MIME::Words, MIME::Tools\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\nThe more-comprehensive filename extraction is courtesy of Lee E. Brotzman, Advanced Data\nSolutions.\n",
                "subsections": []
            }
        }
    }
}