1MIME::Entity(3) User Contributed Perl Documentation MIME::Entity(3)
2
3
4
6 MIME::Entity - class for parsed-and-decoded MIME message
7
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
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
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
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 Description
333 Optional. The text of the content-description. If you don't
334 specify it, the field is not put in the header.
335
336 Disposition
337 Optional. The basic content-disposition ("attachment" or
338 "inline"). If you don't specify it, it defaults to "inline"
339 for backwards compatibility. Thanks to Kurt Freytag for
340 suggesting this feature.
341
342 Encoding
343 Optional. The content-transfer-encoding. If you don't specify
344 it, a reasonable default is put in. You can also give the
345 special value '-SUGGEST', to have it chosen for you in a heavy-
346 duty fashion which scans the data itself.
347
348 Filename
349 Single-part entities only. Optional. The recommended filename.
350 Overrides any name extracted from "Path". The information is
351 stored both the deprecated (content-type) and preferred
352 (content-disposition) locations. If you explicitly want to
353 avoid a recommended filename (even when Path is used), supply
354 this as empty or undef.
355
356 Id Optional. Set the content-id.
357
358 Path
359 Single-part entities only. Optional. The path to the file to
360 attach. The body is opened on that file using
361 MIME::Body::File.
362
363 Top Optional. Is this a top-level entity? If so, it must sport a
364 MIME-Version. The default is true. (NB: look at how
365 "attach()" uses it.)
366
367 Type
368 Optional. The basic content-type ("text/plain", etc.). If you
369 don't specify it, it defaults to "text/plain" as per RFC 2045.
370 Do yourself a favor: put it in.
371
372 dup Instance method. Duplicate the entity. Does a deep, recursive
373 copy, but beware: external data in bodyhandles is not copied to new
374 files! Changing the data in one entity's data file, or purging
375 that entity, will affect its duplicate. Entities with in-core data
376 probably need not worry.
377
378 Access
379 body [VALUE]
380 Instance method. Get the encoded (transport-ready) body, as an
381 array of lines. Returns an array reference. Each array entry is a
382 newline-terminated line.
383
384 This is a read-only data structure: changing its contents will have
385 no effect. Its contents are identical to what is printed by
386 print_body().
387
388 Provided for compatibility with Mail::Internet, so that methods
389 like "smtpsend()" will work. Note however that if VALUE is given,
390 a fatal exception is thrown, since you cannot use this method to
391 set the lines of the encoded message.
392
393 If you want the raw (unencoded) body data, use the bodyhandle()
394 method to get and use a MIME::Body. The content-type of the entity
395 will tell you whether that body is best read as text (via
396 getline()) or raw data (via read()).
397
398 bodyhandle [VALUE]
399 Instance method. Get or set an abstract object representing the
400 body of the message. The body holds the decoded message data.
401
402 Note that not all entities have bodies! An entity will have either
403 a body or parts: not both. This method will only return an object
404 if this entity can have a body; otherwise, it will return
405 undefined. Whether-or-not a given entity can have a body is
406 determined by (1) its content type, and (2) whether-or-not the
407 parser was told to extract nested messages:
408
409 Type: | Extract nested? | bodyhandle() | parts()
410 -----------------------------------------------------------------------
411 multipart/* | - | undef | 0 or more MIME::Entity
412 message/* | true | undef | 0 or 1 MIME::Entity
413 message/* | false | MIME::Body | empty list
414 (other) | - | MIME::Body | empty list
415
416 If "VALUE" is not given, the current bodyhandle is returned, or
417 undef if the entity cannot have a body.
418
419 If "VALUE" is given, the bodyhandle is set to the new value, and
420 the previous value is returned.
421
422 See "parts" for more info.
423
424 effective_type [MIMETYPE]
425 Instance method. Set/get the effective MIME type of this entity.
426 This is usually identical to the actual (or defaulted) MIME type,
427 but in some cases it differs. For example, from RFC-2045:
428
429 Any entity with an unrecognized Content-Transfer-Encoding must be
430 treated as if it has a Content-Type of "application/octet-stream",
431 regardless of what the Content-Type header field actually says.
432
433 Why? because if we can't decode the message, then we have to take
434 the bytes as-is, in their (unrecognized) encoded form. So the
435 message ceases to be a "text/foobar" and becomes a bunch of
436 undecipherable bytes -- in other words, an
437 "application/octet-stream".
438
439 Such an entity, if parsed, would have its effective_type() set to
440 "application/octet_stream", although the mime_type() and the
441 contents of the header would remain the same.
442
443 If there is no effective type, the method just returns what
444 mime_type() would.
445
446 Warning: the effective type is "sticky"; once set, that
447 effective_type() will always be returned even if the conditions
448 that necessitated setting the effective type become no longer true.
449
450 epilogue [LINES]
451 Instance method. Get/set the text of the epilogue, as an array of
452 newline-terminated LINES. Returns a reference to the array of
453 lines, or undef if no epilogue exists.
454
455 If there is a epilogue, it is output when printing this entity;
456 otherwise, a default epilogue is used. Setting the epilogue to
457 undef (not []!) causes it to fallback to the default.
458
459 head [VALUE]
460 Instance method. Get/set the head.
461
462 If there is no VALUE given, returns the current head. If none
463 exists, an empty instance of MIME::Head is created, set, and
464 returned.
465
466 Note: This is a patch over a problem in Mail::Internet, which
467 doesn't provide a method for setting the head to some given object.
468
469 is_multipart
470 Instance method. Does this entity's effective MIME type indicate
471 that it's a multipart entity? Returns undef (false) if the answer
472 couldn't be determined, 0 (false) if it was determined to be false,
473 and true otherwise. Note that this says nothing about whether or
474 not parts were extracted.
475
476 NOTE: we switched to effective_type so that multiparts with bad or
477 missing boundaries could be coerced to an effective type of
478 "application/x-unparseable-multipart".
479
480 mime_type
481 Instance method. A purely-for-convenience method. This simply
482 relays the request to the associated MIME::Head object. If there
483 is no head, returns undef in a scalar context and the empty array
484 in a list context.
485
486 Before you use this, consider using effective_type() instead,
487 especially if you obtained the entity from a MIME::Parser.
488
489 open READWRITE
490 Instance method. A purely-for-convenience method. This simply
491 relays the request to the associated MIME::Body object (see
492 MIME::Body::open()). READWRITE is either 'r' (open for read) or
493 'w' (open for write).
494
495 If there is no body, returns false.
496
497 parts
498 parts INDEX
499 parts ARRAYREF
500 Instance method. Return the MIME::Entity objects which are the sub
501 parts of this entity (if any).
502
503 If no argument is given, returns the array of all sub parts,
504 returning the empty array if there are none (e.g., if this is a
505 single part message, or a degenerate multipart). In a scalar
506 context, this returns you the number of parts.
507
508 If an integer INDEX is given, return the INDEXed part, or undef if
509 it doesn't exist.
510
511 If an ARRAYREF to an array of parts is given, then this method sets
512 the parts to a copy of that array, and returns the parts. This can
513 be used to delete parts, as follows:
514
515 ### Delete some parts of a multipart message:
516 $msg->parts([ grep { keep_part($_) } $msg->parts ]);
517
518 Note: for multipart messages, the preamble and epilogue are not
519 considered parts. If you need them, use the "preamble()" and
520 "epilogue()" methods.
521
522 Note: there are ways of parsing with a MIME::Parser which cause
523 certain message parts (such as those of type "message/rfc822") to
524 be "reparsed" into pseudo-multipart entities. You should read the
525 documentation for those options carefully: it is possible for a
526 diddled entity to not be multipart, but still have parts attached
527 to it!
528
529 See "bodyhandle" for a discussion of parts vs. bodies.
530
531 parts_DFS
532 Instance method. Return the list of all MIME::Entity objects
533 included in the entity, starting with the entity itself, in depth-
534 first-search order. If the entity has no parts, it alone will be
535 returned.
536
537 Thanks to Xavier Armengou for suggesting this method.
538
539 preamble [LINES]
540 Instance method. Get/set the text of the preamble, as an array of
541 newline-terminated LINES. Returns a reference to the array of
542 lines, or undef if no preamble exists (e.g., if this is a single-
543 part entity).
544
545 If there is a preamble, it is output when printing this entity;
546 otherwise, a default preamble is used. Setting the preamble to
547 undef (not []!) causes it to fallback to the default.
548
549 Manipulation
550 make_multipart [SUBTYPE], OPTSHASH...
551 Instance method. Force the entity to be a multipart, if it isn't
552 already. We do this by replacing the original [singlepart] entity
553 with a new multipart that has the same non-MIME headers ("From",
554 "Subject", etc.), but all-new MIME headers ("Content-type", etc.).
555 We then create a copy of the original singlepart, strip out the
556 non-MIME headers from that, and make it a part of the new
557 multipart. So this:
558
559 From: me
560 To: you
561 Content-type: text/plain
562 Content-length: 12
563
564 Hello there!
565
566 Becomes something like this:
567
568 From: me
569 To: you
570 Content-type: multipart/mixed; boundary="----abc----"
571
572 ------abc----
573 Content-type: text/plain
574 Content-length: 12
575
576 Hello there!
577 ------abc------
578
579 The actual type of the new top-level multipart will be
580 "multipart/SUBTYPE" (default SUBTYPE is "mixed").
581
582 Returns 'DONE' if we really did inflate a singlepart to a
583 multipart. Returns 'ALREADY' (and does nothing) if entity is
584 already multipart and Force was not chosen.
585
586 If OPTSHASH contains Force=>1, then we always bump the top-level's
587 content and content-headers down to a subpart of this entity, even
588 if this entity is already a multipart. This is apparently of use
589 to people who are tweaking messages after parsing them.
590
591 make_singlepart
592 Instance method. If the entity is a multipart message with one
593 part, this tries hard to rewrite it as a singlepart, by replacing
594 the content (and content headers) of the top level with those of
595 the part. Also crunches 0-part multiparts into singleparts.
596
597 Returns 'DONE' if we really did collapse a multipart to a
598 singlepart. Returns 'ALREADY' (and does nothing) if entity is
599 already a singlepart. Returns '0' (and does nothing) if it
600 can't be made into a singlepart.
601
602 purge
603 Instance method. Recursively purge (e.g., unlink) all external
604 (e.g., on-disk) body parts in this message. See
605 MIME::Body::purge() for details.
606
607 Note: this does not delete the directories that those body parts
608 are contained in; only the actual message data files are deleted.
609 This is because some parsers may be customized to create
610 intermediate directories while others are not, and it's impossible
611 for this class to know what directories are safe to remove. Only
612 your application program truly knows that.
613
614 If you really want to "clean everything up", one good way is to use
615 "MIME::Parser::file_under()", and then do this before parsing your
616 next message:
617
618 $parser->filer->purge();
619
620 I wouldn't attempt to read those body files after you do this, for
621 obvious reasons. As of MIME-tools 4.x, each body's path is
622 undefined after this operation. I warned you I might do this;
623 truly I did.
624
625 Thanks to Jason L. Tibbitts III for suggesting this method.
626
627 remove_sig [NLINES]
628 Instance method, override. Attempts to remove a user's signature
629 from the body of a message.
630
631 It does this by looking for a line matching "/^-- $/" within the
632 last "NLINES" of the message. If found then that line and all
633 lines after it will be removed. If "NLINES" is not given, a default
634 value of 10 will be used. This would be of most use in auto-reply
635 scripts.
636
637 For MIME entity, this method is reasonably cautious: it will only
638 attempt to un-sign a message with a content-type of "text/*".
639
640 If you send remove_sig() to a multipart entity, it will relay it to
641 the first part (the others usually being the "attachments").
642
643 Warning: currently slurps the whole message-part into core as an
644 array of lines, so you probably don't want to use this on extremely
645 long messages.
646
647 Returns truth on success, false on error.
648
649 sign PARAMHASH
650 Instance method, override. Append a signature to the message. The
651 params are:
652
653 Attach
654 Instead of appending the text, add it to the message as an
655 attachment. The disposition will be "inline", and the
656 description will indicate that it is a signature. The default
657 behavior is to append the signature to the text of the message
658 (or the text of its first part if multipart). MIME-specific;
659 new in this subclass.
660
661 File
662 Use the contents of this file as the signature. Fatal error if
663 it can't be read. As per superclass method.
664
665 Force
666 Sign it even if the content-type isn't "text/*". Useful for
667 non-standard types like "x-foobar", but be careful! MIME-
668 specific; new in this subclass.
669
670 Remove
671 Normally, we attempt to strip out any existing signature. If
672 true, this gives us the NLINES parameter of the remove_sig
673 call. If zero but defined, tells us not to remove any existing
674 signature. If undefined, removal is done with the default of
675 10 lines. New in this subclass.
676
677 Signature
678 Use this text as the signature. You can supply it as either a
679 scalar, or as a ref to an array of newline-terminated scalars.
680 As per superclass method.
681
682 For MIME messages, this method is reasonably cautious: it will only
683 attempt to sign a message with a content-type of "text/*", unless
684 "Force" is specified.
685
686 If you send this message to a multipart entity, it will relay it to
687 the first part (the others usually being the "attachments").
688
689 Warning: currently slurps the whole message-part into core as an
690 array of lines, so you probably don't want to use this on extremely
691 long messages.
692
693 Returns true on success, false otherwise.
694
695 suggest_encoding
696 Instance method. Based on the effective content type, return a
697 good suggested encoding.
698
699 "text" and "message" types have their bodies scanned line-by-line
700 for 8-bit characters and long lines; lack of either means that the
701 message is 7bit-ok. Other types are chosen independent of their
702 body:
703
704 Major type: 7bit ok? Suggested encoding:
705 -----------------------------------------------------------
706 text yes 7bit
707 text no quoted-printable
708 message yes 7bit
709 message no binary
710 multipart * binary (in case some parts are bad)
711 image, etc... * base64
712
713 sync_headers OPTIONS
714 Instance method. This method does a variety of activities which
715 ensure that the MIME headers of an entity "tree" are in-synch with
716 the body parts they describe. It can be as expensive an operation
717 as printing if it involves pre-encoding the body parts; however,
718 the aim is to produce fairly clean MIME. You will usually only
719 need to invoke this if processing and re-sending MIME from an
720 outside source.
721
722 The OPTIONS is a hash, which describes what is to be done.
723
724 Length
725 One of the "official unofficial" MIME fields is "Content-
726 Length". Normally, one doesn't care a whit about this field;
727 however, if you are preparing output destined for HTTP, you
728 may. The value of this option dictates what will be done:
729
730 COMPUTE means to set a "Content-Length" field for every non-
731 multipart part in the entity, and to blank that field out for
732 every multipart part in the entity.
733
734 ERASE means that "Content-Length" fields will all be blanked
735 out. This is fast, painless, and safe.
736
737 Any false value (the default) means to take no action.
738
739 Nonstandard
740 Any header field beginning with "Content-" is, according to the
741 RFC, a MIME field. However, some are non-standard, and may
742 cause problems with certain MIME readers which interpret them
743 in different ways.
744
745 ERASE means that all such fields will be blanked out. This is
746 done before the Length option (q.v.) is examined and acted
747 upon.
748
749 Any false value (the default) means to take no action.
750
751 Returns a true value if everything went okay, a false value
752 otherwise.
753
754 tidy_body
755 Instance method, override. Currently unimplemented for MIME
756 messages. Does nothing, returns false.
757
758 Output
759 dump_skeleton [FILEHANDLE]
760 Instance method. Dump the skeleton of the entity to the given
761 FILEHANDLE, or to the currently-selected one if none given.
762
763 Each entity is output with an appropriate indentation level, the
764 following selection of attributes:
765
766 Content-type: multipart/mixed
767 Effective-type: multipart/mixed
768 Body-file: NONE
769 Subject: Hey there!
770 Num-parts: 2
771
772 This is really just useful for debugging purposes; I make no
773 guarantees about the consistency of the output format over time.
774
775 print [OUTSTREAM]
776 Instance method, override. Print the entity to the given
777 OUTSTREAM, or to the currently-selected filehandle if none given.
778 OUTSTREAM can be a filehandle, or any object that responds to a
779 print() message.
780
781 The entity is output as a valid MIME stream! This means that the
782 header is always output first, and the body data (if any) will be
783 encoded if the header says that it should be. For example, your
784 output may look like this:
785
786 Subject: Greetings
787 Content-transfer-encoding: base64
788
789 SGkgdGhlcmUhCkJ5ZSB0aGVyZSEK
790
791 If this entity has MIME type "multipart/*", the preamble, parts,
792 and epilogue are all output with appropriate boundaries separating
793 each. Any bodyhandle is ignored:
794
795 Content-type: multipart/mixed; boundary="*----*"
796 Content-transfer-encoding: 7bit
797
798 [Preamble]
799 --*----*
800 [Entity: Part 0]
801 --*----*
802 [Entity: Part 1]
803 --*----*--
804 [Epilogue]
805
806 If this entity has a single-part MIME type with no attached parts,
807 then we're looking at a normal singlepart entity: the body is
808 output according to the encoding specified by the header. If no
809 body exists, a warning is output and the body is treated as empty:
810
811 Content-type: image/gif
812 Content-transfer-encoding: base64
813
814 [Encoded body]
815
816 If this entity has a single-part MIME type but it also has parts,
817 then we're probably looking at a "re-parsed" singlepart, usually
818 one of type "message/*" (you can get entities like this if you set
819 the "parse_nested_messages(NEST)" option on the parser to true).
820 In this case, the parts are output with single blank lines
821 separating each, and any bodyhandle is ignored:
822
823 Content-type: message/rfc822
824 Content-transfer-encoding: 7bit
825
826 [Entity: Part 0]
827
828 [Entity: Part 1]
829
830 In all cases, when outputting a "part" of the entity, this method
831 is invoked recursively.
832
833 Note: the output is very likely not going to be identical to any
834 input you parsed to get this entity. If you're building some sort
835 of email handler, it's up to you to save this information.
836
837 print_body [OUTSTREAM]
838 Instance method, override. Print the body of the entity to the
839 given OUTSTREAM, or to the currently-selected filehandle if none
840 given. OUTSTREAM can be a filehandle, or any object that responds
841 to a print() message.
842
843 The body is output for inclusion in a valid MIME stream; this means
844 that the body data will be encoded if the header says that it
845 should be.
846
847 Note: by "body", we mean "the stuff following the header". A
848 printed multipart body includes the printed representations of its
849 subparts.
850
851 Note: The body is stored in an un-encoded form; however, the idea
852 is that the transfer encoding is used to determine how it should be
853 output. This means that the "print()" method is always guaranteed
854 to get you a sendmail-ready stream whose body is consistent with
855 its head. If you want the raw body data to be output, you can
856 either read it from the bodyhandle yourself, or use:
857
858 $ent->bodyhandle->print($outstream);
859
860 which uses read() calls to extract the information, and thus will
861 work with both text and binary bodies.
862
863 Warning: Please supply an OUTSTREAM. This override method differs
864 from Mail::Internet's behavior, which outputs to the STDOUT if no
865 filehandle is given: this may lead to confusion.
866
867 print_header [OUTSTREAM]
868 Instance method, inherited. Output the header to the given
869 OUTSTREAM. You really should supply the OUTSTREAM.
870
871 stringify
872 Instance method. Return the entity as a string, exactly as "print"
873 would print it. The body will be encoded as necessary, and will
874 contain any subparts. You can also use "as_string()".
875
876 stringify_body
877 Instance method. Return the encoded message body as a string,
878 exactly as "print_body" would print it. You can also use
879 "body_as_string()".
880
881 If you want the unencoded body, and you are dealing with a
882 singlepart message (like a "text/plain"), use "bodyhandle()"
883 instead:
884
885 if ($ent->bodyhandle) {
886 $unencoded_data = $ent->bodyhandle->as_string;
887 }
888 else {
889 ### this message has no body data (but it might have parts!)
890 }
891
892 stringify_header
893 Instance method. Return the header as a string, exactly as
894 "print_header" would print it. You can also use
895 "header_as_string()".
896
898 Under the hood
899 A MIME::Entity is composed of the following elements:
900
901 • A head, which is a reference to a MIME::Head object containing the
902 header information.
903
904 • A bodyhandle, which is a reference to a MIME::Body object
905 containing the decoded body data. This is only defined if the
906 message is a "singlepart" type:
907
908 application/*
909 audio/*
910 image/*
911 text/*
912 video/*
913
914 • An array of parts, where each part is a MIME::Entity object. The
915 number of parts will only be nonzero if the content-type is not one
916 of the "singlepart" types:
917
918 message/* (should have exactly one part)
919 multipart/* (should have one or more parts)
920
921 The "two-body problem"
922 MIME::Entity and Mail::Internet see message bodies differently, and
923 this can cause confusion and some inconvenience. Sadly, I can't change
924 the behavior of MIME::Entity without breaking lots of code already out
925 there. But let's open up the floor for a few questions...
926
927 What is the difference between a "message" and an "entity"?
928 A message is the actual data being sent or received; usually this
929 means a stream of newline-terminated lines. An entity is the
930 representation of a message as an object.
931
932 This means that you get a "message" when you print an "entity" to a
933 filehandle, and you get an "entity" when you parse a message from a
934 filehandle.
935
936 What is a message body?
937 Mail::Internet: The portion of the printed message after the
938 header.
939
940 MIME::Entity: The portion of the printed message after the header.
941
942 How is a message body stored in an entity?
943 Mail::Internet: As an array of lines.
944
945 MIME::Entity: It depends on the content-type of the message. For
946 "container" types ("multipart/*", "message/*"), we store the
947 contained entities as an array of "parts", accessed via the
948 "parts()" method, where each part is a complete MIME::Entity. For
949 "singlepart" types ("text/*", "image/*", etc.), the unencoded body
950 data is referenced via a MIME::Body object, accessed via the
951 "bodyhandle()" method:
952
953 bodyhandle() parts()
954 Content-type: returns: returns:
955 ------------------------------------------------------------
956 application/* MIME::Body empty
957 audio/* MIME::Body empty
958 image/* MIME::Body empty
959 message/* undef MIME::Entity list (usually 1)
960 multipart/* undef MIME::Entity list (usually >0)
961 text/* MIME::Body empty
962 video/* MIME::Body empty
963 x-*/* MIME::Body empty
964
965 As a special case, "message/*" is currently ambiguous: depending on
966 the parser, a "message/*" might be treated as a singlepart, with a
967 MIME::Body and no parts. Use bodyhandle() as the final arbiter.
968
969 What does the body() method return?
970 Mail::Internet: As an array of lines, ready for sending.
971
972 MIME::Entity: As an array of lines, ready for sending.
973
974 What's the best way to get at the body data?
975 Mail::Internet: Use the body() method.
976
977 MIME::Entity: Depends on what you want... the encoded data (as it
978 is transported), or the unencoded data? Keep reading...
979
980 How do I get the "encoded" body data?
981 Mail::Internet: Use the body() method.
982
983 MIME::Entity: Use the body() method. You can also use:
984
985 $entity->print_body()
986 $entity->stringify_body() ### a.k.a. $entity->body_as_string()
987
988 How do I get the "unencoded" body data?
989 Mail::Internet: Use the body() method.
990
991 MIME::Entity: Use the bodyhandle() method! If bodyhandle() method
992 returns true, then that value is a MIME::Body which can be used to
993 access the data via its open() method. If bodyhandle() method
994 returns an undefined value, then the entity is probably a
995 "container" that has no real body data of its own (e.g., a
996 "multipart" message): in this case, you should access the
997 components via the parts() method. Like this:
998
999 if ($bh = $entity->bodyhandle) {
1000 $io = $bh->open;
1001 ...access unencoded data via $io->getline or $io->read...
1002 $io->close;
1003 }
1004 else {
1005 foreach my $part (@parts) {
1006 ...do something with the part...
1007 }
1008 }
1009
1010 You can also use:
1011
1012 if ($bh = $entity->bodyhandle) {
1013 $unencoded_data = $bh->as_string;
1014 }
1015 else {
1016 ...do stuff with the parts...
1017 }
1018
1019 What does the body() method return?
1020 Mail::Internet: The transport-encoded message body, as an array of
1021 lines.
1022
1023 MIME::Entity: The transport-encoded message body, as an array of
1024 lines.
1025
1026 What does print_body() print?
1027 Mail::Internet: Exactly what body() would return to you.
1028
1029 MIME::Entity: Exactly what body() would return to you.
1030
1031 Say I have an entity which might be either singlepart or multipart. How
1032 do I print out just "the stuff after the header"?
1033 Mail::Internet: Use print_body().
1034
1035 MIME::Entity: Use print_body().
1036
1037 Why is MIME::Entity so different from Mail::Internet?
1038 Because MIME streams are expected to have non-textual data...
1039 possibly, quite a lot of it, such as a tar file.
1040
1041 Because MIME messages can consist of multiple parts, which are
1042 most-easily manipulated as MIME::Entity objects themselves.
1043
1044 Because in the simpler world of Mail::Internet, the data of a
1045 message and its printed representation are identical... and in the
1046 MIME world, they're not.
1047
1048 Because parsing multipart bodies on-the-fly, or formatting
1049 multipart bodies for output, is a non-trivial task.
1050
1051 This is confusing. Can the two classes be made more compatible?
1052 Not easily; their implementations are necessarily quite different.
1053 Mail::Internet is a simple, efficient way of dealing with a "black
1054 box" mail message... one whose internal data you don't care much
1055 about. MIME::Entity, in contrast, cares very much about the
1056 message contents: that's its job!
1057
1058 Design issues
1059 Some things just can't be ignored
1060 In multipart messages, the "preamble" is the portion that precedes
1061 the first encapsulation boundary, and the "epilogue" is the portion
1062 that follows the last encapsulation boundary.
1063
1064 According to RFC 2046:
1065
1066 There appears to be room for additional information prior
1067 to the first encapsulation boundary and following the final
1068 boundary. These areas should generally be left blank, and
1069 implementations must ignore anything that appears before the
1070 first boundary or after the last one.
1071
1072 NOTE: These "preamble" and "epilogue" areas are generally
1073 not used because of the lack of proper typing of these parts
1074 and the lack of clear semantics for handling these areas at
1075 gateways, particularly X.400 gateways. However, rather than
1076 leaving the preamble area blank, many MIME implementations
1077 have found this to be a convenient place to insert an
1078 explanatory note for recipients who read the message with
1079 pre-MIME software, since such notes will be ignored by
1080 MIME-compliant software.
1081
1082 In the world of standards-and-practices, that's the standard. Now
1083 for the practice:
1084
1085 Some "MIME" mailers may incorrectly put a "part" in the preamble.
1086 Since we have to parse over the stuff anyway, in the future I may
1087 allow the parser option of creating special MIME::Entity objects
1088 for the preamble and epilogue, with bogus MIME::Head objects.
1089
1090 For now, though, we're MIME-compliant, so I probably won't change
1091 how we work.
1092
1094 MIME::Tools, MIME::Head, MIME::Body, MIME::Decoder, Mail::Internet
1095
1097 Eryq (eryq@zeegee.com), ZeeGee Software Inc (http://www.zeegee.com).
1098 Dianne Skoll (dfs@roaringpenguin.com) http://www.roaringpenguin.com
1099
1100 All rights reserved. This program is free software; you can
1101 redistribute it and/or modify it under the same terms as Perl itself.
1102
1103
1104
1105perl v5.34.0 2022-01-21 MIME::Entity(3)