The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.
<HTML>
<HEAD>
  <TITLE>MIME::Parser</TITLE>
</HEAD>
<BODY 
       bgcolor="#FFFFFF" link="#CC3366" vlink="#993366" alink="#FF6666">
<FONT FACE="sans-serif" SIZE=-1><A HREF="http://www.zeegee.com" TARGET="_top"><IMG SRC="icons/zeegee.gif" ALT="ZeeGee Software" ALIGN="RIGHT" BORDER="0"></A><A NAME="__TOP__"><H1>MIME::Parser</H1>
</A>
<P><B>This module is <FONT COLOR="#990000">BETA</FONT> code, which means that the interfaces are fairly stable BUT it has not been out in the community long enough to guarantee much testing. Use with caution! Please report any errors back to <A HREF="mailto:eryq@zeegee.com">eryq@zeegee.com</A> as soon as you can.</B><UL>
<LI> <A HREF="#NAME">NAME</A>
<LI> <A HREF="#SYNOPSIS">SYNOPSIS</A>
<UL>
<LI> <A HREF="#Basic_usage_examples">Basic usage examples</A>
<LI> <A HREF="#Examples_of_input">Examples of input</A>
<LI> <A HREF="#Examples_of_output_control">Examples of output control</A>
<LI> <A HREF="#Examples_of_error_recovery">Examples of error recovery</A>
<LI> <A HREF="#Examples_of_parser_options">Examples of parser options</A>
<LI> <A HREF="#Miscellaneous_examples">Miscellaneous examples</A>
</UL>
<LI> <A HREF="#DESCRIPTION">DESCRIPTION</A>
<LI> <A HREF="#PUBLIC_INTERFACE">PUBLIC INTERFACE</A>
<UL>
<LI> <A HREF="#Construction">Construction</A>
<LI> <A HREF="#Altering_how_messages_are_parsed">Altering how messages are parsed</A>
<LI> <A HREF="#Parsing_an_input_source">Parsing an input source</A>
<LI> <A HREF="#Specifying_output_destination">Specifying output destination</A>
<LI> <A HREF="#Specifying_classes_to_be_instantiated">Specifying classes to be instantiated</A>
<LI> <A HREF="#Parse_results_and_error_recovery">Parse results and error recovery</A>
</UL>
<LI> <A HREF="#OPTIMIZING_YOUR_PARSER">OPTIMIZING YOUR PARSER</A>
<UL>
<LI> <A HREF="#Maximizing_speed">Maximizing speed</A>
<LI> <A HREF="#Minimizing_memory">Minimizing memory</A>
<LI> <A HREF="#Maximizing_tolerance_of_bad_MIME">Maximizing tolerance of bad MIME</A>
<LI> <A HREF="#Avoiding_disk-based_temporary_files">Avoiding disk-based temporary files</A>
</UL>
<LI> <A HREF="#WARNINGS">WARNINGS</A>
<LI> <A HREF="#AUTHOR">AUTHOR</A>
<LI> <A HREF="#VERSION">VERSION</A>
</UL>
</A>

<P><HR>
<A NAME="NAME"><H2><A HREF="#__TOP__"><IMG SRC="icons/h1bullet.gif" ALT="Top" BORDER="0"></A> NAME</H2></A>


<P>MIME::Parser - experimental class for parsing MIME streams



<P><HR>
<A NAME="SYNOPSIS"><H2><A HREF="#__TOP__"><IMG SRC="icons/h1bullet.gif" ALT="Top" BORDER="0"></A> SYNOPSIS</H2></A>


<P>Before reading further, you should see <A HREF="../MIME/Tools.pm.html">MIME::Tools</A> to make sure that 
you understand where this module fits into the grand scheme of things.
Go on, do it now.  I'll wait.


<P>Ready?  Ok...



<P><HR>
<A NAME="Basic_usage_examples"><H3><A HREF="#__TOP__"><IMG SRC="icons/h2bullet.gif" ALT="Top" BORDER="0"></A> Basic usage examples</H3></A>

<FONT SIZE=3 FACE="courier"><PRE>
    ### Create a new parser object:
    my $parser = new MIME::Parser;
     
    ### Tell it where to put things:
    $parser-&gt;output_under(&quot;/tmp&quot;);
     
    ### Parse an input filehandle:
    $entity = $parser-&gt;parse(\*STDIN);
    
    ### Congratulations: you now have a (possibly multipart) MIME entity!
    $entity-&gt;dump_skeleton;          # for debugging 
</PRE></FONT>


<P><HR>
<A NAME="Examples_of_input"><H3><A HREF="#__TOP__"><IMG SRC="icons/h2bullet.gif" ALT="Top" BORDER="0"></A> Examples of input</H3></A>

