blib/lib/Mail/Make.pm untested

filter: Statementstmt 0.0% 0 / 492 Branchbran 0.0% 0 / 240 Conditioncond 0.0% 0 / 281 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 58 Podpod 0.0% 0 / 40 totaltotal 0.0% 0 / 1111 CC 121 SCAR 59.3
CC
121
Cov
0%
smtpsend
1560.0
build
182.0
as_entity
156.0
CRAP 375.4
1 ##----------------------------------------------------------------------------
2 ## MIME Email Builder - ~/lib/Mail/Make.pm
3 ## Version v0.22.0
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;
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 $MAX_BODY_IN_MEMORY_SIZE );
22 use Mail::Make::Entity;
23 use Mail::Make::Exception;
24 use Mail::Make::Headers;
25 use Mail::Make::Headers::Subject;
26 use Scalar::Util ();
27 our $CRLF = "\015\012";
28 our $MAX_BODY_IN_MEMORY_SIZE = 1_048_576; # 1 MiB default
29 our $EXCEPTION_CLASS = 'Mail::Make::Exception';
30 our $VERSION = 'v0.22.0';
31 }
32  
33 use strict;
34 use warnings;
35  
36 sub init
37 {
38 my $self = shift( @_ );
39 # Top-level envelope headers live in a Mail::Make::Headers instance.
40 # All RFC 2822 envelope fields (From, To, Cc, Bcc, Subject, Date, Message-ID,
41 # In-Reply-To, References, Reply-To, Sender) are stored there directly, avoiding any
42 # duplication between Mail::Make and the final Mail::Make::Entity's headers object.
43 $self->{_headers} = Mail::Make::Headers->new;
44 # Accumulated body parts (Mail::Make::Entity objects, in order of addition)
45 $self->{_parts} = [];
46 # When the serialised message exceeds this byte threshold (or when use_temp_file is true),
47 # as_string_ref() spools to a temporary file rather than keeping the entire message in RAM.
48 # Set to 0 or undef to disable file spooling entirely.
49 $self->{max_body_in_memory_size} = $MAX_BODY_IN_MEMORY_SIZE;
50 $self->{use_temp_file} = 0;
51 $self->{_exception_class} = $EXCEPTION_CLASS;
52 $self->{_init_strict_use_sub} = 1;
53 $self->SUPER::init( @_ ) || return( $self->pass_error );
54 return( $self );
55 }
56  
57 # as_entity()
58 # Returns the fully assembled top-level Mail::Make::Entity object.
59 # The MIME structure is chosen based on the accumulated parts:
60 #
61 # Only plain text -> text/plain
62 # Only HTML -> text/html
63 # Plain + HTML -> multipart/alternative
64 # Any of the above + inlines -> multipart/related
65 # Any of the above + attachments -> multipart/mixed
66 sub as_entity
67 {
68 my $self = shift( @_ );
69  
70 # When gpg_sign() / gpg_encrypt() / gpg_sign_encrypt() have already assembled the
71 # top-level entity (stored in _gpg_entity), return it directly. Envelope headers have
72 # already been merged by _wrap_in_mail().
73 return( $self->{_gpg_entity} ) if( defined( $self->{_gpg_entity} ) );
74  
75 # S/MIME: entity pre-assembled by Mail::Make::SMIME::_build_from_smime_output().
76 # Headers are already embedded in the parsed entity; return it directly.
77 return( $self->{_smime_entity} ) if( defined( $self->{_smime_entity} ) );
78  
79 # Partition accumulated parts by role
80 my( @plain, @html, @inline, @attachment );
81 for my $part ( @{$self->{_parts}} )
82 {
83 my $type = lc( $part->effective_type // '' );
84 # Use get() for the raw string value; content_disposition() returns a typed
85 # object which stringifies to '' when uninitialised, making // unreliable.
86 my $cd = lc( $part->headers->get( 'Content-Disposition' ) // '' );
87 if( $type eq 'text/plain' && $cd !~ /attachment/ )
88 {
89 push( @plain, $part );
90 }
91 elsif( $type eq 'text/html' && $cd !~ /attachment/ )
92 {
93 push( @html, $part );
94 }
95 elsif( $cd =~ /inline/ && $part->headers->get( 'Content-ID' ) )
96 {
97 push( @inline, $part );
98 }
99 else
100 {
101 push( @attachment, $part );
102 }
103 }
104  
105 # NOTE: Step 1: build the text body (plain, html, or alternative)
106 my $body_entity;
107 if( @plain && @html )
108 {
109 $body_entity = Mail::Make::Entity->build( type => 'multipart/alternative' ) ||
110 return( $self->pass_error( Mail::Make::Entity->error ) );
111 $body_entity->add_part( $_ ) for( @plain );
112 $body_entity->add_part( $_ ) for( @html );
113 }
114 elsif( @html )
115 {
116 $body_entity = $html[0];
117 }
118 elsif( @plain )
119 {
120 $body_entity = $plain[0];
121 }
122 else
123 {
124 return( $self->error( "No body parts have been added." ) );
125 }
126  
127 # NOTE: Step 2: wrap in multipart/related if there are inline parts
128 my $related_entity = $body_entity;
129 if( @inline )
130 {
131 $related_entity = Mail::Make::Entity->build( type => 'multipart/related' ) ||
132 return( $self->pass_error( Mail::Make::Entity->error ) );
133 $related_entity->add_part( $body_entity );
134 $related_entity->add_part( $_ ) for( @inline );
135 }
136  
137 # NOTE: Step 3: wrap in multipart/mixed if there are attachments
138 my $top_entity = $related_entity;
139 if( @attachment )
140 {
141 $top_entity = Mail::Make::Entity->build( type => 'multipart/mixed' ) ||
142 return( $self->pass_error( Mail::Make::Entity->error ) );
143 $top_entity->add_part( $related_entity );
144 $top_entity->add_part( $_ ) for( @attachment );
145 }
146  
147 # NOTE: Step 4: transfer envelope headers to the top-level entity
148 # We merge our own _headers into the entity's headers object so that MIME-specific
149 # headers already set on the entity (Content-Type, CTE, etc.) take precedence, while
150 # envelope headers come from _headers.
151 # Any header already present in the entity headers is left untouched.
152 my $ent_headers = $top_entity->headers;
153  
154 # Auto-generate Date if not set
155 $self->{_headers}->init_header(
156 'Date' => $self->_format_date()
157 );
158  
159 # Auto-generate Message-ID if not set
160 unless( $self->{_headers}->exists( 'Message-ID' ) )
161 {
162 $self->{_headers}->message_id( { generate => 1, domain => $self->_default_domain } ) ||
163 return( $self->pass_error( $self->{_headers}->error ) );
164 }
165  
166 # MIME-Version is always added to the entity's own headers (not the envelope), since
167 # it belongs at the top of the MIME structure.
168 $ent_headers->init_header( 'MIME-Version' => '1.0' );
169  
170 # Merge envelope headers into the entity: each field from _headers that is not already
171 # present in ent_headers is copied over.
172 $self->{_headers}->scan( sub
173 {
174 my( $name, $value ) = @_;
175 $ent_headers->init_header( $name => $value );
176 return(1);
177 });
178  
179 return( $top_entity );
180 }
181  
182 # as_string()
183 # Assembles the message and returns it as a plain string, consistent with
184 # MIME::Entity::stringify. Use print($fh) to avoid loading the whole message into memory,
185 # or as_string_ref() to avoid a string copy.
186 sub as_string
187 {
188 my $self = shift( @_ );
189 my $entity = $self->as_entity || return( $self->pass_error );
190 return( $entity->as_string( @_ ) );
191 }
192  
193 # as_string_ref()
194 # Returns the assembled message as a scalar reference (no string copy).
195 # When use_temp_file is true, or the serialised entity size exceeds max_body_in_memory_size,
196 # the message is written to a Module::Generic::Scalar buffer, thus keeping peak RAM use
197 # to a single copy rather than two overlapping buffers (the serialisation buffer plus the
198 # returned string).
199 sub as_string_ref
200 {
201 my $self = shift( @_ );
202 my $entity = $self->as_entity || return( $self->pass_error );
203 my $threshold = $self->{max_body_in_memory_size};
204 my $force_file = $self->{use_temp_file};
205  
206 # Fast path: build directly in memory when neither condition applies
207 unless( $force_file || ( defined( $threshold ) && $threshold > 0 && $entity->length > $threshold ) )
208 {
209 return( $entity->as_string_ref );
210 }
211  
212 # new_scalar() is inherited from Module::Generic, and returns a Module::Generic::Scalar object
213 my $buf = $self->new_scalar;
214 # In-memory fielhandle; returns a Module::Generic::Scalar::IO object
215 my $fh = $buf->open( '>', { binmode => ':raw', autoflush => 1 } ) || return( $buf->error );
216 $entity->print( $fh ) || return( $self->pass_error( $entity->error ) );
217 # The scalar object stringifies as necessary.
218 return( $buf );
219 }
220  
221 # attach( %opts )
222 # Adds a standard (downloadable) attachment.
223 # Recognised keys: path, data, type, filename, charset, encoding, description
224 sub attach
225 {
226 my $self = shift( @_ );
227 # Detect positional shorthand: attach( '/path/to/file.pdf' ) or
228 # attach( '/path/to/file.pdf', encoding => 'base64', ... )
229 # Triggered when argument count is odd and the first argument is a plain scalar
230 # (not a reference), contains no newline, and resolves to an existing file.
231 if( ( scalar( @_ ) % 2 ) &&
232 ( !ref( $_[0] ) || $self->_can_overload( $_[0] => '""' ) ) &&
233 index( "$_[0]", "\n" ) == -1 )
234 {
235 # shift() first to avoid $_[0] being altered by new_file() resolution
236 my $f = $self->new_file( shift( @_ ) ); # Module::Generic::File will trigger stringification
237 if( $f->exists )
238 {
239 # then, we pass it back here:
240 unshift( @_, path => $f );
241 }
242 }
243 my $opts = $self->_get_args_as_hash( @_ );
244 unless( defined( $opts->{data} ) || defined( $opts->{path} ) )
245 {
246 return( $self->error( "attach(): 'data' or 'path' is required." ) );
247 }
248 $opts->{disposition} //= 'attachment';
249 my $entity = Mail::Make::Entity->build( %$opts ) ||
250 return( $self->pass_error( Mail::Make::Entity->error ) );
251 push( @{$self->{_parts}}, $entity );
252 return( $self );
253 }
254  
255 # attach_inline( %opts )
256 # Adds an inline part (e.g. an image referenced via cid: in HTML).
257 # 'id' or 'cid' is required.
258 sub attach_inline
259 {
260 my $self = shift( @_ );
261 my $opts = $self->_get_args_as_hash( @_ );
262 unless( defined( $opts->{data} ) || defined( $opts->{path} ) )
263 {
264 return( $self->error( "attach_inline(): 'data' or 'path' is required." ) );
265 }
266 unless( defined( $opts->{id} ) || defined( $opts->{cid} ) )
267 {
268 return( $self->error( "attach_inline(): 'id' or 'cid' is required for inline parts." ) );
269 }
270 # Normalise: Entity->build() expects 'cid'
271 $opts->{cid} //= delete( $opts->{id} );
272 $opts->{disposition} //= 'inline';
273 my $entity = Mail::Make::Entity->build( %$opts ) ||
274 return( $self->pass_error( Mail::Make::Entity->error ) );
275 push( @{$self->{_parts}}, $entity );
276 return( $self );
277 }
278  
279 # bcc( @addresses )
280 # Accumulates BCC recipients (may be called multiple times).
281 sub bcc
282 {
283 my $self = shift( @_ );
284 if( @_ )
285 {
286 my @encoded = map { $self->_encode_address( $_ ) } ( ref( $_[0] ) eq 'ARRAY' ? @{$_[0]} : @_ );
287 $self->{_headers}->push_header( 'Bcc' => join( ', ', @encoded ) ) ||
288 return( $self->pass_error( $self->{_headers}->error ) );
289 return( $self );
290 }
291 return( $self->{_headers}->header( 'Bcc' ) );
292 }
293  
294 # build( %params ) - alternate hash-based constructor/factory
295 # Returns a Mail::Make object with all parameters applied.
296 sub build
297 {
298 my $class = shift( @_ );
299 my $params = $class->_get_args_as_hash( @_ );
300 my $self = $class->new || return( $class->pass_error );
301  
302 # Scalar envelope fields
303 foreach my $field ( qw( date from in_reply_to message_id reply_to return_path sender subject ) )
304 {
305 $self->$field( $params->{ $field } ) || return( $self->pass_error )
306 if( exists( $params->{ $field } ) );
307 }
308 # List fields
309 foreach my $field ( qw( bcc cc references to ) )
310 {
311 if( exists( $params->{ $field } ) )
312 {
313 my $v = $params->{ $field };
314 $self->$field( ref( $v ) eq 'ARRAY' ? @$v : $v ) || return( $self->pass_error );
315 }
316 }
317 # Body convenience shorthands
318 if( exists( $params->{plain} ) )
319 {
320 if( exists( $params->{plain_opts} ) && ref( $params->{plain_opts} ) ne 'HASH' )
321 {
322 return( $self->error( "The parameter 'plain_opts' must be a hash reference. You provided '", $self->_str_val( $params->{plain_opts} // 'undef' ), "'." ) );
323 }
324 my %opts = %{$params->{plain_opts} // {}};
325 $self->plain( $params->{plain}, %opts ) || return( $self->pass_error );
326 }
327 if( exists( $params->{html} ) )
328 {
329 if( exists( $params->{html_opts} ) && ref( $params->{html_opts} ) ne 'HASH' )
330 {
331 return( $self->error( "The parameter 'html_opts' must be a hash reference. You provided '", $self->_str_val( $params->{html_opts} // 'undef' ), "'." ) );
332 }
333 my %opts = %{$params->{html_opts} // {}};
334 $self->html( $params->{html}, %opts ) || return( $self->pass_error );
335 }
336 # Attachments: scalar, arrayref of scalars, or arrayref of hashrefs
337 if( exists( $params->{attach} ) && defined( $params->{attach} ) )
338 {
339 my $attach = $params->{attach};
340 # Accepts vanilla array reference or array objects like Module::Generic::Array
341 my @items = $self->_is_array( $attach ) ? @$attach : ( $attach );
342 foreach my $item ( @items )
343 {
344 next unless( defined( $item ) );
345 # Such as:
346 # { path => '/some/where/file.pdf', filename => '04 report.pdf', type => 'application/pdf' }
347 # { data => $attachment_data, filename => '04 report.pdf', type => 'application/pdf' }
348 if( ref( $item ) eq 'HASH' )
349 {
350 $self->attach( %$item ) || return( $self->pass_error );
351 }
352 else
353 {
354 # Plain scalar or stringifiable object - delegate to attach() which
355 # already handles the positional shorthand
356 # So, this can be an attachment data, or a file path, or a file object
357 # like Module::Generic::File (as long as it stringifies) and does not
358 # contain a "\n"
359 $self->attach( $item ) || return( $self->pass_error );
360 }
361 }
362 }
363 # Extra arbitrary headers
364 if( exists( $params->{headers} ) && ref( $params->{headers} ) eq 'HASH' )
365 {
366 while( my( $n, $v ) = each( %{$params->{headers}} ) )
367 {
368 $self->header( $n, $v ) || return( $self->pass_error );
369 }
370 }
371 return( $self );
372 }
373  
374 # cc( @addresses )
375 # Accumulates CC recipients.
376 sub cc
377 {
378 my $self = shift( @_ );
379 if( @_ )
380 {
381 my @encoded = map { $self->_encode_address( $_ ) } ( ref( $_[0] ) eq 'ARRAY' ? @{$_[0]} : @_ );
382 $self->{_headers}->push_header( 'Cc' => join( ', ', @encoded ) ) ||
383 return( $self->pass_error( $self->{_headers}->error ) );
384 return( $self );
385 }
386 return( $self->{_headers}->header( 'Cc' ) );
387 }
388  
389 # date( [$date_string_or_epoch] )
390 # Delegates to Mail::Make::Headers::date(), which handles epoch integers, string validation,
391 # and RFC 5322 formatting.
392 sub date
393 {
394 my $self = shift( @_ );
395 if( @_ )
396 {
397 $self->{_headers}->date( @_ ) ||
398 return( $self->pass_error( $self->{_headers}->error ) );
399 return( $self );
400 }
401 return( $self->{_headers}->date );
402 }
403  
404 # from( [$address] )
405 sub from
406 {
407 my $self = shift( @_ );
408 if( @_ )
409 {
410 my $addr = $self->_encode_address( shift( @_ ) );
411 $self->{_headers}->set( 'From' => $addr ) ||
412 return( $self->pass_error( $self->{_headers}->error ) );
413 return( $self );
414 }
415 return( $self->{_headers}->header( 'From' ) );
416 }
417  
418 # header( $name, $value )
419 # Appends an arbitrary extra header to the envelope (push_header semantics: does not
420 # replace, allows multiple values for the same field).
421 sub header
422 {
423 my $self = shift( @_ );
424 if( @_ == 1 )
425 {
426 # Getter shortcut
427 return( $self->{_headers}->header( $_[0] ) );
428 }
429 my( $name, $value ) = @_;
430 unless( defined( $name ) && length( $name ) && defined( $value ) )
431 {
432 return( $self->error( "header(): name and value are required." ) );
433 }
434 $self->{_headers}->push_header( $name => $value ) ||
435 return( $self->pass_error( $self->{_headers}->error ) );
436 return( $self );
437 }
438  
439 # headers()
440 # Returns the Mail::Make::Headers object that holds the envelope headers.
441 # Read-only: the object is created in init() and is not replaceable from outside, to
442 # prevent accidental aliasing.
443 sub headers { return( $_[0]->{_headers} ); }
444  
445 # html( $content [, %opts] )
446 # Adds a text/html body part.
447 sub html
448 {
449 my $self = shift( @_ );
450 my $text = shift( @_ );
451 my $opts = $self->_get_args_as_hash( @_ );
452 unless( defined( $text ) )
453 {
454 return( $self->error( "html(): text content is required." ) );
455 }
456 my $part = Mail::Make::Entity->build(
457 type => 'text/html',
458 charset => ( $opts->{charset} // 'utf-8' ),
459 encoding => ( $opts->{encoding} // 'quoted-printable' ),
460 data => $text,
461 ) || return( $self->pass_error( Mail::Make::Entity->error ) );
462 push( @{$self->{_parts}}, $part );
463 return( $self );
464 }
465  
466 # in_reply_to( [$mid] )
467 sub in_reply_to
468 {
469 my $self = shift( @_ );
470 if( @_ )
471 {
472 $self->{_headers}->set( 'In-Reply-To' => shift( @_ ) ) ||
473 return( $self->pass_error( $self->{_headers}->error ) );
474 return( $self );
475 }
476 return( $self->{_headers}->header( 'In-Reply-To' ) );
477 }
478  
479 # max_body_in_memory_size( [$bytes] )
480 # Gets or sets the byte threshold above which as_string_ref() spools to a temporary file.
481 # Set to 0 to disable the threshold (always use memory).
482 # Default: $Mail::Make::MAX_BODY_IN_MEMORY_SIZE (1 MiB).
483 sub max_body_in_memory_size { return( shift->_set_get_number( 'max_body_in_memory_size', @_ ) ); }
484  
485 # message_id( [$mid | \%opts] )
486 # Delegates fully to Mail::Make::Headers::message_id(), which handles generation,
487 # validation, and removal.
488 sub message_id
489 {
490 my $self = shift( @_ );
491 if( @_ )
492 {
493 $self->{_headers}->message_id( @_ ) ||
494 return( $self->pass_error( $self->{_headers}->error ) );
495 return( $self );
496 }
497 return( $self->{_headers}->message_id );
498 }
499  
500 # plain( $content [, %opts] )
501 # Adds a text/plain body part.
502 sub plain
503 {
504 my $self = shift( @_ );
505 my $text = shift( @_ );
506 my $opts = $self->_get_args_as_hash( @_ );
507 unless( defined( $text ) )
508 {
509 return( $self->error( "plain(): text content is required." ) );
510 }
511 my $part = Mail::Make::Entity->build(
512 type => 'text/plain',
513 charset => ( $opts->{charset} // 'utf-8' ),
514 encoding => ( $opts->{encoding} // 'quoted-printable' ),
515 data => $text,
516 ) || return( $self->pass_error( Mail::Make::Entity->error ) );
517 push( @{$self->{_parts}}, $part );
518 return( $self );
519 }
520  
521 # print( $fh )
522 # Serialises the assembled message to a filehandle.
523 sub print
524 {
525 my $self = shift( @_ );
526 my $fh = shift( @_ ) ||
527 return( $self->error( "No file handle was provided to print the mail entity." ) );
528 unless( $self->_is_glob( $fh ) )
529 {
530 return( $self->error( "Value provided (", $self->_str_val( $fh // 'undef' ), ") is not a file handle." ) );
531 }
532 my $entity = $self->as_entity || return( $self->pass_error );
533 $entity->print( $fh ) || return( $self->pass_error( $entity->error ) );
534 return( $self );
535 }
536  
537 # references( @mids )
538 # Accumulates Message-ID references.
539 sub references
540 {
541 my $self = shift( @_ );
542 if( @_ )
543 {
544 my @mids = ( ref( $_[0] ) eq 'ARRAY' ? @{$_[0]} : @_ );
545 # References is a single folded header: accumulate by appending.
546 my $existing = $self->{_headers}->header( 'References' ) // '';
547 my $new = join( ' ', grep{ length( $_ ) } $existing, @mids );
548 $self->{_headers}->set( 'References' => $new ) ||
549 return( $self->pass_error( $self->{_headers}->error ) );
550 return( $self );
551 }
552 return( $self->{_headers}->header( 'References' ) );
553 }
554  
555 # reply_to( [$address] )
556 sub reply_to
557 {
558 my $self = shift( @_ );
559 if( @_ )
560 {
561 my $addr = $self->_encode_address( shift( @_ ) );
562 $self->{_headers}->set( 'Reply-To' => $addr ) ||
563 return( $self->pass_error( $self->{_headers}->error ) );
564 return( $self );
565 }
566 return( $self->{_headers}->header( 'Reply-To' ) );
567 }
568  
569 # return_path( [$address] )
570 sub return_path
571 {
572 my $self = shift( @_ );
573 if( @_ )
574 {
575 my $addr = $self->_encode_address( shift( @_ ) );
576 $self->{_headers}->set( 'Return-Path' => $addr ) ||
577 return( $self->pass_error( $self->{_headers}->error ) );
578 return( $self );
579 }
580 return( $self->{_headers}->header( 'Return-Path' ) );
581 }
582  
583 # sender( [$address] )
584 sub sender
585 {
586 my $self = shift( @_ );
587 if( @_ )
588 {
589 my $addr = $self->_encode_address( shift( @_ ) );
590 $self->{_headers}->set( 'Sender' => $addr ) ||
591 return( $self->pass_error( $self->{_headers}->error ) );
592 return( $self );
593 }
594 return( $self->{_headers}->header( 'Sender' ) );
595 }
596  
597 # smtpsend( %opts )
598 # Assembles the message and submits it via SMTP using Net::SMTP.
599 #
600 # Recognised options:
601 # Host => $hostname_or_Net_SMTP_object
602 # Defaults to trying $ENV{SMTPHOSTS} (colon-separated),
603 # 'mailhost', then 'localhost'.
604 # MailFrom => $envelope_sender (MAIL FROM)
605 # Defaults to the From: header address-spec.
606 # To => \@recipients Override the To header for RCPT TO.
607 # Cc => \@recipients Additional CC addresses for RCPT TO.
608 # Bcc => \@recipients Additional BCC addresses for RCPT TO.
609 # Note: Bcc is stripped from the outgoing headers per RFC 2822 §3.6.3.
610 # Hello => $fqdn EHLO/HELO hostname.
611 # Port => $port SMTP port (default 25).
612 # Debug => $bool Enable Net::SMTP debug output.
613 #
614 # Returns the list of recipients successfully handed to the MTA on success, or undef and
615 # sets error() on failure.
616 sub smtpsend
617 {
618 my $self = shift( @_ );
619 my $opts = $self->_get_args_as_hash( @_ );
620  
621 $self->_load_class( 'Net::SMTP' ) || return( $self->pass_error );
622  
623 # Build the entity first so we can inspect its headers
624 my $entity = $self->as_entity || return( $self->pass_error );
625  
626 # Determine envelope sender (MAIL FROM)
627 my $mail_from = $opts->{MailFrom};
628 unless( defined( $mail_from ) && length( $mail_from ) )
629 {
630 my $from_hdr = $self->{_headers}->header( 'From' ) // '';
631 if( $from_hdr =~ /<([^>]+)>/ )
632 {
633 $mail_from = $1;
634 }
635 else
636 {
637 ( $mail_from = $from_hdr ) =~ s/\s+//g;
638 }
639 }
640  
641 unless( defined( $mail_from ) && length( $mail_from ) )
642 {
643 return( $self->error( "smtpsend(): cannot determine envelope sender (MAIL FROM). Set MailFrom or From header." ) );
644 }
645  
646 # Validate auth credentials before touching the network
647 # Password may be a plain string or a CODE ref (resolved later).
648 my $username = $opts->{Username};
649 my $password = $opts->{Password};
650  
651 if( defined( $username ) && length( $username ) )
652 {
653 unless( defined( $password ) )
654 {
655 return( $self->error( "smtpsend(): Username supplied but Password is missing." ) );
656 }
657  
658 # Authen::SASL and MIME::Base64 are required for SMTP AUTH.
659 # Check early so the error is clear rather than a cryptic auth failure.
660 foreach my $mod ( qw( MIME::Base64 Authen::SASL ) )
661 {
662 $self->_load_class( $mod ) ||
663 return( $self->error( "smtpsend(): SMTP authentication requires $mod, which is not installed. Install it with: cpan $mod" ) );
664 }
665 }
666  
667 # Determine RCPT TO addresses before connecting, so we can bail early.
668 # Honour explicit override lists first; fall back to message headers.
669 my @rcpt_raw;
670 foreach my $field ( qw( To Cc Bcc ) )
671 {
672 my $v = $opts->{ $field };
673 if( defined( $v ) )
674 {
675 push( @rcpt_raw, ref( $v ) eq 'ARRAY' ? @$v : $v );
676 }
677 else
678 {
679 my $hv = $self->{_headers}->header( $field ) // '';
680 push( @rcpt_raw, $hv ) if( length( $hv ) );
681 }
682 }
683  
684 # Parse each raw value into bare addr-specs
685 my @addr;
686 foreach my $raw ( @rcpt_raw )
687 {
688 my @found_angle;
689 while( $raw =~ /<([^>]+)>/g )
690 {
691 push( @found_angle, $1 );
692 }
693 if( @found_angle )
694 {
695 push( @addr, @found_angle );
696 }
697 else
698 {
699 # Bare comma-separated list (no angle brackets)
700 push( @addr, grep{ /\@/ } map{ s/^\s+|\s+$//gr } split( /,/, $raw ) );
701 }
702 }
703 # Deduplicate while preserving order
704 my %seen;
705 @addr = grep{ !$seen{ $_ }++ } @addr;
706  
707 unless( @addr )
708 {
709 return( $self->error( "smtpsend(): no recipients found." ) );
710 }
711  
712 # Build Net::SMTP connection options
713 # SSL => 1 : direct SSL/TLS (e.g. port 465, aka SMTPS)
714 my @smtp_opts;
715 push( @smtp_opts, Hello => $opts->{Hello} ) if( defined( $opts->{Hello} ) );
716 push( @smtp_opts, Port => $opts->{Port} ) if( defined( $opts->{Port} ) );
717 push( @smtp_opts, Debug => $opts->{Debug} ) if( defined( $opts->{Debug} ) );
718 push( @smtp_opts, Timeout => $opts->{Timeout} ) if( defined( $opts->{Timeout} ) );
719 if( $opts->{SSL} )
720 {
721 push( @smtp_opts, SSL => 1 );
722 if( ref( $opts->{SSL_opts} ) eq 'HASH' )
723 {
724 push( @smtp_opts, %{$opts->{SSL_opts}} );
725 }
726 }
727  
728 # NOTE: SMTP connect
729 my $smtp;
730 my $quit = 1;
731 my $host = $opts->{Host};
732  
733 if( !defined( $host ) )
734 {
735 my @hosts = qw( mailhost localhost );
736 if( defined( $ENV{SMTPHOSTS} ) && length( $ENV{SMTPHOSTS} ) )
737 {
738 unshift( @hosts, split( /:/, $ENV{SMTPHOSTS} ) );
739 }
740  
741 foreach my $h ( @hosts )
742 {
743 local $@;
744 $smtp = eval{ Net::SMTP->new( $h, @smtp_opts ) };
745 last if( defined( $smtp ) );
746 }
747 }
748 elsif( $self->_is_a( $host => 'Net::SMTP' ) )
749 {
750 # Caller passes an already-connected object; we must not quit it.
751 $smtp = $host;
752 $quit = 0;
753 }
754 else
755 {
756 local $@;
757 $smtp = eval{ Net::SMTP->new( $host, @smtp_opts ) };
758 }
759  
760 unless( defined( $smtp ) )
761 {
762 return( $self->error( "smtpsend(): could not connect to any SMTP server." ) );
763 }
764  
765 # STARTTLS upgrade (ignored when caller supplied a pre-built object or SSL)
766 if( $opts->{StartTLS} && $quit )
767 {
768 my %tls_opts;
769 if( ref( $opts->{SSL_opts} ) eq 'HASH' )
770 {
771 %tls_opts = %{$opts->{SSL_opts}};
772 }
773 unless( $smtp->starttls( %tls_opts ) )
774 {
775 my $smtp_msg = join( ' ', $smtp->message );
776 $smtp->quit;
777 return( $self->error( "smtpsend(): STARTTLS negotiation failed" . ( length( $smtp_msg ) ? ": $smtp_msg" : '.' ) ) );
778 }
779 }
780  
781 # -------------------------------------------------------------------------
782 # SMTP Authentication (SASL via Authen::SASL + Net::SMTP::auth)
783 # Password is resolved here so the CODE ref is called as late as possible.
784 #
785 # We build an explicit Authen::SASL object rather than letting Net::SMTP
786 # pick the mechanism freely. Left to itself, Authen::SASL prefers
787 # DIGEST-MD5 and CRAM-MD5, which are both deprecated (RFC 6331, RFC 8314) and
788 # routinely disabled on modern Postfix/Dovecot servers. Over an already
789 # encrypted STARTTLS or SSL channel, PLAIN and LOGIN are both safe and
790 # universally supported.
791 #
792 # Mechanism selection:
793 # 1. Caller may supply an explicit list via AuthMechanisms option.
794 # 2. Otherwise we use our preferred order: PLAIN LOGIN.
795 # 3. We intersect with what the server actually advertises (supports AUTH).
796 # -------------------------------------------------------------------------
797 if( defined( $username ) && length( $username ) )
798 {
799 if( ref( $password ) eq 'CODE' )
800 {
801 local $@;
802 $password = eval{ $password->() };
803 if( $@ || !defined( $password ) )
804 {
805 $smtp->quit if( $quit );
806 return( $self->error( "smtpsend(): password callback failed: " . ( $@ // 'returned undef' ) ) );
807 }
808 }
809  
810 # Determine which mechanisms the server advertises
811 my $server_mechs = $smtp->supports( 'AUTH' ) // '';
812  
813 # Build the preferred mechanism list
814 my $preferred = $opts->{AuthMechanisms} // 'PLAIN LOGIN';
815  
816 # Intersect: keep only those the server supports, preserving our order
817 my %server_set = map{ uc( $_ ) => 1 } split( /\s+/, $server_mechs );
818 my @agreed = grep{ $server_set{ uc( $_ ) } } split( /\s+/, $preferred );
819  
820 if( !@agreed )
821 {
822 # No intersection -- fall back to whatever the server offers,
823 # excluding the deprecated challenge-response mechanisms.
824 @agreed = grep{ !/^(?:DIGEST-MD5|CRAM-MD5|GSSAPI)$/i }
825 split( /\s+/, $server_mechs );
826 }
827  
828 my $sasl = Authen::SASL->new(
829 mechanism => join( ' ', @agreed ),
830 callback => {
831 user => $username,
832 pass => $password,
833 authname => $username,
834 },
835 );
836  
837 unless( $smtp->auth( $sasl ) )
838 {
839 # Capture the server's error message for a more useful diagnostic
840 my $smtp_msg = join( ' ', $smtp->message );
841 $smtp->quit if( $quit );
842 return( $self->error( "smtpsend(): SMTP authentication failed for user '$username'" . ( length( $smtp_msg ) ? ": $smtp_msg" : '.' ) ) );
843 }
844 }
845  
846 # Serialise message, stripping Bcc from transmitted copy
847 my $send_entity = $self->as_entity || do
848 {
849 $smtp->quit if( $quit );
850 return( $self->pass_error );
851 };
852 $send_entity->headers->remove( 'Bcc' );
853 my $msg = $send_entity->as_string || do
854 {
855 $smtp->quit if( $quit );
856 return( $self->pass_error( $send_entity->error ) );
857 };
858  
859 # Submit
860 my $ok = $smtp->mail( $mail_from )
861 && $smtp->to( @addr )
862 && $smtp->data( $msg );
863  
864 $smtp->quit if( $quit );
865  
866 unless( $ok )
867 {
868 return( $self->error( "smtpsend(): SMTP transaction failed." ) );
869 }
870  
871 return( wantarray() ? @addr : \@addr );
872 }
873  
874 # subject( [$string] )
875 # RFC 2047-encodes non-ASCII subjects before storing.
876 sub subject
877 {
878 my $self = shift( @_ );
879 if( @_ )
880 {
881 my $enc = $self->_encode_header( shift( @_ ) );
882 $self->{_headers}->set( 'Subject' => $enc ) ||
883 return( $self->pass_error( $self->{_headers}->error ) );
884 return( $self );
885 }
886 return( $self->{_headers}->header( 'Subject' ) );
887 }
888  
889 # to( @addresses )
890 # Accumulates To recipients.
891 sub to
892 {
893 my $self = shift( @_ );
894 if( @_ )
895 {
896 my @encoded = map{ $self->_encode_address( $_ ) } ( ref( $_[0] ) eq 'ARRAY' ? @{$_[0]} : @_ );
897 # Merge into a single To: header (RFC 5322 §3.6.3 allows only one To field)
898 my $existing = $self->{_headers}->header( 'To' );
899 my $new_val = join( ', ', grep{ defined( $_ ) && length( $_ ) } $existing, @encoded );
900 $self->{_headers}->set( 'To' => $new_val ) ||
901 return( $self->pass_error( $self->{_headers}->error ) );
902 return( $self );
903 }
904 return( $self->{_headers}->header( 'To' ) );
905 }
906  
907 # use_temp_file( [$bool] )
908 # When true, as_string_ref() always spools to a temporary file regardless of message size.
909 # This is used when we know the message will be large, or when we want to bound peak
910 # memory use unconditionally.
911 # Default: false.
912 sub use_temp_file { return( shift->_set_get_boolean( 'use_temp_file', @_ ) ); }
913  
914 # gpg_encrypt( %opts )
915 # Encrypts this message for one or more recipients and returns a new Mail::Make object
916 # whose body is a RFC 3156 multipart/encrypted structure.
917 #
918 # Required options:
919 # Recipients => [ 'alice@example.com', ... ]
920 #
921 # Optional options:
922 # GpgBin => '/usr/bin/gpg2'
923 # KeyServer => 'keys.openpgp.org'
924 # AutoFetch => 1
925 # Digest => 'SHA256'
926 sub gpg_encrypt
927 {
928 my $self = shift( @_ );
929 my $opts = $self->_get_args_as_hash( @_ );
930 require Mail::Make::GPG;
931 my $gpg = Mail::Make::GPG->new(
932 ( defined( $opts->{GpgBin} ) ? ( gpg_bin => $opts->{GpgBin} ) : () ),
933 ( defined( $opts->{Digest} ) ? ( digest => $opts->{Digest} ) : () ),
934 ( defined( $opts->{KeyServer} ) ? ( keyserver => $opts->{KeyServer} ) : () ),
935 ( defined( $opts->{AutoFetch} ) ? ( auto_fetch => $opts->{AutoFetch} ) : () ),
936 ) || return( $self->pass_error( Mail::Make::GPG->error ) );
937  
938 my $recipients = $opts->{Recipients} ||
939 return( $self->error( 'gpg_encrypt(): Recipients option is required.' ) );
940 $recipients = [ $recipients ] unless( ref( $recipients ) eq 'ARRAY' );
941  
942 return( $gpg->encrypt(
943 entity => $self,
944 recipients => $recipients,
945 ) || $self->pass_error( $gpg->error ) );
946 }
947  
948 # gpg_sign( %opts )
949 # Signs this message and returns a new Mail::Make object whose body is a
950 # RFC 3156 multipart/signed structure with a detached ASCII-armoured signature.
951 #
952 # Required options:
953 # KeyId => '35ADBC3AF8355E845139D8965F3C0261CDB2E752'
954 #
955 # Optional options:
956 # Passphrase => 'secret' # or CODE ref; omit to use gpg-agent
957 # Digest => 'SHA256'
958 # GpgBin => '/usr/bin/gpg2'
959 sub gpg_sign
960 {
961 my $self = shift( @_ );
962 my $opts = $self->_get_args_as_hash( @_ );
963 require Mail::Make::GPG;
964 my $gpg = Mail::Make::GPG->new(
965 ( defined( $opts->{GpgBin} ) ? ( gpg_bin => $opts->{GpgBin} ) : () ),
966 ( defined( $opts->{Digest} ) ? ( digest => $opts->{Digest} ) : () ),
967 ) || return( $self->pass_error( Mail::Make::GPG->error ) );
968  
969 return( $gpg->sign(
970 entity => $self,
971 key_id => ( $opts->{KeyId} // '' ),
972 passphrase => ( $opts->{Passphrase} // undef ),
973 ( defined( $opts->{Digest} ) ? ( digest => $opts->{Digest} ) : () ),
974 ) || $self->pass_error( $gpg->error ) );
975 }
976  
977 # gpg_sign_encrypt( %opts )
978 # Signs then encrypts this message. Returns a new Mail::Make object whose body is a
979 # RFC 3156 multipart/encrypted structure containing a signed and encrypted payload.
980 #
981 # Required options:
982 # KeyId => '35ADBC3AF8355E845139D8965F3C0261CDB2E752'
983 # Recipients => [ 'alice@example.com', ... ]
984 #
985 # Optional options:
986 # Passphrase => 'secret' # or CODE ref
987 # Digest => 'SHA256'
988 # GpgBin => '/usr/bin/gpg2'
989 # KeyServer => 'keys.openpgp.org'
990 # AutoFetch => 1
991 sub gpg_sign_encrypt
992 {
993 my $self = shift( @_ );
994 my $opts = $self->_get_args_as_hash( @_ );
995 require Mail::Make::GPG;
996 my $gpg = Mail::Make::GPG->new(
997 ( defined( $opts->{GpgBin} ) ? ( gpg_bin => $opts->{GpgBin} ) : () ),
998 ( defined( $opts->{Digest} ) ? ( digest => $opts->{Digest} ) : () ),
999 ( defined( $opts->{KeyServer} ) ? ( keyserver => $opts->{KeyServer} ) : () ),
1000 ( defined( $opts->{AutoFetch} ) ? ( auto_fetch => $opts->{AutoFetch} ) : () ),
1001 ) || return( $self->pass_error( Mail::Make::GPG->error ) );
1002  
1003 my $recipients = $opts->{Recipients} ||
1004 return( $self->error( 'gpg_sign_encrypt(): Recipients option is required.' ) );
1005 $recipients = [ $recipients ] unless( ref( $recipients ) eq 'ARRAY' );
1006  
1007 return( $gpg->sign_encrypt(
1008 entity => $self,
1009 key_id => ( $opts->{KeyId} // '' ),
1010 passphrase => ( $opts->{Passphrase} // undef ),
1011 recipients => $recipients,
1012 ( defined( $opts->{Digest} ) ? ( digest => $opts->{Digest} ) : () ),
1013 ) || $self->pass_error( $gpg->error ) );
1014 }
1015  
1016  
1017 # smime_encrypt( %opts )
1018 # Encrypts this message for one or more recipients. Returns a new Mail::Make object whose
1019 # entity is a RFC 5751 application/pkcs7-mime enveloped message.
1020 #
1021 # Required options:
1022 # RecipientCert => $pem_string_or_path (or arrayref of either)
1023 #
1024 # Optional options:
1025 # CACert => $pem_string_or_path
1026 sub smime_encrypt
1027 {
1028 my $self = shift( @_ );
1029 my $opts = $self->_get_args_as_hash( @_ );
1030 require Mail::Make::SMIME;
1031 my $smime = Mail::Make::SMIME->new(
1032 ( defined( $opts->{CACert} ) ? ( ca_cert => $opts->{CACert} ) : () ),
1033 ) || return( $self->pass_error( Mail::Make::SMIME->error ) );
1034  
1035 return( $smime->encrypt(
1036 entity => $self,
1037 RecipientCert => ( $opts->{RecipientCert} || return( $self->error( 'smime_encrypt(): RecipientCert option is required.' ) ) ),
1038 ) || $self->pass_error( $smime->error ) );
1039 }
1040  
1041 # smime_sign( %opts )
1042 # Signs this message and returns a new Mail::Make object whose entity is a RFC 5751
1043 # multipart/signed structure with a detached S/MIME signature.
1044 #
1045 # Required options:
1046 # Cert => $pem_string_or_path
1047 # Key => $pem_string_or_path
1048 #
1049 # Optional options:
1050 # KeyPassword => $string_or_coderef
1051 # CACert => $pem_string_or_path
1052 sub smime_sign
1053 {
1054 my $self = shift( @_ );
1055 my $opts = $self->_get_args_as_hash( @_ );
1056 require Mail::Make::SMIME;
1057 my $smime = Mail::Make::SMIME->new(
1058 ( defined( $opts->{Cert} ) ? ( cert => $opts->{Cert} ) : () ),
1059 ( defined( $opts->{Key} ) ? ( key => $opts->{Key} ) : () ),
1060 ( defined( $opts->{KeyPassword} ) ? ( key_password => $opts->{KeyPassword} ) : () ),
1061 ( defined( $opts->{CACert} ) ? ( ca_cert => $opts->{CACert} ) : () ),
1062 ) || return( $self->pass_error( Mail::Make::SMIME->error ) );
1063  
1064 return( $smime->sign(
1065 entity => $self,
1066 ) || $self->pass_error( $smime->error ) );
1067 }
1068  
1069 # smime_sign_encrypt( %opts )
1070 # Signs then encrypts this message. Returns a new Mail::Make object whose entity is a
1071 # RFC 5751 enveloped message containing a signed payload.
1072 #
1073 # Required options:
1074 # Cert => $pem_string_or_path
1075 # Key => $pem_string_or_path
1076 # RecipientCert => $pem_string_or_path (or arrayref of either)
1077 #
1078 # Optional options:
1079 # KeyPassword => $string_or_coderef
1080 # CACert => $pem_string_or_path
1081 sub smime_sign_encrypt
1082 {
1083 my $self = shift( @_ );
1084 my $opts = $self->_get_args_as_hash( @_ );
1085 require Mail::Make::SMIME;
1086 my $smime = Mail::Make::SMIME->new(
1087 ( defined( $opts->{Cert} ) ? ( cert => $opts->{Cert} ) : () ),
1088 ( defined( $opts->{Key} ) ? ( key => $opts->{Key} ) : () ),
1089 ( defined( $opts->{KeyPassword} ) ? ( key_password => $opts->{KeyPassword} ) : () ),
1090 ( defined( $opts->{CACert} ) ? ( ca_cert => $opts->{CACert} ) : () ),
1091 ) || return( $self->pass_error( Mail::Make::SMIME->error ) );
1092  
1093 return( $smime->sign_encrypt(
1094 entity => $self,
1095 RecipientCert => ( $opts->{RecipientCert} ||
1096 return( $self->error( 'smime_sign_encrypt(): RecipientCert option is required.' ) ) ),
1097 ) || $self->pass_error( $smime->error ) );
1098 }
1099  
1100 # _default_domain()
1101 # Returns a reasonable FQDN for auto-generating Message-IDs.
1102 # Uses Sys::Hostname (core) and falls back to 'mail.make.local'.
1103 sub _default_domain
1104 {
1105 my $self = shift( @_ );
1106 local $@;
1107 my $host = eval
1108 {
1109 require Sys::Hostname;
1110 Sys::Hostname::hostname();
1111 };
1112 return( 'mail.make.local' ) if( $@ || !defined( $host ) || !length( $host ) );
1113 # If it is not a FQDN (no dot), append .local to avoid rejection by
1114 # Mail::Make::Headers::_generate_message_id
1115 $host .= '.local' if( index( $host, '.' ) == -1 );
1116 return( $host );
1117 }
1118  
1119 # _encode_address( $addr_string )
1120 # Encodes the display name portion of an RFC 2822 address using RFC 2047 when it contains
1121 # non-ASCII characters. The addr-spec (the part inside angle brackets) is never altered.
1122 #
1123 # Recognised forms:
1124 # "Display Name" <local@domain>
1125 # Display Name <local@domain>
1126 # local@domain (bare addr-spec, passed through unchanged)
1127 #
1128 # Returns the wire-safe string.
1129 sub _encode_address
1130 {
1131 my( $self, $addr ) = @_;
1132 return( $addr ) unless( defined( $addr ) && length( $addr ) );
1133 if( $addr =~ /^("?)([^<"]+)\1\s*<([^>]+)>\s*$/ )
1134 {
1135 my( $name, $spec ) = ( $2, $3 );
1136 $name =~ s/^\s+|\s+$//g;
1137 my $enc = $self->_encode_header( $name );
1138 # If the name was encoded (contains non-ASCII), the encoded-word is
1139 # self-quoting and must NOT be surrounded by double-quotes.
1140 # If it is plain ASCII, keep surrounding quotes for correct parsing.
1141 return( $enc ne $name
1142 ? "${enc} <${spec}>"
1143 : qq{"${name}" <${spec}>} );
1144 }
1145 # Bare addr-spec - nothing to encode
1146 return( $addr );
1147 }
1148  
1149 # _encode_header( $string )
1150 # Encodes a header value for the wire using RFC 2047 if necessary.
1151 # Delegates to Mail::Make::Headers::Subject which handles fragmentation, fold points,
1152 # and UTF-8 boundary safety.
1153 sub _encode_header
1154 {
1155 my( $self, $str ) = @_;
1156 return( $str ) unless( defined( $str ) );
1157 my $s = Mail::Make::Headers::Subject->new;
1158 $s->value( $str );
1159 return( $s->as_string );
1160 }
1161  
1162 # _format_date()
1163 # Returns the current date/time in RFC 2822 format.
1164 sub _format_date
1165 {
1166 my @t = localtime( time );
1167 my @day = qw( Sun Mon Tue Wed Thu Fri Sat );
1168 my @mon = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec );
1169 my $tz = do
1170 {
1171 my @lt = localtime( time );
1172 my @gt = gmtime( time );
1173 my $diff = ( $lt[2] - $gt[2] ) * 60 + ( $lt[1] - $gt[1] );
1174 $diff += 1440 if( $lt[5] > $gt[5] || ( $lt[5] == $gt[5] && $lt[7] > $gt[7] ) );
1175 $diff -= 1440 if( $lt[5] < $gt[5] || ( $lt[5] == $gt[5] && $lt[7] < $gt[7] ) );
1176 my $sign = $diff >= 0 ? '+' : '-';
1177 $diff = abs( $diff );
1178 sprintf( '%s%02d%02d', $sign, int( $diff / 60 ), $diff % 60 );
1179 };
1180 return( sprintf( '%s, %02d %s %04d %02d:%02d:%02d %s',
1181 $day[ $t[6] ], $t[3], $mon[ $t[4] ], $t[5] + 1900,
1182 $t[2], $t[1], $t[0], $tz ) );
1183 }
1184  
1185 # NOTE: STORABLE support
1186 sub STORABLE_freeze { CORE::return( CORE::shift->FREEZE( @_ ) ); }
1187  
1188 sub STORABLE_thaw { CORE::return( CORE::shift->THAW( @_ ) ); }
1189  
1190 1;
1191 # NOTE: POD
1192 __END__