home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / xampp / xampp-perl-addon-1.4.9-installer.exe / Entity.pm < prev    next >
Encoding:
Perl POD Document  |  2002-06-14  |  64.8 KB  |  2,243 lines

  1. package MIME::Entity;
  2.  
  3.  
  4. =head1 NAME
  5.  
  6. MIME::Entity - class for parsed-and-decoded MIME message
  7.  
  8.  
  9. =head1 SYNOPSIS
  10.  
  11. Before reading further, you should see L<MIME::Tools> to make sure that
  12. you understand where this module fits into the grand scheme of things.
  13. Go on, do it now.  I'll wait.
  14.  
  15. Ready?  Ok...
  16.  
  17.     ### Create an entity:
  18.     $top = MIME::Entity->build(From    => 'me@myhost.com',
  19.                                To      => 'you@yourhost.com',
  20.                                Subject => "Hello, nurse!",
  21.                    Data    => \@my_message);
  22.  
  23.     ### Attach stuff to it:
  24.     $top->attach(Path     => $gif_path,
  25.          Type     => "image/gif",
  26.          Encoding => "base64");
  27.  
  28.     ### Sign it:
  29.     $top->sign;
  30.  
  31.     ### Output it:
  32.     $top->print(\*STDOUT);
  33.  
  34.  
  35. =head1 DESCRIPTION
  36.  
  37. A subclass of B<Mail::Internet>.
  38.  
  39. This package provides a class for representing MIME message entities,
  40. as specified in RFC 1521, I<Multipurpose Internet Mail Extensions>.
  41.  
  42.  
  43. =head1 EXAMPLES
  44.  
  45. =head2 Construction examples
  46.  
  47. Create a document for an ordinary 7-bit ASCII text file (lots of
  48. stuff is defaulted for us):
  49.  
  50.     $ent = MIME::Entity->build(Path=>"english-msg.txt");
  51.  
  52. Create a document for a text file with 8-bit (Latin-1) characters:
  53.  
  54.     $ent = MIME::Entity->build(Path     =>"french-msg.txt",
  55.                                Encoding =>"quoted-printable",
  56.                                From     =>'jean.luc@inria.fr',
  57.                                Subject  =>"C'est bon!");
  58.  
  59. Create a document for a GIF file (the description is completely optional;
  60. note that we have to specify content-type and encoding since they're
  61. not the default values):
  62.  
  63.     $ent = MIME::Entity->build(Description => "A pretty picture",
  64.                                Path        => "./docs/mime-sm.gif",
  65.                                Type        => "image/gif",
  66.                                Encoding    => "base64");
  67.  
  68. Create a document that you already have the text for, using "Data":
  69.  
  70.     $ent = MIME::Entity->build(Type        => "text/plain",
  71.                                Encoding    => "quoted-printable",
  72.                                Data        => ["First line.\n",
  73.                                               "Second line.\n",
  74.                                               "Last line.\n"]);
  75.  
  76. Create a multipart message, with the entire structure given
  77. explicitly:
  78.  
  79.     ### Create the top-level, and set up the mail headers:
  80.     $top = MIME::Entity->build(Type     => "multipart/mixed",
  81.                                From     => 'me@myhost.com',
  82.                                To       => 'you@yourhost.com',
  83.                                Subject  => "Hello, nurse!");
  84.  
  85.     ### Attachment #1: a simple text document:
  86.     $top->attach(Path=>"./testin/short.txt");
  87.  
  88.     ### Attachment #2: a GIF file:
  89.     $top->attach(Path        => "./docs/mime-sm.gif",
  90.                  Type        => "image/gif",
  91.                  Encoding    => "base64");
  92.  
  93.     ### Attachment #3: text we'll create with text we have on-hand:
  94.     $top->attach(Data => $contents);
  95.  
  96. Suppose you don't know ahead of time that you'll have attachments?
  97. No problem: you can "attach" to singleparts as well:
  98.  
  99.     $top = MIME::Entity->build(From    => 'me@myhost.com',
  100.                    To      => 'you@yourhost.com',
  101.                    Subject => "Hello, nurse!",
  102.                    Data    => \@my_message);
  103.     if ($GIF_path) {
  104.     $top->attach(Path     => $GIF_path,
  105.                  Type     => 'image/gif');
  106.     }
  107.  
  108. Copy an entity (headers, parts... everything but external body data):
  109.  
  110.     my $deepcopy = $top->dup;
  111.  
  112.  
  113.  
  114. =head2 Access examples
  115.  
  116.     ### Get the head, a MIME::Head:
  117.     $head = $ent->head;
  118.  
  119.     ### Get the body, as a MIME::Body;
  120.     $bodyh = $ent->bodyhandle;
  121.  
  122.     ### Get the intended MIME type (as declared in the header):
  123.     $type = $ent->mime_type;
  124.  
  125.     ### Get the effective MIME type (in case decoding failed):
  126.     $eff_type = $ent->effective_type;
  127.  
  128.     ### Get preamble, parts, and epilogue:
  129.     $preamble   = $ent->preamble;          ### ref to array of lines
  130.     $num_parts  = $ent->parts;
  131.     $first_part = $ent->parts(0);          ### an entity
  132.     $epilogue   = $ent->epilogue;          ### ref to array of lines
  133.  
  134.  
  135. =head2 Manipulation examples
  136.  
  137. Muck about with the body data:
  138.  
  139.     ### Read the (unencoded) body data:
  140.     if ($io = $ent->open("r")) {
  141.     while (defined($_ = $io->getline)) { print $_ }
  142.     $io->close;
  143.     }
  144.  
  145.     ### Write the (unencoded) body data:
  146.     if ($io = $ent->open("w")) {
  147.     foreach (@lines) { $io->print($_) }
  148.     $io->close;
  149.     }
  150.  
  151.     ### Delete the files for any external (on-disk) data:
  152.     $ent->purge;
  153.  
  154. Muck about with the signature:
  155.  
  156.     ### Sign it (automatically removes any existing signature):
  157.     $top->sign(File=>"$ENV{HOME}/.signature");
  158.  
  159.     ### Remove any signature within 15 lines of the end:
  160.     $top->remove_sig(15);
  161.  
  162. Muck about with the headers:
  163.  
  164.     ### Compute content-lengths for singleparts based on bodies:
  165.     ###   (Do this right before you print!)
  166.     $entity->sync_headers(Length=>'COMPUTE');
  167.  
  168. Muck about with the structure:
  169.  
  170.     ### If a 0- or 1-part multipart, collapse to a singlepart:
  171.     $top->make_singlepart;
  172.  
  173.     ### If a singlepart, inflate to a multipart with 1 part:
  174.     $top->make_multipart;
  175.  
  176. Delete parts:
  177.  
  178.     ### Delete some parts of a multipart message:
  179.     my @keep = grep { keep_part($_) } $msg->parts;
  180.     $msg->parts(\@keep);
  181.  
  182.  
  183. =head2 Output examples
  184.  
  185. Print to filehandles:
  186.  
  187.     ### Print the entire message:
  188.     $top->print(\*STDOUT);
  189.  
  190.     ### Print just the header:
  191.     $top->print_header(\*STDOUT);
  192.  
  193.     ### Print just the (encoded) body... includes parts as well!
  194.     $top->print_body(\*STDOUT);
  195.  
  196. Stringify... note that C<stringify_xx> can also be written C<xx_as_string>;
  197. the methods are synonymous, and neither form will be deprecated:
  198.  
  199.     ### Stringify the entire message:
  200.     print $top->stringify;              ### or $top->as_string
  201.  
  202.     ### Stringify just the header:
  203.     print $top->stringify_header;       ### or $top->header_as_string
  204.  
  205.     ### Stringify just the (encoded) body... includes parts as well!
  206.     print $top->stringify_body;         ### or $top->body_as_string
  207.  
  208. Debug:
  209.  
  210.     ### Output debugging info:
  211.     $entity->dump_skeleton(\*STDERR);
  212.  
  213.  
  214.  
  215. =head1 PUBLIC INTERFACE
  216.  
  217. =cut
  218.  
  219. #------------------------------
  220.  
  221. ### Pragmas:
  222. use vars qw(@ISA $VERSION); 
  223. use strict;
  224.  
  225. ### System modules:
  226. use FileHandle;
  227. use Carp;
  228.  
  229. ### Other modules:
  230. use Mail::Internet 1.28 ();
  231. use Mail::Field    1.05 ();
  232.  
  233. ### Kit modules:
  234. use MIME::Tools qw(:config :msgs :utils);
  235. use MIME::Head;
  236. use MIME::Body;
  237. use MIME::Decoder;
  238. use IO::Scalar;
  239. use IO::Wrap;
  240. use IO::Lines;
  241.  
  242. @ISA = qw(Mail::Internet);
  243.  
  244.  
  245. #------------------------------
  246. #
  247. # Globals...
  248. #
  249. #------------------------------
  250.  
  251. ### The package version, both in 1.23 style *and* usable by MakeMaker:
  252. $VERSION = substr q$Revision: 5.404 $, 10;
  253.  
  254. ### Boundary counter:
  255. my $BCount = 0;
  256.  
  257. ### Standard "Content-" MIME fields, for scrub():
  258. my $StandardFields = 'Description|Disposition|Id|Type|Transfer-Encoding';
  259.  
  260. ### Known Mail/MIME fields... these, plus some general forms like 
  261. ### "x-*", are recognized by build():
  262. my %KnownField = map {$_=>1} 
  263. qw(
  264.    bcc         cc          comments      date          encrypted 
  265.    from        keywords    message-id    mime-version  organization
  266.    received    references  reply-to      return-path   sender        
  267.    subject     to
  268.    );
  269.  
  270. ### Fallback preamble and epilogue:
  271. my $DefPreamble = [ "This is a multi-part message in MIME format...\n" ];
  272. my $DefEpilogue = [ ];
  273.  
  274.  
  275. #==============================
  276. #
  277. # Utilities, private
  278. #
  279.  
  280. #------------------------------
  281. #
  282. # known_field FIELDNAME
  283. #
  284. # Is this a recognized Mail/MIME field?
  285. #
  286. sub known_field {
  287.     my $field = lc(shift);
  288.     $KnownField{$field} or ($field =~ m{^(content|resent|x)-.});
  289. }
  290.  
  291. #------------------------------
  292. #
  293. # make_boundary
  294. #
  295. # Return a unique boundary string.
  296. # This is used both internally and by MIME::ParserBase, but it is NOT in
  297. # the public interface!  Do not use it!
  298. #
  299. # We generate one containing a "=_", as RFC1521 suggests.
  300. #
  301. sub make_boundary {
  302.     return "----------=_".scalar(time)."-$$-".$BCount++;
  303. }
  304.  
  305.  
  306.  
  307.  
  308.  
  309.  
  310. #==============================
  311.  
  312. =head2 Construction
  313.  
  314. =over 4
  315.  
  316. =cut
  317.  
  318.  
  319. #------------------------------
  320.  
  321. =item new [SOURCE]
  322.  
  323. I<Class method.>
  324. Create a new, empty MIME entity.
  325. Basically, this uses the Mail::Internet constructor...
  326.  
  327. If SOURCE is an ARRAYREF, it is assumed to be an array of lines
  328. that will be used to create both the header and an in-core body.
  329.  
  330. Else, if SOURCE is defined, it is assumed to be a filehandle
  331. from which the header and in-core body is to be read.
  332.  
  333. B<Note:> in either case, the body will not be I<parsed:> merely read!
  334.  
  335. =cut
  336.  
  337. sub new {
  338.     my $class = shift;
  339.     my $self = $class->Mail::Internet::new(@_);   ### inherited
  340.     $self->{ME_Parts} = [];                       ### no parts extracted
  341.     $self;
  342. }
  343.  
  344.  
  345. ###------------------------------
  346.  
  347. =item add_part ENTITY, [OFFSET]
  348.  
  349. I<Instance method.>
  350. Assuming we are a multipart message, add a body part (a MIME::Entity)
  351. to the array of body parts.  Returns the part that was just added.
  352.  
  353. If OFFSET is positive, the new part is added at that offset from the
  354. beginning of the array of parts.  If it is negative, it counts from
  355. the end of the array.  (An INDEX of -1 will place the new part at the
  356. very end of the array, -2 will place it as the penultimate item in the
  357. array, etc.)  If OFFSET is not given, the new part is added to the end
  358. of the array.
  359. I<Thanks to Jason L Tibbitts III for providing support for OFFSET.>
  360.  
  361. B<Warning:> in general, you only want to attach parts to entities
  362. with a content-type of C<multipart/*>).
  363.  
  364. =cut
  365.  
  366. sub add_part {
  367.     my ($self, $part, $index) = @_;
  368.     defined($index) or $index = -1;
  369.  
  370.     ### Make $index count from the end if negative:
  371.     $index = $#{$self->{ME_Parts}} + 2 + $index if ($index < 0);
  372.     splice(@{$self->{ME_Parts}}, $index, 0, $part);
  373.     $part;
  374. }
  375.  
  376. #------------------------------
  377.  
  378. =item attach PARAMHASH
  379.  
  380. I<Instance method.>
  381. The real quick-and-easy way to create multipart messages.
  382. The PARAMHASH is used to C<build> a new entity; this method is
  383. basically equivalent to:
  384.  
  385.     $entity->add_part(ref($entity)->build(PARAMHASH, Top=>0));
  386.  
  387. B<Note:> normally, you attach to multipart entities; however, if you
  388. attach something to a singlepart (like attaching a GIF to a text
  389. message), the singlepart will be coerced into a multipart automatically.
  390.  
  391. =cut
  392.  
  393. sub attach {
  394.     my $self = shift;
  395.     $self->make_multipart;
  396.     $self->add_part(ref($self)->build(@_, Top=>0));
  397. }
  398.  
  399. #------------------------------
  400.  
  401. =item build PARAMHASH
  402.  
  403. I<Class/instance method.>
  404. A quick-and-easy catch-all way to create an entity.  Use it like this
  405. to build a "normal" single-part entity:
  406.  
  407.    $ent = MIME::Entity->build(Type     => "image/gif",
  408.                       Encoding => "base64",
  409.                               Path     => "/path/to/xyz12345.gif",
  410.                               Filename => "saveme.gif",
  411.                               Disposition => "attachment");
  412.  
  413. And like this to build a "multipart" entity:
  414.  
  415.    $ent = MIME::Entity->build(Type     => "multipart/mixed",
  416.                               Boundary => "---1234567");
  417.  
  418. A minimal MIME header will be created.  If you want to add or modify
  419. any header fields afterwards, you can of course do so via the underlying
  420. head object... but hey, there's now a prettier syntax!
  421.  
  422.    $ent = MIME::Entity->build(Type          =>"multipart/mixed",
  423.                               From          => $myaddr,
  424.                               Subject       => "Hi!",
  425.                               'X-Certified' => ['SINED',
  426.                                                 'SEELED',
  427.                                                 'DELIVERED']);
  428.  
  429. Normally, an C<X-Mailer> header field is output which contains this
  430. toolkit's name and version (plus this module's RCS version).
  431. This will allow any bad MIME we generate to be traced back to us.
  432. You can of course overwrite that header with your own:
  433.  
  434.    $ent = MIME::Entity->build(Type        => "multipart/mixed",
  435.                               'X-Mailer'  => "myprog 1.1");
  436.  
  437. Or remove it entirely:
  438.  
  439.    $ent = MIME::Entity->build(Type       => "multipart/mixed",
  440.                               'X-Mailer' => undef);
  441.  
  442. OK, enough hype.  The parameters are:
  443.  
  444. =over 4
  445.  
  446. =item (FIELDNAME)
  447.  
  448. Any field you want placed in the message header, taken from the
  449. standard list of header fields (you don't need to worry about case):
  450.  
  451.     Bcc           Encrypted     Received      Sender
  452.     Cc            From          References    Subject
  453.     Comments      Keywords      Reply-To      To
  454.     Content-*      Message-ID    Resent-*      X-*
  455.     Date          MIME-Version  Return-Path
  456.                   Organization
  457.  
  458. To give experienced users some veto power, these fields will be set
  459. I<after> the ones I set... so be careful: I<don't set any MIME fields>
  460. (like C<Content-type>) unless you know what you're doing!
  461.  
  462. To specify a fieldname that's I<not> in the above list, even one that's
  463. identical to an option below, just give it with a trailing C<":">,
  464. like C<"My-field:">.  When in doubt, that I<always> signals a mail
  465. field (and it sort of looks like one too).
  466.  
  467. =item Boundary
  468.  
  469. I<Multipart entities only. Optional.>
  470. The boundary string.  As per RFC-1521, it must consist only
  471. of the characters C<[0-9a-zA-Z'()+_,-./:=?]> and space (you'll be
  472. warned, and your boundary will be ignored, if this is not the case).
  473. If you omit this, a random string will be chosen... which is probably
  474. safer.
  475.  
  476. =item Charset
  477.  
  478. I<Optional.>
  479. The character set.
  480.  
  481. =item Data
  482.  
  483. I<Single-part entities only. Optional.>
  484. An alternative to Path (q.v.): the actual data, either as a scalar
  485. or an array reference (whose elements are joined together to make
  486. the actual scalar).  The body is opened on the data using
  487. MIME::Body::InCore.
  488.  
  489. =item Description
  490.  
  491. I<Optional.>
  492. The text of the content-description.
  493. If you don't specify it, the field is not put in the header.
  494.  
  495. =item Disposition
  496.  
  497. I<Optional.>
  498. The basic content-disposition (C<"attachment"> or C<"inline">).
  499. If you don't specify it, it defaults to "inline" for backwards
  500. compatibility.  I<Thanks to Kurt Freytag for suggesting this feature.>
  501.  
  502. =item Encoding
  503.  
  504. I<Optional.>
  505. The content-transfer-encoding.
  506. If you don't specify it, a reasonable default is put in.
  507. You can also give the special value '-SUGGEST', to have it chosen for
  508. you in a heavy-duty fashion which scans the data itself.
  509.  
  510. =item Filename
  511.  
  512. I<Single-part entities only. Optional.>
  513. The recommended filename.  Overrides any name extracted from C<Path>.
  514. The information is stored both the deprecated (content-type) and
  515. preferred (content-disposition) locations.  If you explicitly want to
  516. I<avoid> a recommended filename (even when Path is used), supply this
  517. as empty or undef.
  518.  
  519. =item Id
  520.  
  521. I<Optional.>
  522. Set the content-id.
  523.  
  524. =item Path
  525.  
  526. I<Single-part entities only. Optional.>
  527. The path to the file to attach.  The body is opened on that file
  528. using MIME::Body::File.
  529.  
  530. =item Top
  531.  
  532. I<Optional.>
  533. Is this a top-level entity?  If so, it must sport a MIME-Version.
  534. The default is true.  (NB: look at how C<attach()> uses it.)
  535.  
  536. =item Type
  537.  
  538. I<Optional.>
  539. The basic content-type (C<"text/plain">, etc.).
  540. If you don't specify it, it defaults to C<"text/plain">
  541. as per RFC-1521.  I<Do yourself a favor: put it in.>
  542.  
  543. =back
  544.  
  545. =cut
  546.  
  547. sub build {
  548.     my ($self, @paramlist) = @_;
  549.     my %params = @paramlist;
  550.     my ($field, $filename, $boundary);
  551.  
  552.     ### Create a new entity, if needed:
  553.     ref($self) or $self = $self->new;
  554.  
  555.  
  556.     ### GET INFO...
  557.  
  558.     ### Get sundry field:
  559.     my $type         = $params{Type} || 'text/plain';
  560.     my $charset      = $params{Charset};
  561.     my $is_multipart = ($type =~ m{^multipart/}i);
  562.     my $encoding     = $params{Encoding} || '';
  563.     my $desc         = $params{Description};
  564.     my $top          = exists($params{Top}) ? $params{Top} : 1;
  565.     my $disposition  = $params{Disposition} || 'inline';
  566.     my $id           = $params{Id};
  567.  
  568.     ### Get recommended filename, allowing explicit no-value value:
  569.     my ($path_fname) = (($params{Path}||'') =~ m{([^/]+)\Z});
  570.     $filename = (exists($params{Filename}) ? $params{Filename} : $path_fname);
  571.     $filename = undef if (defined($filename) and $filename eq '');
  572.     
  573.     ### Type-check sanity:
  574.     if ($type =~ m{^(multipart|message)/}) {
  575.     ($encoding =~ /^(|7bit|8bit|binary|-suggest)$/i) 
  576.         or croak "can't have encoding $encoding for message type $type!";
  577.     }
  578.  
  579.     ### Multipart or not? Do sanity check and fixup:
  580.     if ($is_multipart) {      ### multipart...
  581.     
  582.     ### Get any supplied boundary, and check it:
  583.     if (defined($boundary = $params{Boundary})) {  ### they gave us one...
  584.         if ($boundary eq '') {
  585.         whine "empty string not a legal boundary: I'm ignoring it";
  586.         $boundary = undef;
  587.         }
  588.         elsif ($boundary =~ m{[^0-9a-zA-Z_\'\(\)\+\,\.\/\:\=\?\- ]}) {
  589.         whine "boundary ignored: illegal characters ($boundary)";
  590.         $boundary = undef;
  591.         }
  592.     }
  593.     
  594.     ### If we have to roll our own boundary, do so:
  595.     defined($boundary) or $boundary = make_boundary();
  596.     }
  597.     else {                    ### single part...
  598.     ### Create body:
  599.     if ($params{Path}) {
  600.         $self->bodyhandle(new MIME::Body::File $params{Path});
  601.     }
  602.     elsif (defined($params{Data})) {
  603.         $self->bodyhandle(new MIME::Body::InCore $params{Data});
  604.     }
  605.     else { 
  606.         die "can't build entity: no body, and not multipart\n";
  607.     }
  608.  
  609.     ### Check whether we need to binmode():   [Steve Kilbane]
  610.     $self->bodyhandle->binmode(1) unless textual_type($type);
  611.     }
  612.  
  613.  
  614.     ### MAKE HEAD...
  615.  
  616.     ### Create head:
  617.     my $head = new MIME::Head;
  618.     $self->head($head);
  619.     $head->modify(1);
  620.  
  621.     ### Add content-type field:
  622.     $field = new Mail::Field 'Content_type';         ### not a typo :-(
  623.     $field->type($type);
  624.     $field->charset($charset)    if $charset;
  625.     $field->name($filename)      if defined($filename);
  626.     $field->boundary($boundary)  if defined($boundary);
  627.     $head->replace('Content-type', $field->stringify);
  628.  
  629.     ### Now that both body and content-type are available, we can suggest 
  630.     ### content-transfer-encoding (if desired);
  631.     if (!$encoding) {
  632.     $encoding = $self->suggest_encoding_lite;
  633.     }
  634.     elsif (lc($encoding) eq '-suggest') {
  635.     $encoding = $self->suggest_encoding;
  636.     }
  637.    
  638.     ### Add content-disposition field (if not multipart):
  639.     unless ($is_multipart) {
  640.     $field = new Mail::Field 'Content_disposition';  ### not a typo :-(
  641.     $field->type($disposition);
  642.     $field->filename($filename) if defined($filename);
  643.     $head->replace('Content-disposition', $field->stringify);
  644.     }
  645.  
  646.     ### Add other MIME fields:
  647.     $head->replace('Content-transfer-encoding', $encoding) if $encoding;
  648.     $head->replace('Content-description', $desc)           if $desc;
  649.     $head->replace('Content-id', $id)                      if defined($id);
  650.     $head->replace('MIME-Version', '1.0')                  if $top;
  651.  
  652.     ### Add the X-Mailer field, if top level (use default value if not given):
  653.     $top and $head->replace('X-Mailer', 
  654.                 "MIME-tools ".(0+MIME::Tools->version).
  655.                 " (Entity "  .(0+$VERSION).")"); 
  656.     
  657.     ### Add remaining user-specified fields, if any:
  658.     while (@paramlist) {
  659.     my ($tag, $value) = (shift @paramlist, shift @paramlist);
  660.  
  661.     ### Get fieldname, if that's what it is:
  662.     if    ($tag =~ /^-(.*)/s)  { $tag = lc($1) }    ### old style, b.c.
  663.     elsif ($tag =~ /(.*):$/s ) { $tag = lc($1) }    ### new style
  664.     elsif (known_field(lc($tag)))     { 1 }    ### known field
  665.     else { next; }                             ### not a field
  666.  
  667.     ### Clear head, get list of values, and add them:
  668.     $head->delete($tag);
  669.     foreach $value (ref($value) ? @$value : ($value)) {
  670.         (defined($value) && ($value ne '')) or next;
  671.         $head->add($tag, $value);
  672.     }
  673.     }
  674.     
  675.     ### Done!
  676.     $self;
  677. }
  678.  
  679. #------------------------------
  680.  
  681. =item dup
  682.  
  683. I<Instance method.>
  684. Duplicate the entity.  Does a deep, recursive copy, I<but beware:>
  685. external data in bodyhandles is I<not> copied to new files!
  686. Changing the data in one entity's data file, or purging that entity,
  687. I<will> affect its duplicate.  Entities with in-core data probably need
  688. not worry.
  689.  
  690. =cut
  691.  
  692. sub dup {
  693.     my $self = shift;
  694.     local($_);
  695.  
  696.     ### Self (this will also dup the header):
  697.     my $dup = bless $self->SUPER::dup(), ref($self);
  698.  
  699.     ### Any simple inst vars:
  700.     foreach (keys %$self) {$dup->{$_} = $self->{$_} unless ref($self->{$_})};
  701.     
  702.     ### Bodyhandle:
  703.     $dup->bodyhandle($self->bodyhandle ? $self->bodyhandle->dup : undef);
  704.  
  705.     ### Preamble and epilogue:
  706.     foreach (qw(ME_Preamble ME_Epilogue)) {
  707.     $dup->{$_} = [@{$self->{$_}}]  if $self->{$_};
  708.     }
  709.  
  710.     ### Parts:
  711.     $dup->{ME_Parts} = [];
  712.     foreach (@{$self->{ME_Parts}}) { push @{$dup->{ME_Parts}}, $_->dup }
  713.  
  714.     ### Done!
  715.     $dup;
  716. }
  717.  
  718. =back
  719.  
  720. =cut
  721.  
  722.  
  723.  
  724.  
  725.  
  726. #==============================
  727.  
  728. =head2 Access
  729.  
  730. =over 4
  731.  
  732. =cut
  733.  
  734.  
  735. #------------------------------
  736.  
  737. =item body [VALUE]
  738.  
  739. I<Instance method.>
  740. Get the I<encoded> (transport-ready) body, as an array of lines.
  741. This is a read-only data structure: changing its contents will have
  742. no effect.  Its contents are identical to what is printed by
  743. L<print_body()|/print_body>.
  744.  
  745. Provided for compatibility with Mail::Internet, so that methods
  746. like C<smtpsend()> will work.  Note however that if VALUE is given,
  747. a fatal exception is thrown, since you cannot use this method to
  748. I<set> the lines of the encoded message.
  749.  
  750. If you want the raw (unencoded) body data, use the L<bodyhandle()|/bodyhandle>
  751. method to get and use a MIME::Body.  The content-type of the entity
  752. will tell you whether that body is best read as text (via getline())
  753. or raw data (via read()).
  754.  
  755. =cut
  756.  
  757. sub body {
  758.     my ($self, $value) = @_;
  759.     if (@_ > 1) {      ### setting body line(s)...
  760.     croak "you cannot use body() to set the encoded contents\n";
  761.     }
  762.     else {             ### getting body lines...
  763.     my $lines = [];
  764.     my $lh = IO::Lines->new($lines);
  765.     $self->print_body($lh);
  766.     return $lines;
  767.     }
  768. }
  769.  
  770. #------------------------------
  771.  
  772. =item bodyhandle [VALUE]
  773.  
  774. I<Instance method.>
  775. Get or set an abstract object representing the body of the message.
  776. The body holds the decoded message data.
  777.  
  778. B<Note that not all entities have bodies!>
  779. An entity will have either a body or parts: not both.
  780. This method will I<only> return an object if this entity can
  781. have a body; otherwise, it will return undefined.
  782. Whether-or-not a given entity can have a body is determined by
  783. (1) its content type, and (2) whether-or-not the parser was told to
  784. extract nested messages:
  785.  
  786.     Type:        | Extract nested? | bodyhandle() | parts()
  787.     -----------------------------------------------------------------------
  788.     multipart/*  | -               | undef        | 0 or more MIME::Entity
  789.     message/*    | true            | undef        | 0 or 1 MIME::Entity
  790.     message/*    | false           | MIME::Body   | empty list
  791.     (other)      | -               | MIME::Body   | empty list
  792.  
  793. If C<VALUE> I<is not> given, the current bodyhandle is returned,
  794. or undef if the entity cannot have a body.
  795.  
  796. If C<VALUE> I<is> given, the bodyhandle is set to the new value,
  797. and the previous value is returned.
  798.  
  799. See L</parts> for more info.
  800.  
  801. =cut
  802.  
  803. sub bodyhandle {
  804.     my ($self, $newvalue) = @_;
  805.     my $value = $self->{ME_Bodyhandle};
  806.     $self->{ME_Bodyhandle} = $newvalue if (@_ > 1);
  807.     $value;
  808. }
  809.  
  810. #------------------------------
  811.  
  812. =item effective_type [MIMETYPE]
  813.  
  814. I<Instance method.>
  815. Set/get the I<effective> MIME type of this entity.  This is I<usually>
  816. identical to the actual (or defaulted) MIME type, but in some cases
  817. it differs.  For example, from RFC-2045:
  818.  
  819.    Any entity with an unrecognized Content-Transfer-Encoding must be
  820.    treated as if it has a Content-Type of "application/octet-stream",
  821.    regardless of what the Content-Type header field actually says.
  822.  
  823. Why? because if we can't decode the message, then we have to take
  824. the bytes as-is, in their (unrecognized) encoded form.  So the
  825. message ceases to be a "text/foobar" and becomes a bunch of undecipherable
  826. bytes -- in other words, an "application/octet-stream".
  827.  
  828. Such an entity, if parsed, would have its effective_type() set to
  829. C<"application/octet_stream">, although the mime_type() and the contents
  830. of the header would remain the same.
  831.  
  832. If there is no effective type, the method just returns what
  833. mime_type() would.
  834.  
  835. B<Warning:> the effective type is "sticky"; once set, that effective_type()
  836. will always be returned even if the conditions that necessitated setting
  837. the effective type become no longer true.
  838.  
  839. =cut
  840.  
  841. sub effective_type {
  842.     my $self = shift;
  843.     $self->{ME_EffType} = shift if @_;
  844.     return ($self->{ME_EffType} ? lc($self->{ME_EffType}) : $self->mime_type);
  845. }
  846.  
  847.  
  848. #------------------------------
  849.  
  850. =item epilogue [LINES]
  851.  
  852. I<Instance method.>
  853. Get/set the text of the epilogue, as an array of newline-terminated LINES.
  854. Returns a reference to the array of lines, or undef if no epilogue exists.
  855.  
  856. If there is a epilogue, it is output when printing this entity; otherwise,
  857. a default epilogue is used.  Setting the epilogue to undef (not []!) causes
  858. it to fallback to the default.
  859.  
  860. =cut
  861.  
  862. sub epilogue {
  863.     my ($self, $lines) = @_;
  864.     $self->{ME_Epilogue} = $lines if @_ > 1;
  865.     $self->{ME_Epilogue};
  866. }
  867.  
  868. #------------------------------
  869.  
  870. =item head [VALUE]
  871.  
  872. I<Instance method.>
  873. Get/set the head.
  874.  
  875. If there is no VALUE given, returns the current head.  If none
  876. exists, an empty instance of MIME::Head is created, set, and returned.
  877.  
  878. B<Note:> This is a patch over a problem in Mail::Internet, which doesn't
  879. provide a method for setting the head to some given object.
  880.  
  881. =cut
  882.  
  883. sub head { 
  884.     my ($self, $value) = @_;
  885.     (@_ > 1) and $self->{'mail_inet_head'} = $value;
  886.     $self->{'mail_inet_head'} ||= new MIME::Head;       ### KLUDGE!
  887. }
  888.  
  889. #------------------------------
  890.  
  891. =item is_multipart
  892.  
  893. I<Instance method.>
  894. Does this entity's effective MIME type indicate that it's a multipart entity?
  895. Returns undef (false) if the answer couldn't be determined, 0 (false)
  896. if it was determined to be false, and true otherwise.
  897. Note that this says nothing about whether or not parts were extracted.
  898.  
  899. NOTE: we switched to effective_type so that multiparts with
  900. bad or missing boundaries could be coerced to an effective type
  901. of C<application/x-unparseable-multipart>.
  902.  
  903.  
  904. =cut
  905.  
  906. sub is_multipart {
  907.     my $self = shift;
  908.     $self->head or return undef;        ### no head, so no MIME type!
  909.     my ($type, $subtype) = split('/', $self->effective_type);
  910.     (($type eq 'multipart') ? 1 : 0);
  911. }
  912.  
  913. #------------------------------
  914.  
  915. =item mime_type
  916.  
  917. I<Instance method.>
  918. A purely-for-convenience method.  This simply relays the request to the
  919. associated MIME::Head object.
  920. If there is no head, returns undef in a scalar context and
  921. the empty array in a list context.
  922.  
  923. B<Before you use this,> consider using effective_type() instead,
  924. especially if you obtained the entity from a MIME::Parser.
  925.  
  926. =cut
  927.  
  928. sub mime_type {
  929.     my $self = shift;
  930.     $self->head or return (wantarray ? () : undef);
  931.     $self->head->mime_type;
  932. }
  933.  
  934. #------------------------------
  935.  
  936. =item open READWRITE
  937.  
  938. I<Instance method.>
  939. A purely-for-convenience method.  This simply relays the request to the
  940. associated MIME::Body object (see MIME::Body::open()).
  941. READWRITE is either 'r' (open for read) or 'w' (open for write).
  942.  
  943. If there is no body, returns false.
  944.  
  945. =cut
  946.  
  947. sub open {
  948.     my $self = shift;
  949.     $self->bodyhandle and $self->bodyhandle->open(@_);
  950. }
  951.  
  952. #------------------------------
  953.  
  954. =item parts
  955.  
  956. =item parts INDEX
  957.  
  958. =item parts ARRAYREF
  959.  
  960. I<Instance method.>
  961. Return the MIME::Entity objects which are the sub parts of this
  962. entity (if any).
  963.  
  964. I<If no argument is given,> returns the array of all sub parts,
  965. returning the empty array if there are none (e.g., if this is a single
  966. part message, or a degenerate multipart).  In a scalar context, this
  967. returns you the number of parts.
  968.  
  969. I<If an integer INDEX is given,> return the INDEXed part,
  970. or undef if it doesn't exist.
  971.  
  972. I<If an ARRAYREF to an array of parts is given,> then this method I<sets>
  973. the parts to a copy of that array, and returns the parts.  This can
  974. be used to delete parts, as follows:
  975.  
  976.     ### Delete some parts of a multipart message:
  977.     $msg->parts([ grep { keep_part($_) } $msg->parts ]);
  978.  
  979.  
  980. B<Note:> for multipart messages, the preamble and epilogue are I<not>
  981. considered parts.  If you need them, use the C<preamble()> and C<epilogue()>
  982. methods.
  983.  
  984. B<Note:> there are ways of parsing with a MIME::Parser which cause
  985. certain message parts (such as those of type C<message/rfc822>)
  986. to be "reparsed" into pseudo-multipart entities.  You should read the
  987. documentation for those options carefully: it I<is> possible for
  988. a diddled entity to not be multipart, but still have parts attached to it!
  989.  
  990. See L</bodyhandle> for a discussion of parts vs. bodies.
  991.  
  992. =cut
  993.  
  994. sub parts {
  995.     my $self = shift;
  996.     ref($_[0]) and return @{$self->{ME_Parts} = [@{$_[0]}]};  ### set the parts
  997.     (@_ ? $self->{ME_Parts}[$_[0]] : @{$self->{ME_Parts}});
  998. }
  999.  
  1000. #------------------------------
  1001.  
  1002. =item parts_DFS
  1003.  
  1004. I<Instance method.>
  1005. Return the list of all MIME::Entity objects included in the entity,
  1006. starting with the entity itself, in depth-first-search order.
  1007. If the entity has no parts, it alone will be returned.
  1008.  
  1009. I<Thanks to Xavier Armengou for suggesting this method.>
  1010.  
  1011. =cut
  1012.  
  1013. sub parts_DFS {
  1014.     my $self = shift;
  1015.     return ($self, map { $_->parts_DFS } $self->parts);
  1016. }
  1017.  
  1018. #------------------------------
  1019.  
  1020. =item preamble [LINES]
  1021.  
  1022. I<Instance method.>
  1023. Get/set the text of the preamble, as an array of newline-terminated LINES.
  1024. Returns a reference to the array of lines, or undef if no preamble exists
  1025. (e.g., if this is a single-part entity).
  1026.  
  1027. If there is a preamble, it is output when printing this entity; otherwise,
  1028. a default preamble is used.  Setting the preamble to undef (not []!) causes
  1029. it to fallback to the default.
  1030.  
  1031. =cut
  1032.  
  1033. sub preamble {
  1034.     my ($self, $lines) = @_;
  1035.     $self->{ME_Preamble} = $lines if @_ > 1;
  1036.     $self->{ME_Preamble};
  1037. }
  1038.  
  1039.  
  1040.  
  1041.  
  1042.  
  1043. =back
  1044.  
  1045. =cut
  1046.  
  1047.  
  1048.  
  1049.  
  1050. #==============================
  1051.  
  1052. =head2 Manipulation
  1053.  
  1054. =over 4
  1055.  
  1056. =cut
  1057.  
  1058. #------------------------------
  1059.  
  1060. =item make_multipart [SUBTYPE], OPTSHASH...
  1061.  
  1062. I<Instance method.>
  1063. Force the entity to be a multipart, if it isn't already.
  1064. We do this by replacing the original [singlepart] entity with a new
  1065. multipart that has the same non-MIME headers ("From", "Subject", etc.),
  1066. but all-new MIME headers ("Content-type", etc.).  We then create
  1067. a copy of the original singlepart, I<strip out> the non-MIME headers
  1068. from that, and make it a part of the new multipart.  So this:
  1069.  
  1070.     From: me
  1071.     To: you
  1072.     Content-type: text/plain
  1073.     Content-length: 12
  1074.  
  1075.     Hello there!
  1076.  
  1077. Becomes something like this:
  1078.  
  1079.     From: me
  1080.     To: you
  1081.     Content-type: multipart/mixed; boundary="----abc----"
  1082.  
  1083.     ------abc----
  1084.     Content-type: text/plain
  1085.     Content-length: 12
  1086.  
  1087.     Hello there!
  1088.     ------abc------
  1089.  
  1090. The actual type of the new top-level multipart will be "multipart/SUBTYPE"
  1091. (default SUBTYPE is "mixed").
  1092.  
  1093. Returns 'DONE'    if we really did inflate a singlepart to a multipart.
  1094. Returns 'ALREADY' (and does nothing) if entity is I<already> multipart
  1095. and Force was not chosen.
  1096.  
  1097. If OPTSHASH contains Force=>1, then we I<always> bump the top-level's
  1098. content and content-headers down to a subpart of this entity, even if
  1099. this entity is already a multipart.  This is apparently of use to
  1100. people who are tweaking messages after parsing them.
  1101.  
  1102. =cut
  1103.  
  1104. sub make_multipart {
  1105.     my ($self, $subtype, %opts) = @_;
  1106.     my $tag;
  1107.     $subtype ||= 'mixed';
  1108.     my $force = $opts{Force};
  1109.  
  1110.     ### Trap for simple case: already a multipart?
  1111.     return 'ALREADY' if ($self->is_multipart and !$force); 
  1112.  
  1113.     ### Rip out our guts, and spew them into our future part:
  1114.     my $part = bless {%$self}, ref($self);         ### part is a shallow copy
  1115.     %$self = ();                                   ### lobotomize ourselves!
  1116.     $self->head($part->head->dup);                 ### dup the header
  1117.     
  1118.     ### Remove content headers from top-level, and set it up as a multipart:
  1119.     foreach $tag (grep {/^content-/i} $self->head->tags) {
  1120.     $self->head->delete($tag);
  1121.     }
  1122.     $self->head->mime_attr('Content-type'          => "multipart/$subtype");
  1123.     $self->head->mime_attr('Content-type.boundary' => make_boundary());
  1124.  
  1125.     ### Remove NON-content headers from the part:
  1126.     foreach $tag (grep {!/^content-/i} $part->head->tags) {
  1127.     $part->head->delete($tag);
  1128.     }
  1129.  
  1130.     ### Add the [sole] part:
  1131.     $self->{ME_Parts} = []; 
  1132.     $self->add_part($part);
  1133.     'DONE';
  1134. }
  1135.  
  1136. #------------------------------
  1137.  
  1138. =item make_singlepart
  1139.  
  1140. I<Instance method.>
  1141. If the entity is a multipart message with one part, this tries hard to
  1142. rewrite it as a singlepart, by replacing the content (and content headers)
  1143. of the top level with those of the part.  Also crunches 0-part multiparts
  1144. into singleparts.
  1145.  
  1146. Returns 'DONE'    if we really did collapse a multipart to a singlepart.
  1147. Returns 'ALREADY' (and does nothing) if entity is already a singlepart.
  1148. Returns '0'       (and does nothing) if it can't be made into a singlepart.
  1149.  
  1150. =cut
  1151.  
  1152. sub make_singlepart {
  1153.     my $self = shift;
  1154.  
  1155.     ### Trap for simple cases:
  1156.     return 'ALREADY' if !$self->is_multipart;      ### already a singlepart?
  1157.     return '0' if ($self->parts > 1);              ### can this even be done?
  1158.  
  1159.     ### Do it:
  1160.     if ($self->parts == 1) {    ### one part
  1161.     my $part = $self->parts(0);
  1162.     my $tag;
  1163.  
  1164.     ### Get rid of all our existing content info:
  1165.     foreach $tag (grep {/^content-/i} $self->head->tags) {
  1166.         $self->head->delete($tag);
  1167.     }
  1168.     
  1169.     ### Populate ourselves with any content info from the part:
  1170.     foreach $tag (grep {/^content-/i} $part->head->tags) {
  1171.         foreach ($part->head->get($tag)) { $self->head->add($tag, $_) }
  1172.     }
  1173.  
  1174.     ### Save reconstructed header, replace our guts, and restore header:
  1175.     my $new_head = $self->head;
  1176.     %$self = %$part;               ### shallow copy is ok!
  1177.     $self->head($new_head);
  1178.  
  1179.     ### One more thing: the part *may* have been a multi with 0 or 1 parts!
  1180.     return $self->make_singlepart(@_) if $self->is_multipart;
  1181.     }
  1182.     else {                      ### no parts!
  1183.     $self->head->mime_attr('Content-type'=>'text/plain');   ### simple
  1184.     }
  1185.     'DONE';
  1186. }
  1187.  
  1188. #------------------------------
  1189.  
  1190. =item purge
  1191.  
  1192. I<Instance method.>
  1193. Recursively purge (e.g., unlink) all external (e.g., on-disk) body parts
  1194. in this message.  See MIME::Body::purge() for details.
  1195.  
  1196. B<Note:> this does I<not> delete the directories that those body parts
  1197. are contained in; only the actual message data files are deleted.
  1198. This is because some parsers may be customized to create intermediate
  1199. directories while others are not, and it's impossible for this class
  1200. to know what directories are safe to remove.  Only your application
  1201. program truly knows that.
  1202.  
  1203. B<If you really want to "clean everything up",> one good way is to
  1204. use C<MIME::Parser::file_under()>, and then do this before parsing
  1205. your next message:
  1206.  
  1207.     $parser->filer->purge();
  1208.  
  1209. I wouldn't attempt to read those body files after you do this, for
  1210. obvious reasons.  As of MIME-tools 4.x, each body's path I<is> undefined
  1211. after this operation.  I warned you I might do this; truly I did.
  1212.  
  1213. I<Thanks to Jason L. Tibbitts III for suggesting this method.>
  1214.  
  1215. =cut
  1216.  
  1217. sub purge {
  1218.     my $self = shift;
  1219.     $self->bodyhandle and $self->bodyhandle->purge;      ### purge me
  1220.     foreach ($self->parts) { $_->purge }                 ### recurse
  1221.     1;
  1222. }
  1223.  
  1224. #------------------------------
  1225. #
  1226. # _do_remove_sig
  1227. #
  1228. # Private.  Remove a signature within NLINES lines from the end of BODY.
  1229. # The signature must be flagged by a line containing only "-- ".
  1230.  
  1231. sub _do_remove_sig {
  1232.     my ($body, $nlines) = @_;
  1233.     $nlines ||= 10;
  1234.     my $i = 0;
  1235.  
  1236.     my $line = int(@$body) || return;
  1237.     while ($i++ < $nlines and $line--) {
  1238.     if ($body->[$line] =~ /\A--[ \040][\r\n]+\Z/) {
  1239.         $#{$body} = $line-1;
  1240.         return;
  1241.     }
  1242.     }
  1243. }
  1244.  
  1245. #------------------------------
  1246.  
  1247. =item remove_sig [NLINES]
  1248.  
  1249. I<Instance method, override.>
  1250. Attempts to remove a user's signature from the body of a message.
  1251.  
  1252. It does this by looking for a line matching C</^-- $/> within the last
  1253. C<NLINES> of the message.  If found then that line and all lines after
  1254. it will be removed. If C<NLINES> is not given, a default value of 10
  1255. will be used.  This would be of most use in auto-reply scripts.
  1256.  
  1257. For MIME entity, this method is reasonably cautious: it will only
  1258. attempt to un-sign a message with a content-type of C<text/*>.
  1259.  
  1260. If you send remove_sig() to a multipart entity, it will relay it to
  1261. the first part (the others usually being the "attachments").
  1262.  
  1263. B<Warning:> currently slurps the whole message-part into core as an
  1264. array of lines, so you probably don't want to use this on extremely
  1265. long messages.
  1266.  
  1267. Returns truth on success, false on error.
  1268.  
  1269. =cut
  1270.  
  1271. sub remove_sig {
  1272.     my $self = shift;
  1273.     my $nlines = shift;
  1274.  
  1275.     ### Handle multiparts:
  1276.     $self->is_multipart and return $self->{ME_Parts}[0]->remove_sig(@_);
  1277.  
  1278.     ### Refuse non-textual unless forced:
  1279.     textual_type($self->head->mime_type)
  1280.     or return error "I won't un-sign a non-text message unless I'm forced";
  1281.     
  1282.     ### Get body data, as an array of newline-terminated lines:
  1283.     $self->bodyhandle or return undef;
  1284.     my @body = $self->bodyhandle->as_lines;
  1285.  
  1286.     ### Nuke sig:
  1287.     _do_remove_sig(\@body, $nlines);
  1288.  
  1289.     ### Output data back into body:
  1290.     my $io = $self->bodyhandle->open("w");
  1291.     foreach (@body) { $io->print($_) };  ### body data
  1292.     $io->close;
  1293.  
  1294.     ### Done!
  1295.     1;       
  1296. }
  1297.  
  1298. #------------------------------
  1299.  
  1300. =item sign PARAMHASH
  1301.  
  1302. I<Instance method, override.>
  1303. Append a signature to the message.  The params are:
  1304.  
  1305. =over 4
  1306.  
  1307. =item Attach
  1308.  
  1309. Instead of appending the text, add it to the message as an attachment.
  1310. The disposition will be C<inline>, and the description will indicate
  1311. that it is a signature.  The default behavior is to append the signature
  1312. to the text of the message (or the text of its first part if multipart).
  1313. I<MIME-specific; new in this subclass.>
  1314.  
  1315. =item File
  1316.  
  1317. Use the contents of this file as the signature.
  1318. Fatal error if it can't be read.
  1319. I<As per superclass method.>
  1320.  
  1321. =item Force
  1322.  
  1323. Sign it even if the content-type isn't C<text/*>.  Useful for
  1324. non-standard types like C<x-foobar>, but be careful!
  1325. I<MIME-specific; new in this subclass.>
  1326.  
  1327. =item Remove
  1328.  
  1329. Normally, we attempt to strip out any existing signature.
  1330. If true, this gives us the NLINES parameter of the remove_sig call.
  1331. If zero but defined, tells us I<not> to remove any existing signature.
  1332. If undefined, removal is done with the default of 10 lines.
  1333. I<New in this subclass.>
  1334.  
  1335. =item Signature
  1336.  
  1337. Use this text as the signature.  You can supply it as either
  1338. a scalar, or as a ref to an array of newline-terminated scalars.
  1339. I<As per superclass method.>
  1340.  
  1341. =back
  1342.  
  1343. For MIME messages, this method is reasonably cautious: it will only
  1344. attempt to sign a message with a content-type of C<text/*>, unless
  1345. C<Force> is specified.
  1346.  
  1347. If you send this message to a multipart entity, it will relay it to
  1348. the first part (the others usually being the "attachments").
  1349.  
  1350. B<Warning:> currently slurps the whole message-part into core as an
  1351. array of lines, so you probably don't want to use this on extremely
  1352. long messages.
  1353.  
  1354. Returns true on success, false otherwise.
  1355.  
  1356. =cut
  1357.  
  1358. sub sign {
  1359.     my $self = shift;
  1360.     my %params = @_;
  1361.     my $io;
  1362.  
  1363.     ### If multipart and not attaching, try to sign our first part:
  1364.     if ($self->is_multipart and !$params{Attach}) {
  1365.     return $self->parts(0)->sign(@_);
  1366.     }
  1367.  
  1368.     ### Get signature:
  1369.     my $sig;
  1370.     if (defined($sig = $params{Signature})) {    ### scalar or array
  1371.     $sig = (ref($sig) ? join('', @$sig) : $sig);
  1372.     }
  1373.     elsif ($params{File}) {                      ### file contents
  1374.     CORE::open SIG, $params{File} or croak "can't open $params{File}: $!";
  1375.     $sig = join('', SIG->getlines);
  1376.     close SIG;
  1377.     }
  1378.     else {
  1379.     croak "no signature given!";
  1380.     }
  1381.  
  1382.     ### Add signature to message as appropriate:
  1383.     if ($params{Attach}) {      ### Attach .sig as new part...
  1384.     return $self->attach(Type        => 'text/plain',
  1385.                  Description => 'Signature',
  1386.                  Disposition => 'inline',
  1387.                  Encoding    => '-SUGGEST',
  1388.                  Data        => $sig);
  1389.     }
  1390.     else {                      ### Add text of .sig to body data...
  1391.  
  1392.     ### Refuse non-textual unless forced:
  1393.     ($self->head->mime_type =~ m{text/}i or $params{Force}) or
  1394.         return error "I won't sign a non-text message unless I'm forced";
  1395.  
  1396.     ### Get body data, as an array of newline-terminated lines:
  1397.     $self->bodyhandle or return undef;
  1398.     my @body = $self->bodyhandle->as_lines;
  1399.     
  1400.     ### Nuke any existing sig?
  1401.     if (!defined($params{Remove}) || ($params{Remove} > 0)) {
  1402.         _do_remove_sig(\@body, $params{Remove});
  1403.     }
  1404.  
  1405.     ### Output data back into body, followed by signature:
  1406.     my $line;
  1407.     $io = $self->open("w");
  1408.     foreach $line (@body) { $io->print($line) };      ### body data
  1409.     (($body[-1]||'') =~ /\n\Z/) or $io->print("\n");  ### ensure final \n
  1410.     $io->print("-- \n$sig");                          ### separator + sig
  1411.     $io->close;    
  1412.     return 1;         ### done!
  1413.     }
  1414. }
  1415.  
  1416. #------------------------------
  1417.  
  1418. =item suggest_encoding
  1419.  
  1420. I<Instance method.>
  1421. Based on the effective content type, return a good suggested encoding.
  1422.  
  1423. C<text> and C<message> types have their bodies scanned line-by-line
  1424. for 8-bit characters and long lines; lack of either means that the
  1425. message is 7bit-ok.  Other types are chosen independent of their body:
  1426.  
  1427.     Major type:      7bit ok?    Suggested encoding:
  1428.     -----------------------------------------------------------
  1429.     text             yes         7bit
  1430.     text             no          quoted-printable
  1431.     message          yes         7bit
  1432.     message          no          binary
  1433.     multipart        *           binary (in case some parts are bad)
  1434.     image, etc...    *           base64
  1435.  
  1436. =cut
  1437.  
  1438. ### TO DO: resolve encodings of nested entities (possibly in sync_headers).
  1439.  
  1440. sub suggest_encoding {
  1441.     my $self = shift;
  1442.  
  1443.     my ($type) = split '/', $self->effective_type;
  1444.     if (($type eq 'text') || ($type eq 'message')) {    ### scan message body
  1445.     $self->bodyhandle || return ($self->parts ? 'binary' : '7bit');
  1446.     my ($IO, $unclean);
  1447.     if ($IO = $self->bodyhandle->open("r")) {
  1448.  
  1449.         ### Scan message for 7bit-cleanliness:
  1450.         while (defined($_ = $IO->getline)) {
  1451.         last if ($unclean = ((length($_) > 999) or /[\200-\377]/));
  1452.         }
  1453.         
  1454.         ### Return '7bit' if clean; try and encode if not...
  1455.         ### Note that encodings are not permitted for messages!
  1456.         return ($unclean 
  1457.             ? (($type eq 'message') ? 'binary' : 'quoted-printable')
  1458.             : '7bit'); 
  1459.     }
  1460.     }
  1461.     else {
  1462.     return ($type eq 'multipart') ? 'binary' : 'base64';
  1463.     }
  1464. }
  1465.  
  1466. sub suggest_encoding_lite {
  1467.     my $self = shift;
  1468.     my ($type) = split '/', $self->effective_type;
  1469.     return (($type =~ /^(text|message|multipart)$/) ? 'binary' : 'base64');
  1470. }
  1471.  
  1472. #------------------------------
  1473.  
  1474. =item sync_headers OPTIONS
  1475.  
  1476. I<Instance method.>
  1477. This method does a variety of activities which ensure that
  1478. the MIME headers of an entity "tree" are in-synch with the body parts
  1479. they describe.  It can be as expensive an operation as printing
  1480. if it involves pre-encoding the body parts; however, the aim is to
  1481. produce fairly clean MIME.  B<You will usually only need to invoke
  1482. this if processing and re-sending MIME from an outside source.>
  1483.  
  1484. The OPTIONS is a hash, which describes what is to be done.
  1485.  
  1486. =over 4
  1487.  
  1488.  
  1489. =item Length
  1490.  
  1491. One of the "official unofficial" MIME fields is "Content-Length".
  1492. Normally, one doesn't care a whit about this field; however, if
  1493. you are preparing output destined for HTTP, you may.  The value of
  1494. this option dictates what will be done:
  1495.  
  1496. B<COMPUTE> means to set a C<Content-Length> field for every non-multipart
  1497. part in the entity, and to blank that field out for every multipart
  1498. part in the entity.
  1499.  
  1500. B<ERASE> means that C<Content-Length> fields will all
  1501. be blanked out.  This is fast, painless, and safe.
  1502.  
  1503. B<Any false value> (the default) means to take no action.
  1504.  
  1505.  
  1506. =item Nonstandard
  1507.  
  1508. Any header field beginning with "Content-" is, according to the RFC,
  1509. a MIME field.  However, some are non-standard, and may cause problems
  1510. with certain MIME readers which interpret them in different ways.
  1511.  
  1512. B<ERASE> means that all such fields will be blanked out.  This is
  1513. done I<before> the B<Length> option (q.v.) is examined and acted upon.
  1514.  
  1515. B<Any false value> (the default) means to take no action.
  1516.  
  1517.  
  1518. =back
  1519.  
  1520. Returns a true value if everything went okay, a false value otherwise.
  1521.  
  1522. =cut
  1523.  
  1524. sub sync_headers {
  1525.     my $self = shift;    
  1526.     my $opts = ((int(@_) % 2 == 0) ? {@_} : shift);
  1527.     my $ENCBODY;     ### keep it around until done!
  1528.  
  1529.     ### Get options:
  1530.     my $o_nonstandard = ($opts->{Nonstandard} || 0);
  1531.     my $o_length      = ($opts->{Length}      || 0);
  1532.     
  1533.     ### Get head:
  1534.     my $head = $self->head;
  1535.     
  1536.     ### What to do with "nonstandard" MIME fields?
  1537.     if ($o_nonstandard eq 'ERASE') {       ### Erase them...
  1538.     my $tag;
  1539.     foreach $tag ($head->tags()) {
  1540.         if (($tag =~ /\AContent-/i) && 
  1541.         ($tag !~ /\AContent-$StandardFields\Z/io)) {
  1542.         $head->delete($tag);
  1543.         }
  1544.     }
  1545.     }
  1546.  
  1547.     ### What to do with the "Content-Length" MIME field?
  1548.     if ($o_length eq 'COMPUTE') {        ### Compute the content length...
  1549.     my $content_length = '';
  1550.  
  1551.     ### We don't have content-lengths in multiparts...
  1552.     if ($self->is_multipart) {           ### multipart...
  1553.         $head->delete('Content-length');
  1554.     }
  1555.     else {                               ### singlepart...
  1556.  
  1557.         ### Get the encoded body, if we don't have it already:
  1558.         unless ($ENCBODY) {
  1559.         $ENCBODY = tmpopen() || die "can't open tmpfile";
  1560.         $self->print_body($ENCBODY);    ### write encoded to tmpfile
  1561.         }
  1562.         
  1563.         ### Analyse it:
  1564.         $ENCBODY->seek(0,2);                ### fast-forward
  1565.         $content_length = $ENCBODY->tell;   ### get encoded length
  1566.         $ENCBODY->seek(0,0);                ### rewind     
  1567.         
  1568.         ### Remember:   
  1569.         $self->head->replace('Content-length', $content_length);    
  1570.     }
  1571.     }
  1572.     elsif ($o_length eq 'ERASE') {         ### Erase the content-length...
  1573.     $head->delete('Content-length');
  1574.     }
  1575.  
  1576.     ### Done with everything for us!
  1577.     undef($ENCBODY);
  1578.  
  1579.     ### Recurse:
  1580.     my $part;
  1581.     foreach $part ($self->parts) { $part->sync_headers($opts) or return undef }
  1582.     1;
  1583. }
  1584.  
  1585. #------------------------------
  1586.  
  1587. =item tidy_body
  1588.  
  1589. I<Instance method, override.>
  1590. Currently unimplemented for MIME messages.  Does nothing, returns false.
  1591.  
  1592. =cut
  1593.  
  1594. sub tidy_body {
  1595.     usage "MIME::Entity::tidy_body currently does nothing";
  1596.     0;
  1597. }
  1598.  
  1599. =back
  1600.  
  1601. =cut
  1602.  
  1603.  
  1604.  
  1605.  
  1606.  
  1607. #==============================
  1608.  
  1609. =head2 Output
  1610.  
  1611. =over 4
  1612.  
  1613. =cut
  1614.  
  1615. #------------------------------
  1616.  
  1617. =item dump_skeleton [FILEHANDLE]
  1618.  
  1619. I<Instance method.>
  1620. Dump the skeleton of the entity to the given FILEHANDLE, or
  1621. to the currently-selected one if none given.
  1622.  
  1623. Each entity is output with an appropriate indentation level,
  1624. the following selection of attributes:
  1625.  
  1626.     Content-type: multipart/mixed
  1627.     Effective-type: multipart/mixed
  1628.     Body-file: NONE
  1629.     Subject: Hey there!
  1630.     Num-parts: 2
  1631.  
  1632. This is really just useful for debugging purposes; I make no guarantees
  1633. about the consistency of the output format over time.
  1634.  
  1635. =cut
  1636.  
  1637. sub dump_skeleton {
  1638.     my ($self, $fh, $indent) = @_;
  1639.     $fh or $fh = select;
  1640.     defined($indent) or $indent = 0;
  1641.     my $ind = '    ' x $indent;
  1642.     my $part;
  1643.     no strict 'refs';
  1644.  
  1645.  
  1646.     ### The content type:
  1647.     print $fh $ind,"Content-type: ",   ($self->mime_type||'UNKNOWN'),"\n";
  1648.     print $fh $ind,"Effective-type: ", ($self->effective_type||'UNKNOWN'),"\n";
  1649.  
  1650.     ### The name of the file containing the body (if any!):
  1651.     my $path = ($self->bodyhandle ? $self->bodyhandle->path : undef);
  1652.     print $fh $ind, "Body-file: ", ($path || 'NONE'), "\n";
  1653.  
  1654.     ### The recommended file name (thanks to Allen Campbell):
  1655.     my $filename = $self->head->recommended_filename;
  1656.     print $fh $ind, "Recommended-filename: ", $filename, "\n" if ($filename);
  1657.  
  1658.     ### The subject (note: already a newline if 2.x!)
  1659.     my $subj = $self->head->get('subject',0);
  1660.     defined($subj) or $subj = '';
  1661.     chomp($subj);
  1662.     print $fh $ind, "Subject: $subj\n" if $subj;
  1663.  
  1664.     ### The parts:
  1665.     my @parts = $self->parts;
  1666.     print $fh $ind, "Num-parts: ", int(@parts), "\n" if @parts;
  1667.     print $fh $ind, "--\n";
  1668.     foreach $part (@parts) {
  1669.     $part->dump_skeleton($fh, $indent+1);
  1670.     }
  1671. }
  1672.  
  1673. #------------------------------
  1674.  
  1675. =item print [OUTSTREAM]
  1676.  
  1677. I<Instance method, override.>
  1678. Print the entity to the given OUTSTREAM, or to the currently-selected
  1679. filehandle if none given.  OUTSTREAM can be a filehandle, or any object
  1680. that reponds to a print() message.
  1681.  
  1682. The entity is output as a valid MIME stream!  This means that the
  1683. header is always output first, and the body data (if any) will be
  1684. encoded if the header says that it should be.
  1685. For example, your output may look like this:
  1686.  
  1687.     Subject: Greetings
  1688.     Content-transfer-encoding: base64
  1689.  
  1690.     SGkgdGhlcmUhCkJ5ZSB0aGVyZSEK
  1691.  
  1692. I<If this entity has MIME type "multipart/*",>
  1693. the preamble, parts, and epilogue are all output with appropriate
  1694. boundaries separating each.
  1695. Any bodyhandle is ignored:
  1696.  
  1697.     Content-type: multipart/mixed; boundary="*----*"
  1698.     Content-transfer-encoding: 7bit
  1699.  
  1700.     [Preamble]
  1701.     --*----*
  1702.     [Entity: Part 0]
  1703.     --*----*
  1704.     [Entity: Part 1]
  1705.     --*----*--
  1706.     [Epilogue]
  1707.  
  1708. I<If this entity has a single-part MIME type with no attached parts,>
  1709. then we're looking at a normal singlepart entity: the body is output
  1710. according to the encoding specified by the header.
  1711. If no body exists, a warning is output and the body is treated as empty:
  1712.  
  1713.     Content-type: image/gif
  1714.     Content-transfer-encoding: base64
  1715.  
  1716.     [Encoded body]
  1717.  
  1718. I<If this entity has a single-part MIME type but it also has parts,>
  1719. then we're probably looking at a "re-parsed" singlepart, usually one
  1720. of type C<message/*> (you can get entities like this if you set the
  1721. C<parse_nested_messages(NEST)> option on the parser to true).
  1722. In this case, the parts are output with single blank lines separating each,
  1723. and any bodyhandle is ignored:
  1724.  
  1725.     Content-type: message/rfc822
  1726.     Content-transfer-encoding: 7bit
  1727.  
  1728.     [Entity: Part 0]
  1729.  
  1730.     [Entity: Part 1]
  1731.  
  1732. In all cases, when outputting a "part" of the entity, this method
  1733. is invoked recursively.
  1734.  
  1735. B<Note:> the output is very likely I<not> going to be identical
  1736. to any input you parsed to get this entity.  If you're building
  1737. some sort of email handler, it's up to you to save this information.
  1738.  
  1739. =cut
  1740.  
  1741. use Symbol;
  1742. sub print {
  1743.     my ($self, $out) = @_;
  1744.     $out = select if @_ < 2;
  1745.     $out = Symbol::qualify($out,scalar(caller)) unless ref($out);
  1746.     $out = wraphandle($out);             ### get a printable output
  1747.     
  1748.     $self->print_header($out);   ### the header
  1749.     $out->print("\n");
  1750.     $self->print_body($out);     ### the "stuff after the header"
  1751. }
  1752.  
  1753. #------------------------------
  1754.  
  1755. =item print_body [OUTSTREAM]
  1756.  
  1757. I<Instance method, override.>
  1758. Print the body of the entity to the given OUTSTREAM, or to the
  1759. currently-selected filehandle if none given.  OUTSTREAM can be a
  1760. filehandle, or any object that reponds to a print() message.
  1761.  
  1762. The body is output for inclusion in a valid MIME stream; this means
  1763. that the body data will be encoded if the header says that it should be.
  1764.  
  1765. B<Note:> by "body", we mean "the stuff following the header".
  1766. A printed multipart body includes the printed representations of its subparts.
  1767.  
  1768. B<Note:> The body is I<stored> in an un-encoded form; however, the idea is that
  1769. the transfer encoding is used to determine how it should be I<output.>
  1770. This means that the C<print()> method is always guaranteed to get you
  1771. a sendmail-ready stream whose body is consistent with its head.
  1772. If you want the I<raw body data> to be output, you can either read it from
  1773. the bodyhandle yourself, or use:
  1774.  
  1775.     $ent->bodyhandle->print($outstream);
  1776.  
  1777. which uses read() calls to extract the information, and thus will
  1778. work with both text and binary bodies.
  1779.  
  1780. B<Warning:> Please supply an OUTSTREAM.  This override method differs
  1781. from Mail::Internet's behavior, which outputs to the STDOUT if no
  1782. filehandle is given: this may lead to confusion.
  1783.  
  1784. =cut
  1785.  
  1786. sub print_body {
  1787.     my ($self, $out) = @_;
  1788.     $out = wraphandle($out || select);             ### get a printable output
  1789.     my ($type) = split '/', lc($self->mime_type);  ### handle by MIME type
  1790.  
  1791.     ### Multipart...
  1792.     if ($type eq 'multipart') {
  1793.     my $boundary = $self->head->multipart_boundary; 
  1794.  
  1795.     ### Preamble:
  1796.     my $preamble = join('', @{ $self->preamble || $DefPreamble });
  1797.     $out->print("$preamble\n") if ($preamble ne '');
  1798.  
  1799.     ### Parts:
  1800.     my $part;
  1801.     foreach $part ($self->parts) {
  1802.         $out->print("--$boundary\n");
  1803.         $part->print($out);
  1804.         $out->print("\n");           ### needed for next delim/close
  1805.     }
  1806.     $out->print("--$boundary--\n");
  1807.  
  1808.     ### Epilogue:
  1809.     my $epilogue = join('', @{ $self->epilogue || $DefEpilogue });
  1810.     if ($epilogue ne '') {
  1811.         $out->print($epilogue);
  1812.         $out->print("\n") if ($epilogue !~ /\n\Z/);  ### be nice
  1813.     }
  1814.     }
  1815.  
  1816.     ### Singlepart type with parts...
  1817.     ###    This makes $ent->print handle message/rfc822 bodies
  1818.     ###    when parse_nested_messages('NEST') is on [idea by Marc Rouleau].
  1819.     elsif ($self->parts) {
  1820.     my $need_sep = 0;
  1821.     my $part;
  1822.     foreach $part ($self->parts) {
  1823.         $out->print("\n\n") if $need_sep++;
  1824.         $part->print($out);
  1825.     }
  1826.     }
  1827.  
  1828.     ### Singlepart type, or no parts: output body...
  1829.     else {                     
  1830.     $self->bodyhandle ? $self->print_bodyhandle($out)
  1831.                       : whine "missing body; treated as empty";
  1832.     }
  1833.     1;
  1834. }
  1835.  
  1836. #------------------------------
  1837. #
  1838. # print_bodyhandle
  1839. #
  1840. # Instance method, unpublicized.  Print just the bodyhandle, *encoded*.
  1841. #
  1842. # WARNING: $self->print_bodyhandle() != $self->bodyhandle->print()!
  1843. # The former encodes, and the latter does not! 
  1844. #
  1845. sub print_bodyhandle {
  1846.     my ($self, $out) = @_;
  1847.     $out = wraphandle($out || select);             ### get a printable output
  1848.  
  1849.     ### Get the encoding, defaulting to "binary" if unsupported:
  1850.     my $encoding = ($self->head->mime_encoding || 'binary');
  1851.     my $decoder = best MIME::Decoder $encoding;
  1852.     $decoder->head($self->head);      ### associate with head, if any
  1853.  
  1854.     ### Output the body:
  1855.     my $IO = $self->open("r")     || die "open body: $!";
  1856.     $decoder->encode($IO, $out)   || return error "encoding failed";
  1857.     $IO->close;
  1858.     1;
  1859. }
  1860.  
  1861. #------------------------------
  1862.  
  1863. =item print_header [OUTSTREAM]
  1864.  
  1865. I<Instance method, inherited.>
  1866. Output the header to the given OUTSTREAM.  You really should supply
  1867. the OUTSTREAM.
  1868.  
  1869. =cut
  1870.  
  1871. ### Inherited.
  1872.  
  1873. #------------------------------
  1874.  
  1875. =item stringify
  1876.  
  1877. I<Instance method.>
  1878. Return the entity as a string, exactly as C<print> would print it.
  1879. The body will be encoded as necessary, and will contain any subparts.
  1880. You can also use C<as_string()>.
  1881.  
  1882. =cut
  1883.  
  1884. sub stringify {
  1885.     my $str = '';
  1886.     shift->print(new IO::Scalar \$str);
  1887.     $str;    
  1888. }
  1889. sub as_string { shift->stringify };      ### silent BC
  1890.  
  1891. #------------------------------
  1892.  
  1893. =item stringify_body
  1894.  
  1895. I<Instance method.>
  1896. Return the I<encoded> message body as a string, exactly as C<print_body>
  1897. would print it.  You can also use C<body_as_string()>.
  1898.  
  1899. If you want the I<unencoded> body, and you are dealing with a
  1900. singlepart message (like a "text/plain"), use C<bodyhandle()> instead:
  1901.  
  1902.     if ($ent->bodyhandle) {
  1903.     $unencoded_data = $ent->bodyhandle->as_string;
  1904.     }
  1905.     else {
  1906.     ### this message has no body data (but it might have parts!)
  1907.     }
  1908.  
  1909. =cut
  1910.  
  1911. sub stringify_body {
  1912.     my $str = '';
  1913.     shift->print_body(new IO::Scalar \$str);
  1914.     $str;    
  1915. }
  1916. sub body_as_string { shift->stringify_body }
  1917.  
  1918. #------------------------------
  1919. #
  1920. # stringify_bodyhandle
  1921. #
  1922. # Instance method, unpublicized.  Stringify just the bodyhandle.
  1923.  
  1924. sub stringify_bodyhandle {
  1925.     my $str = '';
  1926.     shift->print_bodyhandle(new IO::Scalar \$str);
  1927.     $str;    
  1928. }
  1929. sub bodyhandle_as_string { shift->stringify_bodyhandle }
  1930.  
  1931. #------------------------------
  1932.  
  1933. =item stringify_header
  1934.  
  1935. I<Instance method.>
  1936. Return the header as a string, exactly as C<print_header> would print it.
  1937. You can also use C<header_as_string()>.
  1938.  
  1939. =cut
  1940.  
  1941. sub stringify_header {
  1942.     shift->head->stringify;
  1943. }
  1944. sub header_as_string { shift->stringify_header }
  1945.  
  1946.  
  1947.  
  1948. __END__
  1949. 1;
  1950.   
  1951. #------------------------------
  1952.  
  1953. =back
  1954.  
  1955. =head1 NOTES
  1956.  
  1957. =head2 Under the hood
  1958.  
  1959. A B<MIME::Entity> is composed of the following elements:
  1960.  
  1961. =over 4
  1962.  
  1963. =item *
  1964.  
  1965. A I<head>, which is a reference to a MIME::Head object
  1966. containing the header information.
  1967.  
  1968. =item *
  1969.  
  1970. A I<bodyhandle>, which is a reference to a MIME::Body object
  1971. containing the decoded body data.  This is only defined if
  1972. the message is a "singlepart" type:
  1973.  
  1974.     application/*
  1975.     audio/*
  1976.     image/*
  1977.     text/*
  1978.     video/*
  1979.  
  1980. =item *
  1981.  
  1982. An array of I<parts>, where each part is a MIME::Entity object.
  1983. The number of parts will only be nonzero if the content-type
  1984. is I<not> one of the "singlepart" types:
  1985.  
  1986.     message/*        (should have exactly one part)
  1987.     multipart/*      (should have one or more parts)
  1988.  
  1989.  
  1990. =back
  1991.  
  1992.  
  1993.  
  1994. =head2 The "two-body problem"
  1995.  
  1996. MIME::Entity and Mail::Internet see message bodies differently,
  1997. and this can cause confusion and some inconvenience.  Sadly, I can't
  1998. change the behavior of MIME::Entity without breaking lots of code already
  1999. out there.  But let's open up the floor for a few questions...
  2000.  
  2001. =over 4
  2002.  
  2003. =item What is the difference between a "message" and an "entity"?
  2004.  
  2005. A B<message> is the actual data being sent or received; usually
  2006. this means a stream of newline-terminated lines.
  2007. An B<entity> is the representation of a message as an object.
  2008.  
  2009. This means that you get a "message" when you print an "entity"
  2010. I<to> a filehandle, and you get an "entity" when you parse a message
  2011. I<from> a filehandle.
  2012.  
  2013.  
  2014. =item What is a message body?
  2015.  
  2016. B<Mail::Internet:>
  2017. The portion of the printed message after the header.
  2018.  
  2019. B<MIME::Entity:>
  2020. The portion of the printed message after the header.
  2021.  
  2022.  
  2023. =item How is a message body stored in an entity?
  2024.  
  2025. B<Mail::Internet:>
  2026. As an array of lines.
  2027.  
  2028. B<MIME::Entity:>
  2029. It depends on the content-type of the message.
  2030. For "container" types (C<multipart/*>, C<message/*>), we store the
  2031. contained entities as an array of "parts", accessed via the C<parts()>
  2032. method, where each part is a complete MIME::Entity.
  2033. For "singlepart" types (C<text/*>, C<image/*>, etc.), the unencoded
  2034. body data is referenced via a MIME::Body object, accessed via
  2035. the C<bodyhandle()> method:
  2036.  
  2037.                       bodyhandle()   parts()
  2038.     Content-type:     returns:       returns:
  2039.     ------------------------------------------------------------
  2040.     application/*     MIME::Body     empty
  2041.     audio/*           MIME::Body     empty
  2042.     image/*           MIME::Body     empty
  2043.     message/*         undef          MIME::Entity list (usually 1)
  2044.     multipart/*       undef          MIME::Entity list (usually >0)
  2045.     text/*            MIME::Body     empty
  2046.     video/*           MIME::Body     empty
  2047.     x-*/*             MIME::Body     empty
  2048.  
  2049. As a special case, C<message/*> is currently ambiguous: depending
  2050. on the parser, a C<message/*> might be treated as a singlepart,
  2051. with a MIME::Body and no parts.  Use bodyhandle() as the final
  2052. arbiter.
  2053.  
  2054.  
  2055. =item What does the body() method return?
  2056.  
  2057. B<Mail::Internet:>
  2058. As an array of lines, ready for sending.
  2059.  
  2060. B<MIME::Entity:>
  2061. As an array of lines, ready for sending.
  2062.  
  2063.  
  2064. =item If an entity has a body, does it have a soul as well?
  2065.  
  2066. The soul does not exist in a corporeal sense, the way the body does;
  2067. it is not a solid [Perl] object.  Rather, it is a virtual object
  2068. which is only visible when you print() an entity to a file... in other
  2069. words, the "soul" it is all that is left after the body is DESTROY'ed.
  2070.  
  2071.  
  2072. =item What's the best way to get at the body data?
  2073.  
  2074. B<Mail::Internet:>
  2075. Use the body() method.
  2076.  
  2077. B<MIME::Entity:>
  2078. Depends on what you want... the I<encoded> data (as it is
  2079. transported), or the I<unencoded> data?  Keep reading...
  2080.  
  2081.  
  2082. =item How do I get the "encoded" body data?
  2083.  
  2084. B<Mail::Internet:>
  2085. Use the body() method.
  2086.  
  2087. B<MIME::Entity:>
  2088. Use the body() method.  You can also use:
  2089.  
  2090.     $entity->print_body()
  2091.     $entity->stringify_body()   ### a.k.a. $entity->body_as_string()
  2092.  
  2093.  
  2094. =item How do I get the "unencoded" body data?
  2095.  
  2096. B<Mail::Internet:>
  2097. Use the body() method.
  2098.  
  2099. B<MIME::Entity:>
  2100. Use the I<bodyhandle()> method!
  2101. If bodyhandle() method returns true, then that value is a
  2102. L<MIME::Body|MIME::Body> which can be used to access the data via
  2103. its open() method.  If bodyhandle() method returns an undefined value,
  2104. then the entity is probably a "container" that has no real body data of
  2105. its own (e.g., a "multipart" message): in this case, you should access
  2106. the components via the parts() method.  Like this:
  2107.  
  2108.     if ($bh = $entity->bodyhandle) {
  2109.     $io = $bh->open;
  2110.     ...access unencoded data via $io->getline or $io->read...
  2111.     $io->close;
  2112.     }
  2113.     else {
  2114.     foreach my $part (@parts) {
  2115.         ...do something with the part...
  2116.     }
  2117.     }
  2118.  
  2119. You can also use:
  2120.  
  2121.     if ($bh = $entity->bodyhandle) {
  2122.     $unencoded_data = $bh->as_string;
  2123.     }
  2124.     else {
  2125.     ...do stuff with the parts...
  2126.     }
  2127.  
  2128.  
  2129. =item What does the body() method return?
  2130.  
  2131. B<Mail::Internet:>
  2132. The transport-encoded message body, as an array of lines.
  2133.  
  2134. B<MIME::Entity:>
  2135. The transport-encoded message body, as an array of lines.
  2136.  
  2137.  
  2138. =item What does print_body() print?
  2139.  
  2140. B<Mail::Internet:>
  2141. Exactly what body() would return to you.
  2142.  
  2143. B<MIME::Entity:>
  2144. Exactly what body() would return to you.
  2145.  
  2146.  
  2147. =item Say I have an entity which might be either singlepart or multipart.
  2148.       How do I print out just "the stuff after the header"?
  2149.  
  2150. B<Mail::Internet:>
  2151. Use print_body().
  2152.  
  2153. B<MIME::Entity:>
  2154. Use print_body().
  2155.  
  2156.  
  2157. =item Why is MIME::Entity so different from Mail::Internet?
  2158.  
  2159. Because MIME streams are expected to have non-textual data...
  2160. possibly, quite a lot of it, such as a tar file.
  2161.  
  2162. Because MIME messages can consist of multiple parts, which are most-easily
  2163. manipulated as MIME::Entity objects themselves.
  2164.  
  2165. Because in the simpler world of Mail::Internet, the data of a message
  2166. and its printed representation are I<identical>... and in the MIME
  2167. world, they're not.
  2168.  
  2169. Because parsing multipart bodies on-the-fly, or formatting multipart
  2170. bodies for output, is a non-trivial task.
  2171.  
  2172.  
  2173. =item This is confusing.  Can the two classes be made more compatible?
  2174.  
  2175. Not easily; their implementations are necessarily quite different.
  2176. Mail::Internet is a simple, efficient way of dealing with a "black box"
  2177. mail message... one whose internal data you don't care much about.
  2178. MIME::Entity, in contrast, cares I<very much> about the message contents:
  2179. that's its job!
  2180.  
  2181. =back
  2182.  
  2183.  
  2184.  
  2185. =head2 Design issues
  2186.  
  2187. =over 4
  2188.  
  2189. =item Some things just can't be ignored
  2190.  
  2191. In multipart messages, the I<"preamble"> is the portion that precedes
  2192. the first encapsulation boundary, and the I<"epilogue"> is the portion
  2193. that follows the last encapsulation boundary.
  2194.  
  2195. According to RFC-1521:
  2196.  
  2197.     There appears to be room for additional information prior
  2198.     to the first encapsulation boundary and following the final
  2199.     boundary.  These areas should generally be left blank, and
  2200.     implementations must ignore anything that appears before the
  2201.     first boundary or after the last one.
  2202.  
  2203.     NOTE: These "preamble" and "epilogue" areas are generally
  2204.     not used because of the lack of proper typing of these parts
  2205.     and the lack of clear semantics for handling these areas at
  2206.     gateways, particularly X.400 gateways.  However, rather than
  2207.     leaving the preamble area blank, many MIME implementations
  2208.     have found this to be a convenient place to insert an
  2209.     explanatory note for recipients who read the message with
  2210.     pre-MIME software, since such notes will be ignored by
  2211.     MIME-compliant software.
  2212.  
  2213. In the world of standards-and-practices, that's the standard.
  2214. Now for the practice:
  2215.  
  2216. I<Some "MIME" mailers may incorrectly put a "part" in the preamble>.
  2217. Since we have to parse over the stuff I<anyway>, in the future I
  2218. I<may> allow the parser option of creating special MIME::Entity objects
  2219. for the preamble and epilogue, with bogus MIME::Head objects.
  2220.  
  2221. For now, though, we're MIME-compliant, so I probably won't change
  2222. how we work.
  2223.  
  2224. =back
  2225.  
  2226.  
  2227. =head1 AUTHOR
  2228.  
  2229. Eryq (F<eryq@zeegee.com>), ZeeGee Software Inc (F<http://www.zeegee.com>).
  2230.  
  2231. All rights reserved.  This program is free software; you can redistribute
  2232. it and/or modify it under the same terms as Perl itself.
  2233.  
  2234.  
  2235. =head1 VERSION
  2236.  
  2237. $Revision: 5.404 $ $Date: 2000/11/06 11:58:53 $
  2238.  
  2239. =cut
  2240.  
  2241. #------------------------------
  2242. 1;
  2243.