<FONT SIZE=3 FACE="courier"><PRE>
    ### Parse from filehandles:
    $entity = $parser-&gt;parse(\*STDIN);
    $entity = $parser-&gt;parse(IO::File-&gt;new(&quot;some command|&quot;);
	  
    ### Parse from any object that supports getline() and read():
    $entity = $parser-&gt;parse($myHandle);
     
    ### Parse an in-core MIME message:
    $entity = $parser-&gt;parse_data($message);
         
    ### Parse an MIME message in a file:
    $entity = $parser-&gt;parse_open(&quot;/some/file.msg&quot;);
    
    ### Parse an MIME message out of a pipeline:
    $entity = $parser-&gt;parse_open(&quot;gunzip - &lt; file.msg.gz |&quot;);
      
    ### Parse already-split input (as &quot;deliver&quot; would give it to you):
    $entity = $parser-&gt;parse_two(&quot;msg.head&quot;, &quot;msg.body&quot;);
</PRE></FONT>


<P><HR>
<A NAME="Examples_of_output_control"><H3><A HREF="#__TOP__"><IMG SRC="icons/h2bullet.gif" ALT="Top" BORDER="0"></A> Examples of output control</H3></A>

<FONT SIZE=3 FACE="courier"><PRE>
    ### Keep parsed message bodies in core (default outputs to disk):
    $parser-&gt;output_to_core(1);
     
    ### Output each message body to a one-per-message directory:
    $parser-&gt;output_under(&quot;/tmp&quot;);
     
    ### Output each message body to the same directory:
    $parser-&gt;output_dir(&quot;/tmp&quot;);
    
    ### Change how nameless message-component files are named:
    $parser-&gt;output_prefix(&quot;msg&quot;);
</PRE></FONT>


<P><HR>
<A NAME="Examples_of_error_recovery"><H3><A HREF="#__TOP__"><IMG SRC="icons/h2bullet.gif" ALT="Top" BORDER="0"></A> Examples of error recovery</H3></A>

<FONT SIZE=3 FACE="courier"><PRE>
    ### Normal mechanism:
    eval { $entity = $parser-&gt;parse(\*STDIN) };
    if ($@) {
	$results  = $parser-&gt;results;
	$decapitated = $parser-&gt;last_head;  ### get last top-level head
    }
    
    ### Ultra-tolerant mechanism:
    $parser-&gt;ignore_errors(1);
    $entity = eval { $parser-&gt;parse(\*STDIN) };
    $error = ($@ || $parser-&gt;last_error);
    
    ### Cleanup all files created by the parse:
    eval { $entity = $parser-&gt;parse(\*STDIN) };
    ...
    $parser-&gt;filer-&gt;purge;
</PRE></FONT>


<P><HR>
<A NAME="Examples_of_parser_options"><H3><A HREF="#__TOP__"><IMG SRC="icons/h2bullet.gif" ALT="Top" BORDER="0"></A> Examples of parser options</H3></A>

<FONT SIZE=3 FACE="courier"><PRE>
    ### Automatically attempt to RFC-1522-decode the MIME headers?
    $parser-&gt;decode_headers(1);             ### default is false
          
    ### Parse contained &quot;message/rfc822&quot; objects as nested MIME streams?
    $parser-&gt;extract_nested_messages(0);    ### default is true 
     
    ### Look for uuencode in &quot;text&quot; messages, and extract it?
    $parser-&gt;extract_uuencode(1);           ### default is false
          
    ### Should we forgive normally-fatal errors?
    $parser-&gt;ignore_errors(0);              ### default is true 
</PRE></FONT>


<P><HR>
<A NAME="Miscellaneous_examples"><H3><A HREF="#__TOP__"><IMG SRC="icons/h2bullet.gif" ALT="Top" BORDER="0"></A> Miscellaneous examples</H3></A>

<FONT SIZE=3 FACE="courier"><PRE>
    ### Convert a Mail::Internet object to a MIME::Entity:
    @lines = (@{$mail-&gt;header}, &quot;\n&quot;, @{$mail-&gt;body});
    $entity = $parser-&gt;parse_data(\@lines);
</PRE></FONT>


<P><HR>
<A NAME="DESCRIPTION"><H2><A HREF="#__TOP__"><IMG SRC="icons/h1bullet.gif" ALT="Top" BORDER="0"></A> DESCRIPTION</H2></A>


<P>You can inherit from this class to create your own subclasses 
that parse MIME streams into MIME::Entity objects.



<P><HR>
<A NAME="PUBLIC_INTERFACE"><H2><A HREF="#__TOP__"><IMG SRC="icons/h1bullet.gif" ALT="Top" BORDER="0"></A> PUBLIC INTERFACE</H2></A>



<P><HR>
<A NAME="Construction"><H3><A HREF="#__TOP__"><IMG SRC="icons/h2bullet.gif" ALT="Top" BORDER="0"></A> Construction</H3></A>



<DL>
<P><DT><B><A NAME="item:new">new ARGS...</A></B></DT>
<DD>
<I>Class method.</I>
Create a new parser object.  
Once you do this, you can then set up various parameters
before doing the actual parsing.  For example:

<FONT SIZE=3 FACE="courier"><PRE>
    my $parser = new MIME::Parser;
    $parser-&gt;output_dir(&quot;/tmp&quot;);
    $parser-&gt;output_prefix(&quot;msg1&quot;);
    my $entity = $parser-&gt;parse(\*STDIN);
</PRE></FONT>

<P>Any arguments are passed into <CODE>init()</CODE>.
Don't override this in your subclasses; override init() instead.

<P><DT><B><A NAME="item:init">init ARGS...</A></B></DT>
<DD>
<I>Instance method.</I>
Initiallize a new MIME::Parser object.  
This is automatically sent to a new object; you may want to override it.
If you override this, be sure to invoke the inherited method.

<P><DT><B><A NAME="item:init_parse">init_parse</A></B></DT>
<DD>
<I>Instance method.</I>
Invoked automatically whenever one of the top-level parse() methods
is called, to reset the parser to a &quot;ready&quot; state.

</DL>



<P><HR>
<A NAME="Altering_how_messages_are_parsed"><H3><A HREF="#__TOP__"><IMG SRC="icons/h2bullet.gif" ALT="Top" BORDER="0"></A> Altering how messages are parsed</H3></A>



<DL>
<P><DT><B><A NAME="item:decode_headers">decode_headers [YESNO]</A></B></DT>
<DD>
<I>Instance method.</I>
Controls whether the parser will attempt to decode all the MIME headers
(as per RFC-1522) the moment it sees them.  <B>This is not advisable
for two very important reasons:</B>



<UL>
<P><LI>
<P><B>It screws up the extraction of information from MIME fields.</B>
If you fully decode the headers into bytes, you can inadvertently 
transform a parseable MIME header like this:

<FONT SIZE=3 FACE="courier"><PRE>
    Content-type: text/plain; filename=&quot;=?ISO-8859-1?Q?Hi=22Ho?=&quot; 
</PRE></FONT>

<P>into unparseable gobbledygook; in this case:

<FONT SIZE=3 FACE="courier"><PRE>
    Content-type: text/plain; filename=&quot;Hi&quot;Ho&quot;
</PRE></FONT>
<P><LI>
<P><B>It is information-lossy.</B>  An encoded string which contains
both Latin-1 and Cyrillic characters will be turned into a binary
mishmosh which simply can't be rendered.

</UL>


<P><B>History.</B>
This method was once the only out-of-the-box way to deal with attachments
whose filenames had non-ASCII characters.  However, since MIME-tools 5.4xx 
this is no longer necessary.


<P><B>Parameters.</B>
If YESNO is true, decoding is done.  However, you will get a warning 
unless you use one of the special &quot;true&quot; values:

<FONT SIZE=3 FACE="courier"><PRE>
   &quot;I_NEED_TO_FIX_THIS&quot;
          Just shut up and do it.  Not recommended.
          Provided only for those who need to keep old scripts functioning.
</PRE></FONT>
<FONT SIZE=3 FACE="courier"><PRE>
   &quot;I_KNOW_WHAT_I_AM_DOING&quot;
          Just shut up and do it.  Not recommended.
          Provided for those who REALLY know what they are doing.
</PRE></FONT>

<P>If YESNO is false (the default), no attempt at decoding will be done.
With no argument, just returns the current setting.
<B>Remember:</B> you can always decode the headers <I>after</I> the parsing
has completed (see <A HREF="../MIME/Head.pm.html#item:decode">MIME::Head::decode()</A>), or
decode the words on demand (see <A HREF="../MIME/Words.pm.html">MIME::Words</A>).

<P><DT><B><A NAME="item:extract_nested_messages">extract_nested_messages OPTION</A></B></DT>
<DD>
<I>Instance method.</I>
Some MIME messages will contain a part of type <CODE>message/rfc822</CODE>:
literally, the text of an embedded mail/news/whatever message.  
This option controls whether (and how) we parse that embedded message.


<P>If the OPTION is false, we treat such a message just as if it were a 
<CODE>text/plain</CODE> document, without attempting to decode its contents.  


<P>If the OPTION is true (the default), the body of the <CODE>message/rfc822</CODE> 
part is parsed by this parser, creating an entity object.  
What happens then is determined by the actual OPTION:



<DL>
<P><DT><B><A NAME="item:NEST_or_1">NEST or 1</A></B></DT>
<DD>
The default setting.
The contained message becomes the sole &quot;part&quot; of the <CODE>message/rfc822</CODE> 
entity (as if the containing message were a special kind of
&quot;multipart&quot; message).  
You can recover the sub-entity by invoking the <A HREF="../MIME/Entity.pm.html#item:parts">parts()</A> 
method on the <CODE>message/rfc822</CODE> entity.

<P><DT><B><A NAME="item:REPLACE">REPLACE</A></B></DT>
<DD>
The contained message replaces the <CODE>message/rfc822</CODE> entity, as though
the <CODE>message/rfc822</CODE> &quot;container&quot; never existed.  


<P><B>Warning:</B> notice that, with this option, all the header information 
in the <CODE>message/rfc822</CODE> header is lost.  This might seriously bother
you if you're dealing with a top-level message, and you've just lost
the sender's address and the subject line.  <CODE>:-/</CODE>.

</DL>


<P><I>Thanks to Andreas Koenig for suggesting this method.</I>

<P><DT><B><A NAME="item:extract_uuencode">extract_uuencode [YESNO]</A></B></DT>
<DD>
<I>Instance method.</I>
If set true, then whenever we are confronted with a message
whose effective content-type is &quot;text/plain&quot; and whose encoding
is 7bit/8bit/binary, we scan the encoded body to see if it contains
uuencoded data (generally given away by a &quot;begin XXX&quot; line). 


<P>If it does, we explode the uuencoded message into a multipart, 
where the text before the first &quot;begin XXX&quot; becomes the first part,
and all &quot;begin...end&quot; sections following become the subsequent parts. 
The filename (if given) is accessible through the normal means.

<P><DT><B><A NAME="item:ignore_errors">ignore_errors [YESNO]</A></B></DT>
<DD>
<I>Instance method.</I>
Controls whether the parser will attempt to ignore normally-fatal
errors, treating them as warnings and continuing with the parse.


<P>If YESNO is true (the default), many syntax errors are tolerated.
If YESNO is false, fatal errors throw exceptions.
With no argument, just returns the current setting.

</DL>



<P><HR>
<A NAME="Parsing_an_input_source"><H3><A HREF="#__TOP__"><IMG SRC="icons/h2bullet.gif" ALT="Top" BORDER="0"></A> Parsing an input source</H3></A>



<DL>
<P><DT><B><A NAME="item:parse_data">parse_data DATA</A></B></DT>
<DD>
<I>Instance method.</I>
Parse a MIME message that's already in core.  
You may supply the DATA in any of a number of ways...



<UL>
<P><LI>
<P><B>A scalar</B> which holds the message.

<P><LI>
<P><B>A ref to a scalar</B> which holds the message.  This is an efficiency hack.

<P><LI>
<P><B>A ref to an array of scalars.</B>  They are treated as a stream
which (conceptually) consists of simply concatenating the scalars.

</UL>


<P>Returns the parsed MIME::Entity on success.  
Throws exception on failure.

<P><DT><B><A NAME="item:parse">parse INSTREAM</A></B></DT>
<DD>
<I>Instance method.</I>
Takes a MIME-stream and splits it into its component entities.


<P>The INSTREAM can be given as a readable FileHandle, an IO::File,
a globref filehandle (like <CODE>\*STDIN</CODE>),
or as <I>any</I> blessed object conforming to the IO:: interface
(which minimally implements getline() and read()).


<P>Returns the parsed MIME::Entity on success.  
Throws exception on failure.

<P><DT><B><A NAME="item:parse_open">parse_open EXPR</A></B></DT>
<DD>
<I>Instance method.</I>
Convenience front-end onto <CODE>parse()</CODE>.
Simply give this method any expression that may be sent as the second
argument to open() to open a filehandle for reading. 


<P>Returns the parsed MIME::Entity on success.  
Throws exception on failure.

<P><DT><B><A NAME="item:parse_two">parse_two HEADFILE, BODYFILE</A></B></DT>
<DD>
<I>Instance method.</I>
Convenience front-end onto <CODE>parse_open()</CODE>, intended for programs 
running under mail-handlers like <B>deliver</B>, which splits the incoming
mail message into a header file and a body file.
Simply give this method the paths to the respective files.  


<P><B>Warning:</B> it is assumed that, once the files are cat'ed together,
there will be a blank line separating the head part and the body part.


<P><B>Warning:</B> new implementation slurps files into line array
for portability, instead of using 'cat'.  May be an issue if 
your messages are large.


<P>Returns the parsed MIME::Entity on success.  
Throws exception on failure.

</DL>



<P><HR>
<A NAME="Specifying_output_destination"><H3><A HREF="#__TOP__"><IMG SRC="icons/h2bullet.gif" ALT="Top" BORDER="0"></A> Specifying output destination</H3></A>


<P><B>Warning:</B> in 5.212 and before, this was done by methods 
of MIME::Parser.  However, since many users have requested 
fine-tuned control over how this is done, the logic has been split
off from the parser into its own class, MIME::Parser::Filer
Every MIME::Parser maintains an instance of a MIME::Parser::Filer 
subclass to manage disk output (see <A HREF="../MIME/Parser/Filer.pm.html">MIME::Parser::Filer</A> for details.)


<P>The benefit to this is that the MIME::Parser code won't be 
confounded with a lot of garbage related to disk output.
The drawback is that the way you override the default behavior 
will change.


<P>For now, all the normal public-interface methods are still provided, 
but many are only stubs which create or delegate to the underlying 
MIME::Parser::Filer object.



<DL>
<P><DT><B><A NAME="item:filer">filer [FILER]</A></B></DT>
<DD>
<I>Instance method.</I>
Get/set the FILER object used to manage the output of files to disk.
This will be some subclass of <A HREF="../MIME/Parser/Filer.pm.html">MIME::Parser::Filer</A>.

<P><DT><B><A NAME="item:output_dir">output_dir DIRECTORY</A></B></DT>
<DD>
<I>Instance method.</I>
Causes messages to be filed directly into the given DIRECTORY.  
It does this by setting the underlying <A HREF="#item:filer">filer()</A> to 
a new instance of MIME::Parser::FileInto, and passing the arguments 
into that class' new() method.


<P><B>Note:</B> Since this method replaces the underlying
filer, you must invoke it <I>before</I> doing changing any attributes
of the filer, like the output prefix; otherwise those changes
will be lost.

<P><DT><B><A NAME="item:output_under">output_under BASEDIR, OPTS...</A></B></DT>
<DD>
<I>Instance method.</I>
Causes messages to be filed directly into subdirectories of the given
BASEDIR, one subdirectory per message.  It does this by setting the 
underlying <A HREF="#item:filer">filer()</A> to a new instance of MIME::Parser::FileUnder,
and passing the arguments into that class' new() method.


<P><B>Note:</B> Since this method replaces the underlying
filer, you must invoke it <I>before</I> doing changing any attributes
of the filer, like the output prefix; otherwise those changes
will be lost.

<P><DT><B><A NAME="item:output_path">output_path HEAD</A></B></DT>
<DD>
<I>Instance method, DEPRECATED.</I>
Given a MIME head for a file to be extracted, come up with a good
output pathname for the extracted file.
Identical to the preferred form:
 
     $parser-&gt;filer-&gt;output_path(...args...);


<P>We just delegate this to the underlying <A HREF="#item:filer">filer()</A> object.

<P><DT><B><A NAME="item:output_prefix">output_prefix [PREFIX]</A></B></DT>
<DD>
<I>Instance method, DEPRECATED.</I>
Get/set the short string that all filenames for extracted body-parts 
will begin with (assuming that there is no better &quot;recommended filename&quot;).  
Identical to the preferred form:
 
     $parser-&gt;filer-&gt;output_prefix(...args...);


<P>We just delegate this to the underlying <A HREF="#item:filer">filer()</A> object.

<P><DT><B><A NAME="item:evil_filename">evil_filename NAME</A></B></DT>
<DD>
<I>Instance method, DEPRECATED.</I>
Identical to the preferred form:
 
     $parser-&gt;filer-&gt;evil_filename(...args...);


<P>We just delegate this to the underlying <A HREF="#item:filer">filer()</A> object.

<P><DT><B><A NAME="item:output_to_core">output_to_core YESNO</A></B></DT>
<DD>
<I>Instance method.</I>
Normally, instances of this class output all their decoded body
data to disk files (via MIME::Body::File).  However, you can change 
this behaviour by invoking this method before parsing:


<P>If YESNO is false (the default), then all body data goes 
to disk files.


<P>If YESNO is true, then all body data goes to in-core data structures
This is a little risky (what if someone emails you an MPEG or a tar 
file, hmmm?) but people seem to want this bit of noose-shaped rope,
so I'm providing it.  
Note that setting this attribute true <I>does not</I> mean that parser-internal
temporary files are avoided!  Use <A HREF="#item:tmp_to_core">tmp_to_core()</A> for that.


<P>With no argument, returns the current setting as a boolean.

<P><DT><B><A NAME="item:tmp_recycling">tmp_recycling [YESNO]</A></B></DT>
<DD>
<I>Instance method.</I>
Normally, tmpfiles are created when needed during parsing, and
destroyed automatically when they go out of scope.  But for efficiency,
you might prefer for your parser to attempt to rewind and reuse the 
same file until the parser itself is destroyed.


<P>If YESNO is true (the default), we allow recycling; 
tmpfiles persist until the parser itself is destroyed.
If YESNO is false, we do not allow recycling; 
tmpfiles persist only as long as they are needed during the parse.
With no argument, just returns the current setting.

<P><DT><B><A NAME="item:tmp_to_core">tmp_to_core [YESNO]</A></B></DT>
<DD>
<I>Instance method.</I>
Should <A HREF="#item:new_tmpfile">new_tmpfile()</A> create real temp files, or 
use fake in-core ones?  Normally we allow the creation of temporary 
disk files, since this allows us to handle huge attachments even when 
core is limited.


<P>If YESNO is true, we implement new_tmpfile() via in-core handles.
If YESNO is false (the default), we use real tmpfiles.
With no argument, just returns the current setting.

<P><DT><B><A NAME="item:use_inner_files">use_inner_files [YESNO]</A></B></DT>
<DD>
<I>Instance method.</I>
If you are parsing from a handle which supports seek() and tell(), 
then we can avoid tmpfiles completely by using IO::InnerFile, if so 
desired: basically, we simulate a temporary file via pointers
to virtual start- and end-positions in the input stream.


<P>If YESNO is false (the default), then we will not use IO::InnerFile.
If YESNO is true, we use IO::InnerFile if we can. 
With no argument, just returns the current setting.


<P><B>Note:</B> inner files are slower than <I>real</I> tmpfiles,
but possibly faster than <I>in-core</I> tmpfiles... so your choice for
this option will probably depend on your choice for 
<A HREF="#item:tmp_to_core">tmp_to_core()</A> and the kind of input streams you are 
parsing.

</DL>



<P><HR>
<A NAME="Specifying_classes_to_be_instantiated"><H3><A HREF="#__TOP__"><IMG SRC="icons/h2bullet.gif" ALT="Top" BORDER="0"></A> Specifying classes to be instantiated</H3></A>



<DL>
<P><DT><B><A NAME="item:interface">interface ROLE,[VALUE]</A></B></DT>
<DD>
<I>Instance method.</I>
During parsing, the parser normally creates instances of certain classes, 
like MIME::Entity.  However, you may want to create a parser subclass
that uses your own experimental head, entity, etc. classes (for example,
your &quot;head&quot; class may provide some additional MIME-field-oriented methods).


<P>If so, then this is the method that your subclass should invoke during 
init.  Use it like this:

<FONT SIZE=3 FACE="courier"><PRE>
    package MyParser;
    @ISA = qw(MIME::Parser);
    ...
    sub init {
	my $self = shift;
	$self-&gt;SUPER::init(@_);        ### do my parent's init
        $self-&gt;interface(ENTITY_CLASS =&gt; 'MIME::MyEntity');
	$self-&gt;interface(HEAD_CLASS   =&gt; 'MIME::MyHead');
	$self;                         ### return
    }
</PRE></FONT>

<P>With no VALUE, returns the VALUE currently associated with that ROLE.

<P><DT><B><A NAME="item:new_body_for">new_body_for HEAD</A></B></DT>
<DD>
<I>Instance method.</I>
Based on the HEAD of a part we are parsing, return a new
body object (any desirable subclass of MIME::Body) for
receiving that part's data.


<P>If you set the <CODE>output_to_core</CODE> option to false before parsing
(the default), then we call <CODE>output_path()</CODE> and create a
new MIME::Body::File on that filename.


<P>If you set the <CODE>output_to_core</CODE> option to true before parsing, 
then you get a MIME::Body::InCore instead.


<P>If you want the parser to do something else entirely, you can
override this method in a subclass.

<P><DT><B><A NAME="item:new_tmpfile">new_tmpfile [RECYCLE]</A></B></DT>
<DD>
<I>Instance method.</I>
Return an IO handle to be used to hold temporary data during a parse.
The default uses the standard IO::File-&gt;new_tmpfile() method unless
<A HREF="#item:tmp_to_core">tmp_to_core()</A> dictates otherwise, but you can override this.  
You shouldn't need to.


<P>If you do override this, make certain that the object you return is 
set for binmode(), and is able to handle the following methods:

<FONT SIZE=3 FACE="courier"><PRE>
    read(BUF, NBYTES)
    getline()
    getlines()
    print(@ARGS)
    flush() 
    seek(0, 0)
</PRE></FONT>

<P>Fatal exception if the stream could not be established.


<P>If RECYCLE is given, it is an object returned by a previous invocation 
of this method; to recycle it, this method must effectively rewind and 
truncate it, and return the same object.  If you don't want to support
recycling, just ignore it and always return a new object.

</DL>



<P><HR>
<A NAME="Parse_results_and_error_recovery"><H3><A HREF="#__TOP__"><IMG SRC="icons/h2bullet.gif" ALT="Top" BORDER="0"></A> Parse results and error recovery</H3></A>



<DL>
<P><DT><B><A NAME="item:last_error">last_error</A></B></DT>
<DD>
<I>Instance method.</I>
Return the error (if any) that we ignored in the last parse.

<P><DT><B><A NAME="item:last_head">last_head</A></B></DT>
<DD>
<I>Instance method.</I>
Return the top-level MIME header of the last stream we attempted to parse.
This is useful for replying to people who sent us bad MIME messages.

<FONT SIZE=3 FACE="courier"><PRE>
    ### Parse an input stream:
    eval { $entity = $parser-&gt;parse(\*STDIN) };
    if (!$entity) {    ### parse failed!
	my $decapitated = $parser-&gt;last_head;  
	...
    }
</PRE></FONT>
<P><DT><B><A NAME="item:results">results</A></B></DT>
<DD>
<I>Instance method.</I>
Return an object containing lots of info from the last entity parsed.
This will be an instance of class 
<A HREF="../MIME/Parser/Results.pm.html">MIME::Parser::Results</A>.

</DL>



<P><HR>
<A NAME="OPTIMIZING_YOUR_PARSER"><H2><A HREF="#__TOP__"><IMG SRC="icons/h1bullet.gif" ALT="Top" BORDER="0"></A> OPTIMIZING YOUR PARSER</H2></A>



<P><HR>
<A NAME="Maximizing_speed"><H3><A HREF="#__TOP__"><IMG SRC="icons/h2bullet.gif" ALT="Top" BORDER="0"></A> Maximizing speed</H3></A>


<P>Optimum input mechanisms:

<FONT SIZE=3 FACE="courier"><PRE>
    parse()                    YES (if you give it a globref or a 
				    subclass of IO::File)
    parse_open()               YES
    parse_data()               NO  (see below)
    parse_two()                NO  (see below)
</PRE></FONT>

<P>Optimum settings:

<FONT SIZE=3 FACE="courier"><PRE>
    decode_headers()           *** (no real difference; 0 is slightly faster)
    extract_nested_messages()  0   (may be slightly faster, but in 
                                    general you want it set to 1)
    output_to_core()           0   (will be MUCH faster)
    tmp_recycling()            1?  (probably, but should be investigated)
    tmp_to_core()              0   (will be MUCH faster)
    use_inner_files()          0   (if tmp_to_core() is 0; 
				    use 1 otherwise)
</PRE></FONT>

<P><B>File I/O is much faster than in-core I/O.</B>
Although it <I>seems</I> like slurping a message into core and
processing it in-core should be faster... it isn't.
Reason: Perl's filehandle-based I/O translates directly into 
native operating-system calls, whereas the in-core I/O is 
implemented in Perl.


<P><B>Inner files are slower than real tmpfiles, but faster than in-core ones.</B>
If speed is your concern, that's why
you should set use_inner_files(true) if you set tmp_to_core(true):
so that we can bypass the slow in-core tmpfiles if the input stream 
permits.


<P><B>Native I/O is much faster than object-oriented I/O.</B>
It's much faster to use &lt;$foo&gt; than $foo-&gt;getline.
For backwards compatibilty, this module must continue to use 
object-oriented I/O in most places, but if you use <A HREF="#item:parse">parse()</A> 
with a &quot;real&quot; filehandle (string, globref, or subclass of IO::File)
then MIME::Parser is able to perform some crucial optimizations.  


<P><B>The parse_two() call is very inefficient.</B>
Currently this is just a front-end onto parse_data().
If your OS supports it, you're <I>far</I> better off doing something like:

<FONT SIZE=3 FACE="courier"><PRE>
    $parser-&gt;parse_open(&quot;/bin/cat msg.head msg.body |&quot;);
</PRE></FONT>


<P><HR>
<A NAME="Minimizing_memory"><H3><A HREF="#__TOP__"><IMG SRC="icons/h2bullet.gif" ALT="Top" BORDER="0"></A> Minimizing memory</H3></A>


<P>Optimum input mechanisms:

<FONT SIZE=3 FACE="courier"><PRE>
    parse()                    YES
    parse_open()               YES
    parse_data()               NO  (in-core I/O will burn core)
    parse_two()                NO  (in-core I/O will burn core)
</PRE></FONT>

<P>Optimum settings:

<FONT SIZE=3 FACE="courier"><PRE>
    decode_headers()           *** (no real difference)
    extract_nested_messages()  *** (no real difference)
    output_to_core()           0   (will use MUCH less memory)
    tmp_recycling()            0?  (promotes faster GC if 
                                    tmp_to_core is 1)
    tmp_to_core()              0   (will use MUCH less memory)
    use_inner_files()          *** (no real difference, but set it to 1 
				    if you *must* have tmp_to_core set to 1,
				    so that you avoid in-core tmpfiles)
</PRE></FONT>


<P><HR>
<A NAME="Maximizing_tolerance_of_bad_MIME"><H3><A HREF="#__TOP__"><IMG SRC="icons/h2bullet.gif" ALT="Top" BORDER="0"></A> Maximizing tolerance of bad MIME</H3></A>


<P>Optimum input mechanisms:

<FONT SIZE=3 FACE="courier"><PRE>
    parse()                    *** (doesn't matter)
    parse_open()               *** (doesn't matter)
    parse_data()               *** (doesn't matter)
    parse_two()                *** (doesn't matter)
</PRE></FONT>

<P>Optimum settings:

<FONT SIZE=3 FACE="courier"><PRE>
    decode_headers()           0   (sidesteps problem of bad hdr encodings)
    extract_nested_messages()  0   (sidesteps problems of bad nested messages,
                                    but often you want it set to 1 anyway).
    output_to_core()           *** (doesn't matter)
    tmp_recycling()            *** (doesn't matter)
    tmp_to_core()              *** (doesn't matter)
    use_inner_files()          *** (doesn't matter)
</PRE></FONT>


<P><HR>
<A NAME="Avoiding_disk-based_temporary_files"><H3><A HREF="#__TOP__"><IMG SRC="icons/h2bullet.gif" ALT="Top" BORDER="0"></A> Avoiding disk-based temporary files</H3></A>


<P>Optimum input mechanisms:

<FONT SIZE=3 FACE="courier"><PRE>
    parse()                    YES (if you give it a seekable handle)
    parse_open()               YES (becomes a seekable handle) 
    parse_data()               NO  (unless you set tmp_to_core(1))
    parse_two()                NO  (unless you set tmp_to_core(1))
</PRE></FONT>

<P>Optimum settings:

<FONT SIZE=3 FACE="courier"><PRE>
    decode_headers()           *** (doesn't matter)
    extract_nested_messages()  *** (doesn't matter)
    output_to_core()           *** (doesn't matter)
    tmp_recycling              1   (restricts created files to 1 per parser)
    tmp_to_core()              1 
    use_inner_files()          1
</PRE></FONT>

<P><B>If we can use them, inner files avoid most tmpfiles.</B>
If you parse from a seekable-and-tellable filehandle, then the internal 
process_to_bound() doesn't need to extract each part into a temporary 
buffer; it can use IO::InnerFile (<B>warning:</B> this will slow down 
the parsing of messages with large attachments).


<P><B>You can veto tmpfiles entirely.</B>
If you might not be parsing from a seekable-and-tellable filehandle,
you can set <A HREF="#item:tmp_to_core">tmp_to_core()</A> true: this will always 
use in-core I/O for the buffering (<B>warning:</B> this will slow down 
the parsing of messages with large attachments).  


<P><B>Final resort.</B>
You can always override <A HREF="#item:new_tmpfile">new_tmpfile()</A> in a subclass.



<P><HR>
<A NAME="WARNINGS"><H2><A HREF="#__TOP__"><IMG SRC="icons/h1bullet.gif" ALT="Top" BORDER="0"></A> WARNINGS</H2></A>



<DL>
<P><DT><B><A NAME="item:Multipart_messages_are_always_read_line-by-line">Multipart messages are always read line-by-line</A></B></DT>
<DD>
Multipart document parts are read line-by-line, so that the
encapsulation boundaries may easily be detected.  However, bad MIME
composition agents (for example, naive CGI scripts) might return
multipart documents where the parts are, say, unencoded bitmap
files... and, consequently, where such &quot;lines&quot; might be 
veeeeeeeeery long indeed.


<P>A better solution for this case would be to set up some form of 
state machine for input processing.  This will be left for future versions.

<P><DT><B><A NAME="item:Multipart_parts_read_into_temp_files_before_decoding">Multipart parts read into temp files before decoding</A></B></DT>
<DD>
In my original implementation, the MIME::Decoder classes had to be aware
of encapsulation boundaries in multipart MIME documents.
While this decode-while-parsing approach obviated the need for 
temporary files, it resulted in inflexible and complex decoder
implementations.


<P>The revised implementation uses a temporary file (a la <CODE>tmpfile()</CODE>)
during parsing to hold the <I>encoded</I> portion of the current MIME 
document or part.  This file is deleted automatically after the
current part is decoded and the data is written to the &quot;body stream&quot;
object; you'll never see it, and should never need to worry about it.


<P>Some folks have asked for the ability to bypass this temp-file
mechanism, I suppose because they assume it would slow down their application.
I considered accomodating this wish, but the temp-file
approach solves a lot of thorny problems in parsing, and it also
protects against hidden bugs in user applications (what if you've
directed the encoded part into a scalar, and someone unexpectedly
sends you a 6 MB tar file?).  Finally, I'm just not conviced that 
the temp-file use adds significant overhead.

<P><DT><B><A NAME="item:Fuzzing_of_CRLF_and_newline_on_input">Fuzzing of CRLF and newline on input</A></B></DT>
<DD>
RFC-1521 dictates that MIME streams have lines terminated by CRLF
(<CODE>&quot;\r\n&quot;</CODE>).  However, it is extremely likely that folks will want to 
parse MIME streams where each line ends in the local newline 
character <CODE>&quot;\n&quot;</CODE> instead. 


<P>An attempt has been made to allow the parser to handle both CRLF 
and newline-terminated input.

<P><DT><B><A NAME="item:Fuzzing_of_CRLF_and_newline_on_output">Fuzzing of CRLF and newline on output</A></B></DT>
<DD>
The <CODE>&quot;7bit&quot;</CODE> and <CODE>&quot;8bit&quot;</CODE> decoders will decode both
a <CODE>&quot;\n&quot;</CODE> and a <CODE>&quot;\r\n&quot;</CODE> end-of-line sequence into a <CODE>&quot;\n&quot;</CODE>.


<P>The <CODE>&quot;binary&quot;</CODE> decoder (default if no encoding specified) 
still outputs stuff verbatim... so a MIME message with CRLFs 
and no explicit encoding will be output as a text file 
that, on many systems, will have an annoying ^M at the end of
each line... <I>but this is as it should be</I>.

<P><DT><B><A NAME="item:Inability_to_handle_multipart_boundaries_that_contain_newlines">Inability to handle multipart boundaries that contain newlines</A></B></DT>
<DD>
First, let's get something straight: <I>this is an evil, EVIL practice,</I>
and is incompatible with RFC-1521... hence, it's not valid MIME.


<P>If your mailer creates multipart boundary strings that contain
newlines <I>when they appear in the message body,</I> give it two weeks notice 
and find another one.  If your mail robot receives MIME mail like this, 
regard it as syntactically incorrect MIME, which it is.


<P>Why do I say that?  Well, in RFC-1521, the syntax of a boundary is 
given quite clearly:

<FONT SIZE=3 FACE="courier"><PRE>
      boundary := 0*69&lt;bchars&gt; bcharsnospace
        
      bchars := bcharsnospace / &quot; &quot;
      
      bcharsnospace :=    DIGIT / ALPHA / &quot;'&quot; / &quot;(&quot; / &quot;)&quot; / &quot;+&quot; /&quot;_&quot;
                   / &quot;,&quot; / &quot;-&quot; / &quot;.&quot; / &quot;/&quot; / &quot;:&quot; / &quot;=&quot; / &quot;?&quot;
</PRE></FONT>

<P>All of which means that a valid boundary string <I>cannot</I> have 
newlines in it, and any newlines in such a string in the message header
are expected to be solely the result of <I>folding</I> the string (i.e.,
inserting to-be-removed newlines for readability and line-shortening 
<I>only</I>).


<P>Yet, there is at least one brain-damaged user agent out there 
that composes mail like this:

<FONT SIZE=3 FACE="courier"><PRE>
      MIME-Version: 1.0
      Content-type: multipart/mixed; boundary=&quot;----ABC-
       123----&quot;
      Subject: Hi... I'm a dork!
      
      This is a multipart MIME message (yeah, right...)
      
      ----ABC-
       123----
      
      Hi there! 
</PRE></FONT>

<P>We have <I>got</I> to discourage practices like this (and the recent file
upload idiocy where binary files that are part of a multipart MIME
message aren't base64-encoded) if we want MIME to stay relatively 
simple, and MIME parsers to be relatively robust. 


<P><I>Thanks to Andreas Koenig for bringing a baaaaaaaaad user agent to
my attention.</I>

</DL>



<P><HR>
<A NAME="AUTHOR"><H2><A HREF="#__TOP__"><IMG SRC="icons/h1bullet.gif" ALT="Top" BORDER="0"></A> AUTHOR</H2></A>


<P>Eryq (<I><FILE><A HREF="mailto:eryq@zeegee.com">eryq@zeegee.com</A></FILE></I>), ZeeGee Software Inc (<I><FILE><A HREF="http://www.zeegee.com">http://www.zeegee.com</A></FILE></I>).


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



<P><HR>
<A NAME="VERSION"><H2><A HREF="#__TOP__"><IMG SRC="icons/h1bullet.gif" ALT="Top" BORDER="0"></A> VERSION</H2></A>


<P>$Revision: 5.406 $ $Date: 2000/11/12 05:55:11 $

<P><HR>
<ADDRESS><FONT SIZE=-1>
Generated Wed Jan 17 01:58:24 2001 by cvu_pod2html
</FONT></ADDRESS>
</FONT></BODY>
</HTML>