blib/lib/Mail/Make/Entity.pm untested

filter: Statementstmt 0.0% 0 / 428 Branchbran 0.0% 0 / 204 Conditioncond 0.0% 0 / 208 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 52 Podpod 0.0% 0 / 34 totaltotal 0.0% 0 / 926 CC 103 SCAR 61.1
CC
103
Cov
0%
build
1640.0
length
132.0
print_body
90.0
CRAP 451.3
1 ##----------------------------------------------------------------------------
2 ## MIME Email Builder - ~/lib/Mail/Make/Entity.pm
3 ## Version v0.4.1
4 ## Copyright(c) 2026 DEGUEST Pte. Ltd.
5 ## Author: Jacques Deguest <jack@deguest.jp>
6 ## Created 2026/03/02
7 ## Modified 2026/03/18
8 ## All rights reserved
9 ##
10 ##
11 ## This program is free software; you can redistribute it and/or modify it
12 ## under the same terms as Perl itself.
13 ##----------------------------------------------------------------------------
14 package Mail::Make::Entity;
15 BEGIN
16 {
17 use strict;
18 use warnings;
19 warnings::register_categories( 'Mail::Make' );
20 use parent qw( Module::Generic );
21 use vars qw( $VERSION $EXCEPTION_CLASS $CRLF );
22 use Data::UUID;
23 use Mail::Make::Body::File;
24 use Mail::Make::Body::InCore;
25 use Mail::Make::Exception;
26 use Mail::Make::Headers;
27 use Mail::Make::Headers::ContentDisposition;
28 use Mail::Make::Headers::ContentTransferEncoding;
29 use Mail::Make::Headers::ContentType;
30 use Mail::Make::Stream;
31 use Mail::Make::Stream::Base64;
32 use Mail::Make::Stream::QuotedPrint;
33 our $CRLF = "\015\012";
34 our $DEFAULT_MIME_TYPE = 'application/octet-stream';
35 our $EXCEPTION_CLASS = 'Mail::Make::Exception';
36 our $VERSION = 'v0.4.1';
37 }
38  
39 use strict;
40 use warnings;
41  
42 sub init
43 {
44 my $self = shift( @_ );
45 $self->{body} = undef; # Mail::Make::Body object
46 $self->{effective_type} = undef; # cached mime type string
47 $self->{epilogue} = [];
48 $self->{headers} = undef; # Mail::Make::Headers object
49 $self->{is_encoded} = 0;
50 $self->{preamble} = [];
51 $self->{_parts} = []; # [ Mail::Make::Entity, ... ]
52 $self->{_exception_class} = $EXCEPTION_CLASS;
53 $self->{_init_strict_use_sub} = 1;
54 $self->SUPER::init( @_ ) || return( $self->pass_error );
55 return( $self );
56 }
57  
58 # add_part( $entity )
59 # Appends a Mail::Make::Entity as a sub-part of this entity.
60 sub add_part
61 {
62 my( $self, $part ) = @_;
63 unless( $self->_is_a( $part => 'Mail::Make::Entity' ) )
64 {
65 return( $self->error( "add_part: argument must be a Mail::Make::Entity" ) );
66 }
67 push( @{$self->{_parts}}, $part );
68 return( $self );
69 }
70  
71 # as_string()
72 # Returns the serialised entity (headers + blank line + body) as a plain string.
73 sub as_string
74 {
75 my $self = shift( @_ );
76 my $out = '';
77 open( my $fh, '>:raw', \$out ) ||
78 return( $self->error( "Cannot open in-memory buffer for as_string: $!" ) );
79 $self->print( $fh ) || return( $self->pass_error );
80 close( $fh );
81 return( $out );
82 }
83  
84 # Returns the serialised entity as a scalar reference, avoiding a string copy.
85 # Useful for large messages where the caller can pass the ref directly to
86 # print() or write() without materialising a second copy.
87 sub as_string_ref
88 {
89 my $self = shift( @_ );
90 my $out = '';
91 open( my $fh, '>:raw', \$out ) ||
92 return( $self->error( "Cannot open in-memory buffer for as_string_ref: $!" ) );
93 $self->print( $fh ) || return( $self->pass_error );
94 close( $fh );
95 return( \$out );
96 }
97  
98 # body( [$body_object] )
99 # Gets or sets the Mail::Make::Body object.
100 sub body
101 {
102 my $self = shift( @_ );
103 if( @_ )
104 {
105 my $body = shift( @_ );
106 if( defined( $body ) )
107 {
108 unless( $self->_is_a( $body => 'Mail::Make::Body' ) )
109 {
110 return( $self->error( "body: argument must be a Mail::Make::Body-derived object" ) );
111 }
112 }
113 $self->{body} = $body;
114 return( $self );
115 }
116 return( $self->{body} );
117 }
118  
119 # body_as_string()
120 # Returns the encoded body content as a scalar reference.
121 sub body_as_string
122 {
123 my $self = shift( @_ );
124 unless( defined( $self->{body} ) )
125 {
126 return( $self->error( "No body is set on this entity" ) );
127 }
128  
129 my $enc = $self->headers->content_transfer_encoding // '';
130 if( CORE::length( $enc ) && !$self->{is_encoded} )
131 {
132 $self->encode_body || return( $self->pass_error );
133 }
134 return( $self->{body}->as_string );
135 }
136  
137 # build( %params )
138 # Factory / class method: build a single MIME entity from parameters.
139 # This is the key method - it performs strict validation and correct encoding.
140 #
141 # Parameters:
142 # attach Shorthand for 'path'
143 # boundary boundary for multipart/* types (auto-generated if omitted)
144 # charset charset for text/* types
145 # cid Content-ID for inline parts (wrapped in <...> automatically if needed)
146 # data scalar body content
147 # debug debug level (default: 0)
148 # description Content-Description value
149 # disposition inline | attachment (default: none unless filename provided)
150 # encoding CTE (default: auto-suggested)
151 # filename filename for Content-Type name= and Content-Disposition filename=
152 # path file path body content
153 # top boolean - is this the top-level entity? (default: 1)
154 # type MIME type string (default: 'text/plain')
155 sub build
156 {
157 my $class = shift( @_ );
158 # Support both class and instance call
159 my $self = ref( $class ) ? $class : $class->new;
160 return( $self->pass_error ) if( !$self );
161 my $opts = $self->_get_args_as_hash( @_ );
162 $self->debug( delete( $opts->{debug} ) );
163  
164 # NOTE: 1. Extract and validate parameters
165 my $has_type = ( exists( $opts->{type} ) && defined( $opts->{type} ) );
166 my $type = lc( delete( $opts->{type} ) // 'text/plain' );
167 my $charset = delete( $opts->{charset} );
168 my $encoding = defined( $opts->{encoding} )
169 ? lc( delete( $opts->{encoding} ) )
170 : undef;
171 my $disposition = defined( $opts->{disposition} )
172 ? lc( delete( $opts->{disposition} ) )
173 : undef;
174 my $filename = delete( $opts->{filename} );
175 my $cid = delete( $opts->{cid} ) || delete( $opts->{id} );
176 my $data = delete( $opts->{data} );
177 my $path = delete( $opts->{path} );
178 my $boundary = delete( $opts->{boundary} );
179 my $description = delete( $opts->{description} );
180 my $top = exists( $opts->{top} ) ? delete( $opts->{top} ) : 1;
181  
182 if( !defined( $path ) &&
183 !defined( $data ) &&
184 exists( $opts->{attach} ) &&
185 defined( $opts->{attach} ) &&
186 ( !ref( $opts->{attach} ) || $self->_can_overload( $opts->{attach} => '""' ) ) &&
187 index( "$opts->{attach}", "\n" ) == -1 )
188 {
189 my $f = $self->new_file( delete( $opts->{attach} ) ); # Module::Generic::File will trigger stringification
190 if( $f->exists )
191 {
192 $path = $f;
193 # Auto-detect the MIME type from the file content if not explicitly provided
194 if( !$has_type )
195 {
196 my $candidate = $f->finfo->mime_type;
197 $type = "$candidate" if( $candidate );
198 }
199 }
200 }
201 # Auto-detect MIME type from path if not explicitly provided
202 elsif( !$has_type && defined( $path ) && CORE::length( $path ) )
203 {
204 my $f = $self->new_file( $path );
205 my $candidate = $f->finfo->mime_type;
206 $type = "$candidate" if( $candidate );
207 }
208  
209 my $is_multipart = ( $type =~ m{^multipart/}i );
210 my $is_message = ( $type =~ m{^message/}i );
211  
212 # NOTE: 2. Validate the MIME type format
213 my $ct_obj = Mail::Make::Headers::ContentType->new( $type ) ||
214 return( $self->pass_error( Mail::Make::Headers::ContentType->error ) );
215  
216 # NOTE: 3. Validate charset (text/* types only)
217 if( defined( $charset ) )
218 {
219 if( !$is_multipart )
220 {
221 $ct_obj->param( charset => $charset ) ||
222 return( $self->pass_error( $ct_obj->error ) );
223 }
224 else
225 {
226 # Silently discard charset on multipart - do not pass invalid param
227 undef( $charset );
228 }
229 }
230 else
231 {
232 # Default charset for text/* parts
233 if( $type =~ m{^text/}i && !$is_multipart )
234 {
235 $ct_obj->param( charset => 'utf-8' ) ||
236 return( $self->pass_error( $ct_obj->error ) );
237 }
238 }
239  
240 # NOTE: 4. Determine filename (from explicit param or basename of path)
241 if( !defined( $filename ) && defined( $path ) && CORE::length( $path ) )
242 {
243 ( $filename ) = ( $path =~ m{([^/\\]+)\z} );
244 }
245 # Empty string -> treat as no filename
246 undef( $filename ) if( defined( $filename ) && !CORE::length( $filename ) );
247  
248 # NOTE: 5. Content-Type set for filename
249 # 5. Set Content-Type name= parameter if we have a filename
250 # THIS IS THE KEY FIX: we go through ContentType->param() which
251 # handles RFC 2231 encoding, not a raw string that Mail::Field
252 # would misparse on commas.
253 if( defined( $filename ) && !$is_multipart )
254 {
255 $ct_obj->param( name => $filename ) ||
256 return( $self->pass_error( $ct_obj->error ) );
257 }
258  
259 # NOTE: 6. Validate / generate boundary for multipart
260 if( $is_multipart )
261 {
262 if( defined( $boundary ) )
263 {
264 if( !CORE::length( $boundary ) )
265 {
266 # Empty boundary: warn and generate a fresh one
267 warn( "Empty boundary string provided; generating a new one\n" );
268 undef( $boundary );
269 }
270 elsif( $boundary =~ /[^0-9a-zA-Z'()+_,\-.\/:=? ]/ )
271 {
272 return( $self->error( "Boundary '$boundary' contains illegal characters" ) );
273 }
274 }
275 $boundary //= $self->make_boundary;
276 # Boundary is safe to pass directly (we just validated it)
277 $ct_obj->param( boundary => $boundary ) ||
278 return( $self->pass_error( $ct_obj->error ) );
279 }
280  
281 # NOTE: 7. Validate Content-Transfer-Encoding
282 if( defined( $encoding ) )
283 {
284 if( $is_multipart )
285 {
286 return( $self->error(
287 "build(): encoding '$encoding' is not permitted for multipart type '$type'."
288 ) );
289 }
290 elsif( $is_message )
291 {
292 # RFC 2045 §6.4 - multipart and message types must not have a CTE
293 undef( $encoding );
294 }
295 elsif( $encoding eq 'suggest' )
296 {
297 # Deferred: computed after we know the body type
298 undef( $encoding );
299 }
300 else
301 {
302 my $cte_obj = Mail::Make::Headers::ContentTransferEncoding->new( $encoding ) ||
303 return( $self->pass_error( Mail::Make::Headers::ContentTransferEncoding->error ) );
304 # 'binary' is not valid for text/* parts in SMTP contexts
305 if( $cte_obj->is_binary && $type =~ m{^text/}i )
306 {
307 return( $self->error( "Encoding 'binary' is not permitted for text/* type '$type'" ) );
308 }
309 }
310 }
311  
312 # NOTE: 8. Build a fresh entity object with fresh headers
313 my $entity = ref( $class ) ? $class->new : $class->new;
314 return( $self->pass_error ) if( !$entity );
315 my $headers = Mail::Make::Headers->new ||
316 return( $self->pass_error( Mail::Make::Headers->error ) );
317 $entity->headers( $headers );
318  
319 # NOTE: 9. Attach body (single-part only)
320 if( !$is_multipart )
321 {
322 if( defined( $path ) && CORE::length( $path ) )
323 {
324 my $body = Mail::Make::Body::File->new( $path ) ||
325 return( $self->pass_error( Mail::Make::Body::File->error ) );
326 $entity->body( $body );
327 }
328 elsif( defined( $data ) )
329 {
330 my $body = Mail::Make::Body::InCore->new( $data ) ||
331 return( $self->pass_error( Mail::Make::Body::InCore->error ) );
332 $entity->body( $body );
333 }
334 else
335 {
336 return( $self->error( "build: a body is required for non-multipart type '$type' - provide 'data' or 'path'" ) );
337 }
338 }
339  
340 # NOTE: 10. Auto-suggest encoding if not specified
341 if( !$is_multipart && !defined( $encoding ) )
342 {
343 $entity->effective_type( $type );
344 $encoding = $entity->suggest_encoding;
345 }
346  
347 # NOTE: 11. Set the Content-Type header
348 $headers->replace( 'Content-Type' => $ct_obj->as_string );
349 $entity->effective_type( $type );
350  
351 # NOTE: 12. Set Content-Transfer-Encoding header (single-part only)
352 if( !$is_multipart && defined( $encoding ) && CORE::length( $encoding ) )
353 {
354 $headers->replace( 'Content-Transfer-Encoding' => $encoding );
355 }
356  
357 # NOTE: 13. Set Content-Disposition header
358 if( !$is_multipart && ( defined( $disposition ) || defined( $filename ) ) )
359 {
360 # Default to 'attachment' when we have a filename but no explicit disposition
361 $disposition //= ( defined( $filename ) ? 'attachment' : 'inline' );
362 my $cd_obj = Mail::Make::Headers::ContentDisposition->new( $disposition ) ||
363 return( $self->pass_error( Mail::Make::Headers::ContentDisposition->error ) );
364 if( defined( $filename ) )
365 {
366 $cd_obj->filename( $filename ) ||
367 return( $self->pass_error( $cd_obj->error ) );
368 }
369 $headers->replace( 'Content-Disposition' => $cd_obj->as_string );
370 }
371  
372 # NOTE: 14. Set Content-ID header (for inline parts)
373 if( defined( $cid ) && CORE::length( $cid ) )
374 {
375 # Ensure it's wrapped in angle brackets
376 $cid = "<${cid}>" unless( $cid =~ /\A<[^>]+>\z/ );
377 $headers->replace( 'Content-ID' => $cid );
378 }
379  
380 # NOTE: 15. Set Content-Description header
381 if( defined( $description ) && CORE::length( $description ) )
382 {
383 $headers->replace( 'Content-Description' => $description );
384 }
385  
386 return( $entity );
387 }
388  
389 # effective_type( [$type_string] )
390 # Gets or sets the cached effective MIME type string.
391 sub effective_type
392 {
393 my $self = shift( @_ );
394 if( @_ )
395 {
396 $self->{effective_type} = shift( @_ );
397 return( $self );
398 }
399 # Lazy: read from headers if not cached
400 unless( defined( $self->{effective_type} ) )
401 {
402 my $ct = $self->{headers}
403 ? ( $self->{headers}->content_type // '' )
404 : '';
405 # Strip parameters - just want type/subtype
406 ( $self->{effective_type} ) = ( $ct =~ m{^([^;\s]+)} );
407 }
408 return( $self->{effective_type} );
409 }
410  
411 # encode_body()
412 # Encodes the body according to the Content-Transfer-Encoding header.
413 # No-op if already encoded or no encoding header is set.
414 sub encode_body
415 {
416 my $self = shift( @_ );
417 return( $self ) if( $self->{is_encoded} );
418 my $enc = lc( $self->headers->content_transfer_encoding // '' );
419 return( $self ) unless( CORE::length( $enc ) );
420 my $body = $self->{body};
421 unless( defined( $body ) )
422 {
423 return( $self->error( "encode_body: no body to encode." ) );
424 }
425  
426 # 7bit / 8bit: no transformation needed
427 if( $enc ne 'base64' && $enc ne 'quoted-printable' )
428 {
429 $self->{is_encoded} = 1;
430 return( $self );
431 }
432  
433 # Open a read handle on the source body
434 my $from_fh = $body->open || return( $self->pass_error( $body->error ) );
435  
436 # Choose the output destination to mirror the source:
437 # Body::File → encode to a temp file (no large attachment loaded into RAM)
438 # Body::InCore → encode into a scalar buffer in memory
439 my $new_body;
440 if( $body->is_on_file )
441 {
442 my $tmp = $self->new_tempfile( open => 1 ) || return( $self->pass_error );
443 $tmp->binmode( ':raw' );
444 if( $enc eq 'base64' )
445 {
446 my $encoder = Mail::Make::Stream::Base64->new;
447 $encoder->encode( $from_fh => $tmp ) ||
448 return( $self->pass_error( $encoder->error ) );
449 }
450 else
451 {
452 my $encoder = Mail::Make::Stream::QuotedPrint->new;
453 $encoder->encode( $from_fh => $tmp ) ||
454 return( $self->pass_error( $encoder->error ) );
455 }
456 $new_body = Mail::Make::Body::File->new( "$tmp" ) ||
457 return( $self->pass_error( Mail::Make::Body::File->error ) );
458 }
459 else
460 {
461 my $out = '';
462 if( $enc eq 'base64' )
463 {
464 my $encoder = Mail::Make::Stream::Base64->new;
465 $encoder->encode( $from_fh => \$out ) ||
466 return( $self->pass_error( $encoder->error ) );
467 }
468 else
469 {
470 my $encoder = Mail::Make::Stream::QuotedPrint->new;
471 $encoder->encode( $from_fh => \$out ) ||
472 return( $self->pass_error( $encoder->error ) );
473 }
474 $new_body = Mail::Make::Body::InCore->new( $out ) ||
475 return( $self->pass_error( Mail::Make::Body::InCore->error ) );
476 }
477  
478 $self->{body} = $new_body;
479 $self->{is_encoded} = 1;
480 return( $self );
481 }
482  
483 # epilogue( [$arrayref] )
484 sub epilogue
485 {
486 my $self = shift( @_ );
487 if( @_ )
488 {
489 my $val = shift( @_ );
490 $self->{epilogue} = ref( $val ) eq 'ARRAY' ? $val : [ $val ];
491 return( $self );
492 }
493 return( $self->{epilogue} );
494 }
495  
496 # headers( [$headers_object] )
497 sub headers
498 {
499 my $self = shift( @_ );
500 if( @_ )
501 {
502 my $h = shift( @_ );
503 if( !$self->_is_a( $h => 'Mail::Make::Headers' ) )
504 {
505 return( $self->error( "headers: argument must be a Mail::Make::Headers object" ) );
506 }
507 $self->{headers} = $h;
508 return( $self );
509 }
510 unless( defined( $self->{headers} ) )
511 {
512 $self->{headers} = Mail::Make::Headers->new ||
513 return( $self->pass_error( Mail::Make::Headers->error ) );
514 }
515 return( $self->{headers} );
516 }
517  
518 # is_encoded( [$bool] )
519 sub is_encoded
520 {
521 my $self = shift( @_ );
522 if( @_ )
523 {
524 $self->{is_encoded} = shift( @_ ) ? 1 : 0;
525 return( $self );
526 }
527 return( $self->{is_encoded} );
528 }
529  
530 # is_multipart()
531 # Returns true if the effective MIME type is multipart/*.
532 sub is_multipart
533 {
534 my $self = shift( @_ );
535 my $type = $self->effective_type // '';
536 return( ( $type =~ m{^multipart/}i ) ? 1 : 0 );
537 }
538  
539 # is_binary()
540 # Returns true if the MIME type is not a text type.
541 sub is_binary
542 {
543 my $self = shift( @_ );
544 return( $self->textual_type( $self->effective_type ) ? 0 : 1 );
545 }
546  
547 # is_text()
548 sub is_text { return( !shift->is_binary ); }
549  
550 # length()
551 # Returns the exact serialised size in bytes of this entity (headers + CRLF separator +
552 # encoded body, recursively for multipart).
553 #
554 # The calculation mirrors print() exactly - no serialisation buffer is accumulated.
555 # For singlepart entities the body is encoded first (if not already done) and the
556 # encoded body's length is obtained via Body::File::length (stat on disk) or
557 # Body::InCore::length (in-memory scalar length) without loading the content into a
558 # fresh buffer.
559 # Headers are unavoidably stringified since they are always in memory.
560 sub length
561 {
562 my $self = shift( @_ );
563 my $total = 0;
564 use bytes;
565  
566 # Headers + the blank separator line
567 my $hdr_str = $self->headers->as_string;
568 $total += CORE::length( $hdr_str );
569 $total += CORE::length( $CRLF ); # blank line between headers and body
570  
571 if( $self->is_multipart )
572 {
573 my $boundary = $self->_extract_boundary;
574 unless( defined( $boundary ) && CORE::length( $boundary ) )
575 {
576 return( $self->error( "length: cannot measure multipart entity: no boundary." ) );
577 }
578  
579 # Preamble
580 if( @{$self->{preamble}} )
581 {
582 $total += CORE::length( join( $CRLF, @{$self->{preamble}} ) . $CRLF );
583 }
584  
585 for my $part ( @{$self->{_parts}} )
586 {
587 $total += CORE::length( "--${boundary}${CRLF}" );
588 my $part_len = $part->length;
589 return( $self->pass_error( $part->error ) ) unless( defined( $part_len ) );
590 $total += $part_len;
591 $total += CORE::length( $CRLF ); # post-part CRLF
592 }
593  
594 # Closing boundary
595 $total += CORE::length( "--${boundary}--${CRLF}" );
596  
597 # Epilogue
598 if( @{$self->{epilogue}} )
599 {
600 $total += CORE::length( join( $CRLF, @{$self->{epilogue}} ) . $CRLF );
601 }
602 }
603 elsif( @{$self->{_parts}} )
604 {
605 # Nested singlepart with sub-parts (e.g. message/rfc822)
606 my $need_sep = 0;
607 for my $part ( @{$self->{_parts}} )
608 {
609 $total += CORE::length( "${CRLF}${CRLF}" ) if( $need_sep++ );
610 my $part_len = $part->length;
611 return( $self->pass_error( $part->error ) ) unless( defined( $part_len ) );
612 $total += $part_len;
613 }
614 }
615 else
616 {
617 # Plain singlepart: encode if not already done, then ask the body for its byte
618 # length without reading it into a new buffer.
619 unless( defined( $self->{body} ) )
620 {
621 return( $self->error( "length: no body set on this entity." ) );
622 }
623 $self->encode_body || return( $self->pass_error );
624 my $body_len = $self->{body}->length;
625 return( $self->pass_error( $self->{body}->error ) ) unless( defined( $body_len ) );
626 $total += $body_len;
627 }
628  
629 return( $total );
630 }
631  
632 # make_boundary()
633 # Generates a unique boundary string suitable for MIME use.
634 sub make_boundary { return( Data::UUID->new->create_str ); }
635  
636 # mime_type()
637 # Returns just the type/subtype portion (no parameters).
638 sub mime_type
639 {
640 my $self = shift( @_ );
641 my $type = $self->effective_type // '';
642 ( my $bare ) = ( $type =~ m{^([^;\s]+)} );
643 return( $bare );
644 }
645  
646 # parts( [$arrayref_or_list] )
647 # Gets or sets the list of sub-parts.
648 sub parts
649 {
650 my $self = shift( @_ );
651 if( @_ )
652 {
653 my $parts = ref( $_[0] ) eq 'ARRAY' ? $_[0] : [ @_ ];
654 for my $part ( @$parts )
655 {
656 unless( $self->_is_a( $part => 'Mail::Make::Entity' ) )
657 {
658 return( $self->error( "parts: each element must be a Mail::Make::Entity" ) );
659 }
660 }
661 $self->{_parts} = $parts;
662 return( $self );
663 }
664 return( wantarray() ? @{$self->{_parts}} : $self->{_parts} );
665 }
666  
667 # preamble( [$arrayref] )
668 sub preamble
669 {
670 my $self = shift( @_ );
671 if( @_ )
672 {
673 my $val = shift( @_ );
674 $self->{preamble} = ref( $val ) eq 'ARRAY' ? $val : [ $val ];
675 return( $self );
676 }
677 return( $self->{preamble} );
678 }
679  
680 # print( [$fh] )
681 # Serialises the entity to a filehandle.
682 sub print
683 {
684 my $self = shift( @_ );
685 my $fh = shift( @_ ) ||
686 return( $self->error( "No file handle was provided to print the mail entity to." ) );
687 unless( $self->_is_glob( $fh ) )
688 {
689 return( $self->error( "Value provided (", $self->_str_val( $fh // 'undef' ), ") is not a file handle." ) );
690 }
691 # Headers
692 print( $fh $self->headers->as_string ) ||
693 return( $self->error( "Cannot write headers: $!" ) );
694 # Blank line separating headers from body
695 print( $fh $CRLF ) ||
696 return( $self->error( "Cannot write header/body separator: $!" ) );
697 # Body
698 $self->print_body( $fh ) || return( $self->pass_error );
699 return( $self );
700 }
701  
702 # print_body( [$fh] )
703 # Serialises the body (or multipart boundaries and sub-parts) to a filehandle.
704 sub print_body
705 {
706 my $self = shift( @_ );
707 my $fh = shift( @_ ) ||
708 return( $self->error( "No file handle was provided to print the mail entity to." ) );
709 unless( $self->_is_glob( $fh ) )
710 {
711 return( $self->error( "Value provided (", $self->_str_val( $fh // 'undef' ), ") is not a file handle." ) );
712 }
713 if( $self->is_multipart )
714 {
715 my $boundary = $self->_extract_boundary;
716 unless( defined( $boundary ) && CORE::length( $boundary ) )
717 {
718 return( $self->error( "Cannot serialise multipart entity: no boundary in Content-Type" ) );
719 }
720  
721 # Preamble
722 if( @{$self->{preamble}} )
723 {
724 print( $fh join( $CRLF, @{$self->{preamble}} ) . $CRLF );
725 }
726 foreach my $part ( @{$self->{_parts}} )
727 {
728 print( $fh "--${boundary}${CRLF}" ) ||
729 return( $self->error( "Cannot write part boundary: $!" ) );
730 $part->print( $fh ) ||
731 return( $self->pass_error( $part->error ) );
732 print( $fh $CRLF ) ||
733 return( $self->error( "Cannot write post-part CRLF: $!" ) );
734 }
735 print( $fh "--${boundary}--${CRLF}" ) ||
736 return( $self->error( "Cannot write closing boundary: $!" ) );
737 # Epilogue
738 if( @{$self->{epilogue}} )
739 {
740 print( $fh join( $CRLF, @{$self->{epilogue}} ) . $CRLF );
741 }
742 }
743 elsif( @{$self->{_parts}} )
744 {
745 # Nested singlepart with sub-parts (e.g. message/rfc822)
746 my $need_sep = 0;
747 foreach my $part ( @{$self->{_parts}} )
748 {
749 print( $fh "${CRLF}${CRLF}" ) if( $need_sep++ );
750 $part->print( $fh ) || return( $self->pass_error( $part->error ) );
751 }
752 }
753 else
754 {
755 # Plain single part
756 unless( defined( $self->{body} ) )
757 {
758 return( $self->error( "print_body: no body set on this entity" ) );
759 }
760 $self->encode_body || return( $self->pass_error );
761 my $in_ref = $self->{body}->as_string ||
762 return( $self->pass_error( $self->{body}->error ) );
763 print( $fh $$in_ref ) ||
764 return( $self->error( "Cannot write body: $!" ) );
765 }
766 return( $self );
767 }
768  
769 # stringify()
770 # Alias for as_string.
771 sub stringify { return( shift->as_string ); }
772  
773 sub stringify_ref { return( shift->as_string_ref ); }
774  
775 # stringify_body()
776 # Alias for body_as_string.
777 sub stringify_body { return( shift->body_as_string ); }
778  
779 # stringify_header()
780 sub stringify_header { return( shift->headers->as_string ); }
781  
782 # suggest_encoding()
783 # Returns a suitable Content-Transfer-Encoding for this entity's MIME type.
784 # Rules:
785 # multipart/* / message/* -> '' (no encoding)
786 # text/* -> quoted-printable
787 # everything else -> base64
788 sub suggest_encoding
789 {
790 my $self = shift( @_ );
791 my $type = $self->effective_type // '';
792 # Strip any parameters
793 ( $type ) = ( $type =~ m{^([^;\s]+)} );
794 $type = lc( $type );
795 return( '' ) if( $type =~ m{^multipart/} );
796 return( '' ) if( $type =~ m{^message/} );
797 return( 'quoted-printable' ) if( $type =~ m{^text/} );
798 return( 'base64' );
799 }
800  
801 # textual_type( $mime_type )
802 # Returns true if the given MIME type is a text or message type.
803 sub textual_type
804 {
805 my( $self, $type ) = @_;
806 return(0) unless( defined( $type ) && CORE::length( $type ) );
807 return( ( $type =~ m{^(text|message)(/|\z)}i ) ? 1 : 0 );
808 }
809  
810 # make_multipart( [ $subtype [, %opts] ] )
811 # Promotes a single-part entity to multipart by wrapping the existing body in a child
812 # entity and replacing the Content-Type with multipart/$subtype.
813 sub make_multipart
814 {
815 my $self = shift( @_ );
816 my $subtype = shift( @_ ) // 'mixed';
817 $subtype = lc( $subtype );
818 return( $self ) if( $self->is_multipart );
819 my $new_type = "multipart/${subtype}";
820 my $boundary = $self->make_boundary;
821 my $h = $self->headers;
822 if( $h )
823 {
824 my $ct_obj = Mail::Make::Headers::ContentType->new( $new_type ) ||
825 return( $self->pass_error( Mail::Make::Headers::ContentType->error ) );
826 $ct_obj->boundary( $boundary ) || return( $self->pass_error( $ct_obj->error ) );
827 $h->set( 'Content-Type', "$ct_obj" ) || return( $self->pass_error( $h->error ) );
828 $h->remove( 'Content-Transfer-Encoding' );
829 }
830 if( $self->body )
831 {
832 my $old_type = $self->effective_type;
833 my $child = Mail::Make::Entity->new ||
834 return( $self->pass_error );
835 my $child_h = Mail::Make::Headers->new ||
836 return( $self->pass_error( Mail::Make::Headers->error ) );
837 my $orig_ct = $h ? $h->get( 'Content-Type' ) : undef;
838 $child_h->set( 'Content-Type', $orig_ct ) if( defined( $orig_ct ) );
839 $child->headers( $child_h );
840 $child->body( $self->body );
841 $child->effective_type( $old_type );
842 $self->{body} = undef;
843 push( @{$self->{_parts}}, $child );
844 }
845 $self->effective_type( $new_type );
846 return( $self );
847 }
848  
849 # purge()
850 # Recursively releases body content.
851 sub purge
852 {
853 my $self = shift( @_ );
854 if( my $body = $self->body )
855 {
856 $body->purge;
857 $self->{body} = undef;
858 }
859 for my $part ( @{$self->{_parts}} )
860 {
861 $part->purge;
862 }
863 return( $self );
864 }
865  
866 # _extract_boundary()
867 # Pulls the boundary parameter out of the Content-Type header string.
868 sub _extract_boundary
869 {
870 my $self = shift( @_ );
871 # content_type() returns a typed object; we need the raw string.
872 my $ct = $self->headers->get( 'Content-Type' ) // '';
873 return( undef ) unless( CORE::length( $ct ) );
874 # Match boundary="..." or boundary=...
875 if( $ct =~ /;\s*boundary=(?:"([^"]+)"|([^;\s]+))/i )
876 {
877 return( $1 // $2 );
878 }
879 return( undef );
880 }
881  
882 # NOTE: STORABLE support
883 sub STORABLE_freeze { CORE::return( CORE::shift->FREEZE( @_ ) ); }
884  
885 sub STORABLE_thaw { CORE::return( CORE::shift->THAW( @_ ) ); }
886  
887 1;
888 # NOTE: POD
889 __END__