1MIME::Entity(3)       User Contributed Perl Documentation      MIME::Entity(3)
2
3
4

NAME

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

SYNOPSIS

9       Before reading further, you should see MIME::Tools to make sure that
10       you understand where this module fits into the grand scheme of things.
11       Go on, do it now.  I'll wait.
12
13       Ready?  Ok...
14
15           ### Create an entity:
16           $top = MIME::Entity->build(From    => 'me@myhost.com',
17                                      To      => 'you@yourhost.com',
18                                      Subject => "Hello, nurse!",
19                                      Data    => \@my_message);
20
21           ### Attach stuff to it:
22           $top->attach(Path     => $gif_path,
23                        Type     => "image/gif",
24                        Encoding => "base64");
25
26           ### Sign it:
27           $top->sign;
28
29           ### Output it:
30           $top->print(\*STDOUT);
31

DESCRIPTION

33       A subclass of Mail::Internet.
34
35       This package provides a class for representing MIME message entities,
36       as specified in RFCs 2045, 2046, 2047, 2048 and 2049.
37

EXAMPLES

39   Construction examples
40       Create a document for an ordinary 7-bit ASCII text file (lots of stuff
41       is defaulted for us):
42
43           $ent = MIME::Entity->build(Path=>"english-msg.txt");
44
45       Create a document for a text file with 8-bit (Latin-1) characters:
46
47           $ent = MIME::Entity->build(Path     =>"french-msg.txt",
48                                      Encoding =>"quoted-printable",
49                                      From     =>'jean.luc@inria.fr',
50                                      Subject  =>"C'est bon!");
51
52       Create a document for a GIF file (the description is completely
53       optional; note that we have to specify content-type and encoding since
54       they're not the default values):
55
56           $ent = MIME::Entity->build(Description => "A pretty picture",
57                                      Path        => "./docs/mime-sm.gif",
58                                      Type        => "image/gif",
59                                      Encoding    => "base64");
60
61       Create a document that you already have the text for, using "Data":
62
63           $ent = MIME::Entity->build(Type        => "text/plain",
64                                      Encoding    => "quoted-printable",
65                                      Data        => ["First line.\n",
66                                                     "Second line.\n",
67                                                     "Last line.\n"]);
68
69       Create a multipart message, with the entire structure given explicitly:
70
71           ### Create the top-level, and set up the mail headers:
72           $top = MIME::Entity->build(Type     => "multipart/mixed",
73                                      From     => 'me@myhost.com',
74                                      To       => 'you@yourhost.com',
75                                      Subject  => "Hello, nurse!");
76
77           ### Attachment #1: a simple text document:
78           $top->attach(Path=>"./testin/short.txt");
79
80           ### Attachment #2: a GIF file:
81           $top->attach(Path        => "./docs/mime-sm.gif",
82                        Type        => "image/gif",
83                        Encoding    => "base64");
84
85           ### Attachment #3: text we'll create with text we have on-hand:
86           $top->attach(Data => $contents);
87
88       Suppose you don't know ahead of time that you'll have attachments?  No
89       problem: you can "attach" to singleparts as well:
90
91           $top = MIME::Entity->build(From    => 'me@myhost.com',
92                                      To      => 'you@yourhost.com',
93                                      Subject => "Hello, nurse!",
94                                      Data    => \@my_message);
95           if ($GIF_path) {
96               $top->attach(Path     => $GIF_path,
97                            Type     => 'image/gif');
98           }
99
100       Copy an entity (headers, parts... everything but external body data):
101
102           my $deepcopy = $top->dup;
103
104   Access examples
105           ### Get the head, a MIME::Head:
106           $head = $ent->head;
107
108           ### Get the body, as a MIME::Body;
109           $bodyh = $ent->bodyhandle;
110
111           ### Get the intended MIME type (as declared in the header):
112           $type = $ent->mime_type;
113
114           ### Get the effective MIME type (in case decoding failed):
115           $eff_type = $ent->effective_type;
116
117           ### Get preamble, parts, and epilogue:
118           $preamble   = $ent->preamble;          ### ref to array of lines
119           $num_parts  = $ent->parts;
120           $first_part = $ent->parts(0);          ### an entity
121           $epilogue   = $ent->epilogue;          ### ref to array of lines
122
123   Manipulation examples
124       Muck about with the body data:
125
126           ### Read the (unencoded) body data:
127           if ($io = $ent->open("r")) {
128               while (defined($_ = $io->getline)) { print $_ }
129               $io->close;
130           }
131
132           ### Write the (unencoded) body data:
133           if ($io = $ent->open("w")) {
134               foreach (@lines) { $io->print($_) }
135               $io->close;
136           }
137
138           ### Delete the files for any external (on-disk) data:
139           $ent->purge;
140
141       Muck about with the signature:
142
143           ### Sign it (automatically removes any existing signature):
144           $top->sign(File=>"$ENV{HOME}/.signature");
145
146           ### Remove any signature within 15 lines of the end:
147           $top->remove_sig(15);
148
149       Muck about with the headers:
150
151           ### Compute content-lengths for singleparts based on bodies:
152           ###   (Do this right before you print!)
153           $entity->sync_headers(Length=>'COMPUTE');
154
155       Muck about with the structure:
156
157           ### If a 0- or 1-part multipart, collapse to a singlepart:
158           $top->make_singlepart;
159
160           ### If a singlepart, inflate to a multipart with 1 part:
161           $top->make_multipart;
162
163       Delete parts:
164
165           ### Delete some parts of a multipart message:
166           my @keep = grep { keep_part($_) } $msg->parts;
167           $msg->parts(\@keep);
168
169   Output examples
170       Print to filehandles:
171
172           ### Print the entire message:
173           $top->print(\*STDOUT);
174
175           ### Print just the header:
176           $top->print_header(\*STDOUT);
177
178           ### Print just the (encoded) body... includes parts as well!
179           $top->print_body(\*STDOUT);
180
181       Stringify... note that "stringify_xx" can also be written
182       "xx_as_string"; the methods are synonymous, and neither form will be
183       deprecated.
184
185       If you set the variable $MIME::Entity::BOUNDARY_DELIMITER to a string,
186       that string will be used as the line-end delimiter on output.  If it is
187       not set, the line ending will be a newline character (\n)
188
189       NOTE that $MIME::Entity::BOUNDARY_DELIMITER only applies to structural
190       parts of the MIME data generated by this package and to the Base64
191       encoded output; if a part internally uses a different line-end
192       delimiter and is output as-is, the line-ending is not changed to match
193       $MIME::Entity::BOUNDARY_DELIMITER.
194
195           ### Stringify the entire message:
196           print $top->stringify;              ### or $top->as_string
197
198           ### Stringify just the header:
199           print $top->stringify_header;       ### or $top->header_as_string
200
201           ### Stringify just the (encoded) body... includes parts as well!
202           print $top->stringify_body;         ### or $top->body_as_string
203
204       Debug:
205
206           ### Output debugging info:
207           $entity->dump_skeleton(\*STDERR);
208

PUBLIC INTERFACE

210   Construction
211       new [SOURCE]
212           Class method.  Create a new, empty MIME entity.  Basically, this
213           uses the Mail::Internet constructor...
214
215           If SOURCE is an ARRAYREF, it is assumed to be an array of lines
216           that will be used to create both the header and an in-core body.
217
218           Else, if SOURCE is defined, it is assumed to be a filehandle from
219           which the header and in-core body is to be read.
220
221           Note: in either case, the body will not be parsed: merely read!
222
223       add_part ENTITY, [OFFSET]
224           Instance method.  Assuming we are a multipart message, add a body
225           part (a MIME::Entity) to the array of body parts.  Returns the part
226           that was just added.
227
228           If OFFSET is positive, the new part is added at that offset from
229           the beginning of the array of parts.  If it is negative, it counts
230           from the end of the array.  (An INDEX of -1 will place the new part
231           at the very end of the array, -2 will place it as the penultimate
232           item in the array, etc.)  If OFFSET is not given, the new part is
233           added to the end of the array.  Thanks to Jason L Tibbitts III for
234           providing support for OFFSET.
235
236           Warning: in general, you only want to attach parts to entities with
237           a content-type of "multipart/*").
238
239       attach PARAMHASH
240           Instance method.  The real quick-and-easy way to create multipart
241           messages.  The PARAMHASH is used to "build" a new entity; this
242           method is basically equivalent to:
243
244               $entity->add_part(ref($entity)->build(PARAMHASH, Top=>0));
245
246           Note: normally, you attach to multipart entities; however, if you
247           attach something to a singlepart (like attaching a GIF to a text
248           message), the singlepart will be coerced into a multipart
249           automatically.
250
251       build PARAMHASH
252           Class/instance method.  A quick-and-easy catch-all way to create an
253           entity.  Use it like this to build a "normal" single-part entity:
254
255              $ent = MIME::Entity->build(Type     => "image/gif",
256                                         Encoding => "base64",
257                                         Path     => "/path/to/xyz12345.gif",
258                                         Filename => "saveme.gif",
259                                         Disposition => "attachment");
260
261           And like this to build a "multipart" entity:
262
263              $ent = MIME::Entity->build(Type     => "multipart/mixed",
264                                         Boundary => "---1234567");
265
266           A minimal MIME header will be created.  If you want to add or
267           modify any header fields afterwards, you can of course do so via
268           the underlying head object... but hey, there's now a prettier
269           syntax!
270
271              $ent = MIME::Entity->build(Type          =>"multipart/mixed",
272                                         From          => $myaddr,
273                                         Subject       => "Hi!",
274                                         'X-Certified' => ['SINED',
275                                                           'SEELED',
276                                                           'DELIVERED']);
277
278           Normally, an "X-Mailer" header field is output which contains this
279           toolkit's name and version (plus this module's RCS version).  This
280           will allow any bad MIME we generate to be traced back to us.  You
281           can of course overwrite that header with your own:
282
283              $ent = MIME::Entity->build(Type        => "multipart/mixed",
284                                         'X-Mailer'  => "myprog 1.1");
285
286           Or remove it entirely:
287
288              $ent = MIME::Entity->build(Type       => "multipart/mixed",
289                                         'X-Mailer' => undef);
290
291           OK, enough hype.  The parameters are:
292
293           (FIELDNAME)
294               Any field you want placed in the message header, taken from the
295               standard list of header fields (you don't need to worry about
296               case):
297
298                   Bcc           Encrypted     Received      Sender
299                   Cc            From          References    Subject
300                   Comments      Keywords      Reply-To      To
301                   Content-*     Message-ID    Resent-*      X-*
302                   Date          MIME-Version  Return-Path
303                                 Organization
304
305               To give experienced users some veto power, these fields will be
306               set after the ones I set... so be careful: don't set any MIME
307               fields (like "Content-type") unless you know what you're doing!
308
309               To specify a fieldname that's not in the above list, even one
310               that's identical to an option below, just give it with a
311               trailing ":", like "My-field:".  When in doubt, that always
312               signals a mail field (and it sort of looks like one too).
313
314           Boundary
315               Multipart entities only. Optional.  The boundary string.  As
316               per RFC-2046, it must consist only of the characters
317               "[0-9a-zA-Z'()+_,-./:=?]" and space (you'll be warned, and your
318               boundary will be ignored, if this is not the case).  If you
319               omit this, a random string will be chosen... which is probably
320               safer.
321
322           Charset
323               Optional.  The character set.
324
325           Data
326               Single-part entities only. Optional.  An alternative to Path
327               (q.v.): the actual data, either as a scalar or an array
328               reference (whose elements are joined together to make the
329               actual scalar).  The body is opened on the data using
330               MIME::Body::InCore.
331
332               Note that for text parts, the Data scalar or array is assumed
333               to be encoded in a suitable character encoding (as if by
334               "Encode::encode") rather than a native Perl string.  The
335               encoding you use must, of course, match the "charset" option of
336               the "MIME-Type" header.
337
338           Description
339               Optional.  The text of the content-description.  If you don't
340               specify it, the field is not put in the header.
341
342           Disposition
343               Optional.  The basic content-disposition ("attachment" or
344               "inline").  If you don't specify it, it defaults to "inline"
345               for backwards compatibility.  Thanks to Kurt Freytag for
346               suggesting this feature.
347
348           Encoding
349               Optional.  The content-transfer-encoding.  If you don't specify
350               it, a reasonable default is put in.  You can also give the
351               special value '-SUGGEST', to have it chosen for you in a heavy-
352               duty fashion which scans the data itself.
353
354           Filename
355               Single-part entities only. Optional.  The recommended filename.
356               Overrides any name extracted from "Path".  The information is
357               stored both the deprecated (content-type) and preferred
358               (content-disposition) locations.  If you explicitly want to
359               avoid a recommended filename (even when Path is used), supply
360               this as empty or undef.
361
362           Id  Optional.  Set the content-id.
363
364           Path
365               Single-part entities only. Optional.  The path to the file to
366               attach.  The body is opened on that file using
367               MIME::Body::File.
368
369           Top Optional.  Is this a top-level entity?  If so, it must sport a
370               MIME-Version.  The default is true.  (NB: look at how
371               "attach()" uses it.)
372
373           Type
374               Optional.  The basic content-type ("text/plain", etc.).  If you
375               don't specify it, it defaults to "text/plain" as per RFC 2045.
376               Do yourself a favor: put it in.
377
378       dup Instance method.  Duplicate the entity.  Does a deep, recursive
379           copy, but beware: external data in bodyhandles is not copied to new
380           files!  Changing the data in one entity's data file, or purging
381           that entity, will affect its duplicate.  Entities with in-core data
382           probably need not worry.
383
384   Access
385       body [VALUE]
386           Instance method.  Get the encoded (transport-ready) body, as an
387           array of lines.  Returns an array reference.  Each array entry is a
388           newline-terminated line.
389
390           This is a read-only data structure: changing its contents will have
391           no effect.  Its contents are identical to what is printed by
392           print_body().
393
394           Provided for compatibility with Mail::Internet, so that methods
395           like "smtpsend()" will work.  Note however that if VALUE is given,
396           a fatal exception is thrown, since you cannot use this method to
397           set the lines of the encoded message.
398
399           If you want the raw (unencoded) body data, use the bodyhandle()
400           method to get and use a MIME::Body.  The content-type of the entity
401           will tell you whether that body is best read as text (via
402           getline()) or raw data (via read()).
403
404       bodyhandle [VALUE]
405           Instance method.  Get or set an abstract object representing the
406           body of the message.  The body holds the decoded message data.
407
408           Note that not all entities have bodies!  An entity will have either
409           a body or parts: not both.  This method will only return an object
410           if this entity can have a body; otherwise, it will return
411           undefined.  Whether-or-not a given entity can have a body is
412           determined by (1) its content type, and (2) whether-or-not the
413           parser was told to extract nested messages:
414
415               Type:        | Extract nested? | bodyhandle() | parts()
416               -----------------------------------------------------------------------
417               multipart/*  | -               | undef        | 0 or more MIME::Entity
418               message/*    | true            | undef        | 0 or 1 MIME::Entity
419               message/*    | false           | MIME::Body   | empty list
420               (other)      | -               | MIME::Body   | empty list
421
422           If "VALUE" is not given, the current bodyhandle is returned, or
423           undef if the entity cannot have a body.
424
425           If "VALUE" is given, the bodyhandle is set to the new value, and
426           the previous value is returned.
427
428           See "parts" for more info.
429
430       effective_type [MIMETYPE]
431           Instance method.  Set/get the effective MIME type of this entity.
432           This is usually identical to the actual (or defaulted) MIME type,
433           but in some cases it differs.  For example, from RFC-2045:
434
435              Any entity with an unrecognized Content-Transfer-Encoding must be
436              treated as if it has a Content-Type of "application/octet-stream",
437              regardless of what the Content-Type header field actually says.
438
439           Why? because if we can't decode the message, then we have to take
440           the bytes as-is, in their (unrecognized) encoded form.  So the
441           message ceases to be a "text/foobar" and becomes a bunch of
442           undecipherable bytes -- in other words, an
443           "application/octet-stream".
444
445           Such an entity, if parsed, would have its effective_type() set to
446           "application/octet_stream", although the mime_type() and the
447           contents of the header would remain the same.
448
449           If there is no effective type, the method just returns what
450           mime_type() would.
451
452           Warning: the effective type is "sticky"; once set, that
453           effective_type() will always be returned even if the conditions
454           that necessitated setting the effective type become no longer true.
455
456       epilogue [LINES]
457           Instance method.  Get/set the text of the epilogue, as an array of
458           newline-terminated LINES.  Returns a reference to the array of
459           lines, or undef if no epilogue exists.
460
461           If there is a epilogue, it is output when printing this entity;
462           otherwise, a default epilogue is used.  Setting the epilogue to
463           undef (not []!) causes it to fallback to the default.
464
465       head [VALUE]
466           Instance method.  Get/set the head.
467
468           If there is no VALUE given, returns the current head.  If none
469           exists, an empty instance of MIME::Head is created, set, and
470           returned.
471
472           Note: This is a patch over a problem in Mail::Internet, which
473           doesn't provide a method for setting the head to some given object.
474
475       is_multipart
476           Instance method.  Does this entity's effective MIME type indicate
477           that it's a multipart entity?  Returns undef (false) if the answer
478           couldn't be determined, 0 (false) if it was determined to be false,
479           and true otherwise.  Note that this says nothing about whether or
480           not parts were extracted.
481
482           NOTE: we switched to effective_type so that multiparts with bad or
483           missing boundaries could be coerced to an effective type of
484           "application/x-unparseable-multipart".
485
486       mime_type
487           Instance method.  A purely-for-convenience method.  This simply
488           relays the request to the associated MIME::Head object.  If there
489           is no head, returns undef in a scalar context and the empty array
490           in a list context.
491
492           Before you use this, consider using effective_type() instead,
493           especially if you obtained the entity from a MIME::Parser.
494
495       open READWRITE
496           Instance method.  A purely-for-convenience method.  This simply
497           relays the request to the associated MIME::Body object (see
498           MIME::Body::open()).  READWRITE is either 'r' (open for read) or
499           'w' (open for write).
500
501           If there is no body, returns false.
502
503       parts
504       parts INDEX
505       parts ARRAYREF
506           Instance method.  Return the MIME::Entity objects which are the sub
507           parts of this entity (if any).
508
509           If no argument is given, returns the array of all sub parts,
510           returning the empty array if there are none (e.g., if this is a
511           single part message, or a degenerate multipart).  In a scalar
512           context, this returns you the number of parts.
513
514           If an integer INDEX is given, return the INDEXed part, or undef if
515           it doesn't exist.
516
517           If an ARRAYREF to an array of parts is given, then this method sets
518           the parts to a copy of that array, and returns the parts.  This can
519           be used to delete parts, as follows:
520
521               ### Delete some parts of a multipart message:
522               $msg->parts([ grep { keep_part($_) } $msg->parts ]);
523
524           Note: for multipart messages, the preamble and epilogue are not
525           considered parts.  If you need them, use the "preamble()" and
526           "epilogue()" methods.
527
528           Note: there are ways of parsing with a MIME::Parser which cause
529           certain message parts (such as those of type "message/rfc822") to
530           be "reparsed" into pseudo-multipart entities.  You should read the
531           documentation for those options carefully: it is possible for a
532           diddled entity to not be multipart, but still have parts attached
533           to it!
534
535           See "bodyhandle" for a discussion of parts vs. bodies.
536
537       parts_DFS
538           Instance method.  Return the list of all MIME::Entity objects
539           included in the entity, starting with the entity itself, in depth-
540           first-search order.  If the entity has no parts, it alone will be
541           returned.
542
543           Thanks to Xavier Armengou for suggesting this method.
544
545       preamble [LINES]
546           Instance method.  Get/set the text of the preamble, as an array of
547           newline-terminated LINES.  Returns a reference to the array of
548           lines, or undef if no preamble exists (e.g., if this is a single-
549           part entity).
550
551           If there is a preamble, it is output when printing this entity;
552           otherwise, a default preamble is used.  Setting the preamble to
553           undef (not []!) causes it to fallback to the default.
554
555   Manipulation
556       make_multipart [SUBTYPE], OPTSHASH...
557           Instance method.  Force the entity to be a multipart, if it isn't
558           already.  We do this by replacing the original [singlepart] entity
559           with a new multipart that has the same non-MIME headers ("From",
560           "Subject", etc.), but all-new MIME headers ("Content-type", etc.).
561           We then create a copy of the original singlepart, strip out the
562           non-MIME headers from that, and make it a part of the new
563           multipart.  So this:
564
565               From: me
566               To: you
567               Content-type: text/plain
568               Content-length: 12
569
570               Hello there!
571
572           Becomes something like this:
573
574               From: me
575               To: you
576               Content-type: multipart/mixed; boundary="----abc----"
577
578               ------abc----
579               Content-type: text/plain
580               Content-length: 12
581
582               Hello there!
583               ------abc------
584
585           The actual type of the new top-level multipart will be
586           "multipart/SUBTYPE" (default SUBTYPE is "mixed").
587
588           Returns 'DONE'    if we really did inflate a singlepart to a
589           multipart.  Returns 'ALREADY' (and does nothing) if entity is
590           already multipart and Force was not chosen.
591
592           If OPTSHASH contains Force=>1, then we always bump the top-level's
593           content and content-headers down to a subpart of this entity, even
594           if this entity is already a multipart.  This is apparently of use
595           to people who are tweaking messages after parsing them.
596
597       make_singlepart
598           Instance method.  If the entity is a multipart message with one
599           part, this tries hard to rewrite it as a singlepart, by replacing
600           the content (and content headers) of the top level with those of
601           the part.  Also crunches 0-part multiparts into singleparts.
602
603           Returns 'DONE'    if we really did collapse a multipart to a
604           singlepart.  Returns 'ALREADY' (and does nothing) if entity is
605           already a singlepart.  Returns '0'       (and does nothing) if it
606           can't be made into a singlepart.
607
608       purge
609           Instance method.  Recursively purge (e.g., unlink) all external
610           (e.g., on-disk) body parts in this message.  See
611           MIME::Body::purge() for details.
612
613           Note: this does not delete the directories that those body parts
614           are contained in; only the actual message data files are deleted.
615           This is because some parsers may be customized to create
616           intermediate directories while others are not, and it's impossible
617           for this class to know what directories are safe to remove.  Only
618           your application program truly knows that.
619
620           If you really want to "clean everything up", one good way is to use
621           "MIME::Parser::file_under()", and then do this before parsing your
622           next message:
623
624               $parser->filer->purge();
625
626           I wouldn't attempt to read those body files after you do this, for
627           obvious reasons.  As of MIME-tools 4.x, each body's path is
628           undefined after this operation.  I warned you I might do this;
629           truly I did.
630
631           Thanks to Jason L. Tibbitts III for suggesting this method.
632
633       remove_sig [NLINES]
634           Instance method, override.  Attempts to remove a user's signature
635           from the body of a message.
636
637           It does this by looking for a line matching "/^-- $/" within the
638           last "NLINES" of the message.  If found then that line and all
639           lines after it will be removed. If "NLINES" is not given, a default
640           value of 10 will be used.  This would be of most use in auto-reply
641           scripts.
642
643           For MIME entity, this method is reasonably cautious: it will only
644           attempt to un-sign a message with a content-type of "text/*".
645
646           If you send remove_sig() to a multipart entity, it will relay it to
647           the first part (the others usually being the "attachments").
648
649           Warning: currently slurps the whole message-part into core as an
650           array of lines, so you probably don't want to use this on extremely
651           long messages.
652
653           Returns truth on success, false on error.
654
655       sign PARAMHASH
656           Instance method, override.  Append a signature to the message.  The
657           params are:
658
659           Attach
660               Instead of appending the text, add it to the message as an
661               attachment.  The disposition will be "inline", and the
662               description will indicate that it is a signature.  The default
663               behavior is to append the signature to the text of the message
664               (or the text of its first part if multipart).  MIME-specific;
665               new in this subclass.
666
667           File
668               Use the contents of this file as the signature.  Fatal error if
669               it can't be read.  As per superclass method.
670
671           Force
672               Sign it even if the content-type isn't "text/*".  Useful for
673               non-standard types like "x-foobar", but be careful!  MIME-
674               specific; new in this subclass.
675
676           Remove
677               Normally, we attempt to strip out any existing signature.  If
678               true, this gives us the NLINES parameter of the remove_sig
679               call.  If zero but defined, tells us not to remove any existing
680               signature.  If undefined, removal is done with the default of
681               10 lines.  New in this subclass.
682
683           Signature
684               Use this text as the signature.  You can supply it as either a
685               scalar, or as a ref to an array of newline-terminated scalars.
686               As per superclass method.
687
688           For MIME messages, this method is reasonably cautious: it will only
689           attempt to sign a message with a content-type of "text/*", unless
690           "Force" is specified.
691
692           If you send this message to a multipart entity, it will relay it to
693           the first part (the others usually being the "attachments").
694
695           Warning: currently slurps the whole message-part into core as an
696           array of lines, so you probably don't want to use this on extremely
697           long messages.
698
699           Returns true on success, false otherwise.
700
701       suggest_encoding
702           Instance method.  Based on the effective content type, return a
703           good suggested encoding.
704
705           "text" and "message" types have their bodies scanned line-by-line
706           for 8-bit characters and long lines; lack of either means that the
707           message is 7bit-ok.  Other types are chosen independent of their
708           body:
709
710               Major type:      7bit ok?    Suggested encoding:
711               -----------------------------------------------------------
712               text             yes         7bit
713               text             no          quoted-printable
714               message          yes         7bit
715               message          no          binary
716               multipart        *           binary (in case some parts are bad)
717               image, etc...    *           base64
718
719       sync_headers OPTIONS
720           Instance method.  This method does a variety of activities which
721           ensure that the MIME headers of an entity "tree" are in-synch with
722           the body parts they describe.  It can be as expensive an operation
723           as printing if it involves pre-encoding the body parts; however,
724           the aim is to produce fairly clean MIME.  You will usually only
725           need to invoke this if processing and re-sending MIME from an
726           outside source.
727
728           The OPTIONS is a hash, which describes what is to be done.
729
730           Length
731               One of the "official unofficial" MIME fields is "Content-
732               Length".  Normally, one doesn't care a whit about this field;
733               however, if you are preparing output destined for HTTP, you
734               may.  The value of this option dictates what will be done:
735
736               COMPUTE means to set a "Content-Length" field for every non-
737               multipart part in the entity, and to blank that field out for
738               every multipart part in the entity.
739
740               ERASE means that "Content-Length" fields will all be blanked
741               out.  This is fast, painless, and safe.
742
743               Any false value (the default) means to take no action.
744
745           Nonstandard
746               Any header field beginning with "Content-" is, according to the
747               RFC, a MIME field.  However, some are non-standard, and may
748               cause problems with certain MIME readers which interpret them
749               in different ways.
750
751               ERASE means that all such fields will be blanked out.  This is
752               done before the Length option (q.v.) is examined and acted
753               upon.
754
755               Any false value (the default) means to take no action.
756
757           Returns a true value if everything went okay, a false value
758           otherwise.
759
760       tidy_body
761           Instance method, override.  Currently unimplemented for MIME
762           messages.  Does nothing, returns false.
763
764   Output
765       dump_skeleton [FILEHANDLE]
766           Instance method.  Dump the skeleton of the entity to the given
767           FILEHANDLE, or to the currently-selected one if none given.
768
769           Each entity is output with an appropriate indentation level, the
770           following selection of attributes:
771
772               Content-type: multipart/mixed
773               Effective-type: multipart/mixed
774               Body-file: NONE
775               Subject: Hey there!
776               Num-parts: 2
777
778           This is really just useful for debugging purposes; I make no
779           guarantees about the consistency of the output format over time.
780
781       print [OUTSTREAM]
782           Instance method, override.  Print the entity to the given
783           OUTSTREAM, or to the currently-selected filehandle if none given.
784           OUTSTREAM can be a filehandle, or any object that responds to a
785           print() message.
786
787           The entity is output as a valid MIME stream!  This means that the
788           header is always output first, and the body data (if any) will be
789           encoded if the header says that it should be.  For example, your
790           output may look like this:
791
792               Subject: Greetings
793               Content-transfer-encoding: base64
794
795               SGkgdGhlcmUhCkJ5ZSB0aGVyZSEK
796
797           If this entity has MIME type "multipart/*", the preamble, parts,
798           and epilogue are all output with appropriate boundaries separating
799           each.  Any bodyhandle is ignored:
800
801               Content-type: multipart/mixed; boundary="*----*"
802               Content-transfer-encoding: 7bit
803
804               [Preamble]
805               --*----*
806               [Entity: Part 0]
807               --*----*
808               [Entity: Part 1]
809               --*----*--
810               [Epilogue]
811
812           If this entity has a single-part MIME type with no attached parts,
813           then we're looking at a normal singlepart entity: the body is
814           output according to the encoding specified by the header.  If no
815           body exists, a warning is output and the body is treated as empty:
816
817               Content-type: image/gif
818               Content-transfer-encoding: base64
819
820               [Encoded body]
821
822           If this entity has a single-part MIME type but it also has parts,
823           then we're probably looking at a "re-parsed" singlepart, usually
824           one of type "message/*" (you can get entities like this if you set
825           the "parse_nested_messages(NEST)" option on the parser to true).
826           In this case, the parts are output with single blank lines
827           separating each, and any bodyhandle is ignored:
828
829               Content-type: message/rfc822
830               Content-transfer-encoding: 7bit
831
832               [Entity: Part 0]
833
834               [Entity: Part 1]
835
836           In all cases, when outputting a "part" of the entity, this method
837           is invoked recursively.
838
839           Note: the output is very likely not going to be identical to any
840           input you parsed to get this entity.  If you're building some sort
841           of email handler, it's up to you to save this information.
842
843       print_body [OUTSTREAM]
844           Instance method, override.  Print the body of the entity to the
845           given OUTSTREAM, or to the currently-selected filehandle if none
846           given.  OUTSTREAM can be a filehandle, or any object that responds
847           to a print() message.
848
849           The body is output for inclusion in a valid MIME stream; this means
850           that the body data will be encoded if the header says that it
851           should be.
852
853           Note: by "body", we mean "the stuff following the header".  A
854           printed multipart body includes the printed representations of its
855           subparts.
856
857           Note: The body is stored in an un-encoded form; however, the idea
858           is that the transfer encoding is used to determine how it should be
859           output.  This means that the "print()" method is always guaranteed
860           to get you a sendmail-ready stream whose body is consistent with
861           its head.  If you want the raw body data to be output, you can
862           either read it from the bodyhandle yourself, or use:
863
864               $ent->bodyhandle->print($outstream);
865
866           which uses read() calls to extract the information, and thus will
867           work with both text and binary bodies.
868
869           Warning: Please supply an OUTSTREAM.  This override method differs
870           from Mail::Internet's behavior, which outputs to the STDOUT if no
871           filehandle is given: this may lead to confusion.
872
873       print_header [OUTSTREAM]
874           Instance method, inherited.  Output the header to the given
875           OUTSTREAM.  You really should supply the OUTSTREAM.
876
877       stringify
878           Instance method.  Return the entity as a string, exactly as "print"
879           would print it.  The body will be encoded as necessary, and will
880           contain any subparts.  You can also use "as_string()".
881
882       stringify_body
883           Instance method.  Return the encoded message body as a string,
884           exactly as "print_body" would print it.  You can also use
885           "body_as_string()".
886
887           If you want the unencoded body, and you are dealing with a
888           singlepart message (like a "text/plain"), use "bodyhandle()"
889           instead:
890
891               if ($ent->bodyhandle) {
892                   $unencoded_data = $ent->bodyhandle->as_string;
893               }
894               else {
895                   ### this message has no body data (but it might have parts!)
896               }
897
898       stringify_header
899           Instance method.  Return the header as a string, exactly as
900           "print_header" would print it.  You can also use
901           "header_as_string()".
902

NOTES

904   Under the hood
905       A MIME::Entity is composed of the following elements:
906
907       •   A head, which is a reference to a MIME::Head object containing the
908           header information.
909
910       •   A bodyhandle, which is a reference to a MIME::Body object
911           containing the decoded body data.  This is only defined if the
912           message is a "singlepart" type:
913
914               application/*
915               audio/*
916               image/*
917               text/*
918               video/*
919
920       •   An array of parts, where each part is a MIME::Entity object.  The
921           number of parts will only be nonzero if the content-type is not one
922           of the "singlepart" types:
923
924               message/*        (should have exactly one part)
925               multipart/*      (should have one or more parts)
926
927   The "two-body problem"
928       MIME::Entity and Mail::Internet see message bodies differently, and
929       this can cause confusion and some inconvenience.  Sadly, I can't change
930       the behavior of MIME::Entity without breaking lots of code already out
931       there.  But let's open up the floor for a few questions...
932
933       What is the difference between a "message" and an "entity"?
934           A message is the actual data being sent or received; usually this
935           means a stream of newline-terminated lines.  An entity is the
936           representation of a message as an object.
937
938           This means that you get a "message" when you print an "entity" to a
939           filehandle, and you get an "entity" when you parse a message from a
940           filehandle.
941
942       What is a message body?
943           Mail::Internet: The portion of the printed message after the
944           header.
945
946           MIME::Entity: The portion of the printed message after the header.
947
948       How is a message body stored in an entity?
949           Mail::Internet: As an array of lines.
950
951           MIME::Entity: It depends on the content-type of the message.  For
952           "container" types ("multipart/*", "message/*"), we store the
953           contained entities as an array of "parts", accessed via the
954           "parts()" method, where each part is a complete MIME::Entity.  For
955           "singlepart" types ("text/*", "image/*", etc.), the unencoded body
956           data is referenced via a MIME::Body object, accessed via the
957           "bodyhandle()" method:
958
959                                 bodyhandle()   parts()
960               Content-type:     returns:       returns:
961               ------------------------------------------------------------
962               application/*     MIME::Body     empty
963               audio/*           MIME::Body     empty
964               image/*           MIME::Body     empty
965               message/*         undef          MIME::Entity list (usually 1)
966               multipart/*       undef          MIME::Entity list (usually >0)
967               text/*            MIME::Body     empty
968               video/*           MIME::Body     empty
969               x-*/*             MIME::Body     empty
970
971           As a special case, "message/*" is currently ambiguous: depending on
972           the parser, a "message/*" might be treated as a singlepart, with a
973           MIME::Body and no parts.  Use bodyhandle() as the final arbiter.
974
975       What does the body() method return?
976           Mail::Internet: As an array of lines, ready for sending.
977
978           MIME::Entity: As an array of lines, ready for sending.
979
980       What's the best way to get at the body data?
981           Mail::Internet: Use the body() method.
982
983           MIME::Entity: Depends on what you want... the encoded data (as it
984           is transported), or the unencoded data?  Keep reading...
985
986       How do I get the "encoded" body data?
987           Mail::Internet: Use the body() method.
988
989           MIME::Entity: Use the body() method.  You can also use:
990
991               $entity->print_body()
992               $entity->stringify_body()   ### a.k.a. $entity->body_as_string()
993
994       How do I get the "unencoded" body data?
995           Mail::Internet: Use the body() method.
996
997           MIME::Entity: Use the bodyhandle() method!  If bodyhandle() method
998           returns true, then that value is a MIME::Body which can be used to
999           access the data via its open() method.  If bodyhandle() method
1000           returns an undefined value, then the entity is probably a
1001           "container" that has no real body data of its own (e.g., a
1002           "multipart" message): in this case, you should access the
1003           components via the parts() method.  Like this:
1004
1005               if ($bh = $entity->bodyhandle) {
1006                   $io = $bh->open;
1007                   ...access unencoded data via $io->getline or $io->read...
1008                   $io->close;
1009               }
1010               else {
1011                   foreach my $part (@parts) {
1012                       ...do something with the part...
1013                   }
1014               }
1015
1016           You can also use:
1017
1018               if ($bh = $entity->bodyhandle) {
1019                   $unencoded_data = $bh->as_string;
1020               }
1021               else {
1022                   ...do stuff with the parts...
1023               }
1024
1025       What does the body() method return?
1026           Mail::Internet: The transport-encoded message body, as an array of
1027           lines.
1028
1029           MIME::Entity: The transport-encoded message body, as an array of
1030           lines.
1031
1032       What does print_body() print?
1033           Mail::Internet: Exactly what body() would return to you.
1034
1035           MIME::Entity: Exactly what body() would return to you.
1036
1037       Say I have an entity which might be either singlepart or multipart. How
1038       do I print out just "the stuff after the header"?
1039           Mail::Internet: Use print_body().
1040
1041           MIME::Entity: Use print_body().
1042
1043       Why is MIME::Entity so different from Mail::Internet?
1044           Because MIME streams are expected to have non-textual data...
1045           possibly, quite a lot of it, such as a tar file.
1046
1047           Because MIME messages can consist of multiple parts, which are
1048           most-easily manipulated as MIME::Entity objects themselves.
1049
1050           Because in the simpler world of Mail::Internet, the data of a
1051           message and its printed representation are identical... and in the
1052           MIME world, they're not.
1053
1054           Because parsing multipart bodies on-the-fly, or formatting
1055           multipart bodies for output, is a non-trivial task.
1056
1057       This is confusing.  Can the two classes be made more compatible?
1058           Not easily; their implementations are necessarily quite different.
1059           Mail::Internet is a simple, efficient way of dealing with a "black
1060           box" mail message... one whose internal data you don't care much
1061           about.  MIME::Entity, in contrast, cares very much about the
1062           message contents: that's its job!
1063
1064   Design issues
1065       Some things just can't be ignored
1066           In multipart messages, the "preamble" is the portion that precedes
1067           the first encapsulation boundary, and the "epilogue" is the portion
1068           that follows the last encapsulation boundary.
1069
1070           According to RFC 2046:
1071
1072               There appears to be room for additional information prior
1073               to the first encapsulation boundary and following the final
1074               boundary.  These areas should generally be left blank, and
1075               implementations must ignore anything that appears before the
1076               first boundary or after the last one.
1077
1078               NOTE: These "preamble" and "epilogue" areas are generally
1079               not used because of the lack of proper typing of these parts
1080               and the lack of clear semantics for handling these areas at
1081               gateways, particularly X.400 gateways.  However, rather than
1082               leaving the preamble area blank, many MIME implementations
1083               have found this to be a convenient place to insert an
1084               explanatory note for recipients who read the message with
1085               pre-MIME software, since such notes will be ignored by
1086               MIME-compliant software.
1087
1088           In the world of standards-and-practices, that's the standard.  Now
1089           for the practice:
1090
1091           Some "MIME" mailers may incorrectly put a "part" in the preamble.
1092           Since we have to parse over the stuff anyway, in the future I may
1093           allow the parser option of creating special MIME::Entity objects
1094           for the preamble and epilogue, with bogus MIME::Head objects.
1095
1096           For now, though, we're MIME-compliant, so I probably won't change
1097           how we work.
1098

SEE ALSO

1100       MIME::Tools, MIME::Head, MIME::Body, MIME::Decoder, Mail::Internet
1101

AUTHOR

1103       Eryq (eryq@zeegee.com), ZeeGee Software Inc (http://www.zeegee.com).
1104       Dianne Skoll (dianne@skoll.ca)
1105
1106       All rights reserved.  This program is free software; you can
1107       redistribute it and/or modify it under the same terms as Perl itself.
1108
1109
1110
1111perl v5.36.0                      2022-07-22                   MIME::Entity(3)
Impressum