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 RFC 1521, Multipurpose Internet Mail Extensions.
37

EXAMPLES

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

PUBLIC INTERFACE

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

NOTES

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

AUTHOR

1096       Eryq (eryq@zeegee.com), ZeeGee Software Inc (http://www.zeegee.com).
1097       David F. Skoll (dfs@roaringpenguin.com) http://www.roaringpenguin.com
1098
1099       All rights reserved.  This program is free software; you can redis‐
1100       tribute it and/or modify it under the same terms as Perl itself.
1101

VERSION

1103       $Revision: 1.18 $ $Date: 2006/03/17 21:15:49 $
1104
1105
1106
1107perl v5.8.8                       2006-03-17                   MIME::Entity(3)
Impressum