lib/MIME/Lite.pm

filter: Statementstmt 58.5% 408 / 697 Branchbran 35.4% 139 / 392 Conditioncond 33.6% 41 / 122 MC/DCmcdc 13.3% 10 / 75 Subroutinesub 61.6% 45 / 73 Podpod 67.9% 36 / 53 totaltotal 48.0% 679 / 1412 CC 241 SCAR 46.1
CC
241
Cov
49%
send_by_smtp
420.0
send_by_sendmail
342.0
print_simple_body
292.5
CRAP 100.4
↑ Summary blib/lib/MIME/Lite.pm »
1 package MIME::Lite;
2  
3  
4 =head1 NAME
5  
6 MIME::Lite - low-calorie MIME generator
7  
8 =head1 SYNOPSIS
9  
10 Create and send using the default send method for your OS a single-part message:
11  
12 use MIME::Lite;
13 ### Create a new single-part message, to send a GIF file:
14 $msg = MIME::Lite->new(
15 From =>'me@myhost.com',
16 To =>'you@yourhost.com',
17 Cc =>'some@other.com, some@more.com',
18 Subject =>'Helloooooo, nurse!',
19 Type =>'image/gif',
20 Encoding =>'base64',
21 Path =>'hellonurse.gif'
22 );
23 $msg->send; # send via default
24  
25 Create a multipart message (i.e., one with attachments) and send it SMTP
26  
27 ### Create a new multipart message:
28 $msg = MIME::Lite->new(
29 From =>'me@myhost.com',
30 To =>'you@yourhost.com',
31 Cc =>'some@other.com, some@more.com',
32 Subject =>'A message with 2 parts...',
33 Type =>'multipart/mixed'
34 );
35  
36 ### Add parts (each "attach" has same arguments as "new"):
37 $msg->attach(
38 Type =>'TEXT',
39 Data =>"Here's the GIF file you wanted"
40 );
41 $msg->attach(
42 Type =>'image/gif',
43 Path =>'aaa000123.gif',
44 Filename =>'logo.gif',
45 Disposition => 'attachment'
46 );
47 ### use Net:SMTP to do the sending
48 $msg->send('smtp','some.host', Debug=>1 );
49  
50 Output a message:
51  
52 ### Format as a string:
53 $str = $msg->as_string;
54  
55 ### Print to a filehandle (say, a "sendmail" stream):
56 $msg->print(\*SENDMAIL);
57  
58 Send a message:
59  
60 ### Send in the "best" way (the default is to use "sendmail"):
61 $msg->send;
62 ### Send a specific way:
63 $msg->send('type',@args);
64  
65 Specify default send method:
66  
67 MIME::Lite->send('smtp','some.host',Debug=>0);
68  
69 with authentication
70  
71 MIME::Lite->send('smtp','some.host',
72 AuthUser=>$user, AuthPass=>$pass);
73  
74 =head1 DESCRIPTION
75  
76 In the never-ending quest for great taste with fewer calories,
77 we proudly present: I<MIME::Lite>.
78  
79 MIME::Lite is intended as a simple, standalone module for generating
80 (not parsing!) MIME messages... specifically, it allows you to
81 output a simple, decent single- or multi-part message with text or binary
82 attachments. It does not require that you have the Mail:: or MIME::
83 modules installed, but will work with them if they are.
84  
85 You can specify each message part as either the literal data itself (in
86 a scalar or array), or as a string which can be given to open() to get
87 a readable filehandle (e.g., "<filename" or "somecommand|").
88  
89 You don't need to worry about encoding your message data:
90 this module will do that for you. It handles the 5 standard MIME encodings.
91  
92 =head1 EXAMPLES
93  
94 =head2 Create a simple message containing just text
95  
96 $msg = MIME::Lite->new(
97 From =>'me@myhost.com',
98 To =>'you@yourhost.com',
99 Cc =>'some@other.com, some@more.com',
100 Subject =>'Helloooooo, nurse!',
101 Data =>"How's it goin', eh?"
102 );
103  
104 =head2 Create a simple message containing just an image
105  
106 $msg = MIME::Lite->new(
107 From =>'me@myhost.com',
108 To =>'you@yourhost.com',
109 Cc =>'some@other.com, some@more.com',
110 Subject =>'Helloooooo, nurse!',
111 Type =>'image/gif',
112 Encoding =>'base64',
113 Path =>'hellonurse.gif'
114 );
115  
116  
117 =head2 Create a multipart message
118  
119 ### Create the multipart "container":
120 $msg = MIME::Lite->new(
121 From =>'me@myhost.com',
122 To =>'you@yourhost.com',
123 Cc =>'some@other.com, some@more.com',
124 Subject =>'A message with 2 parts...',
125 Type =>'multipart/mixed'
126 );
127  
128 ### Add the text message part:
129 ### (Note that "attach" has same arguments as "new"):
130 $msg->attach(
131 Type =>'TEXT',
132 Data =>"Here's the GIF file you wanted"
133 );
134  
135 ### Add the image part:
136 $msg->attach(
137 Type =>'image/gif',
138 Path =>'aaa000123.gif',
139 Filename =>'logo.gif',
140 Disposition => 'attachment'
141 );
142  
143  
144 =head2 Attach a GIF to a text message
145  
146 This will create a multipart message exactly as above, but using the
147 "attach to singlepart" hack:
148  
149 ### Start with a simple text message:
150 $msg = MIME::Lite->new(
151 From =>'me@myhost.com',
152 To =>'you@yourhost.com',
153 Cc =>'some@other.com, some@more.com',
154 Subject =>'A message with 2 parts...',
155 Type =>'TEXT',
156 Data =>"Here's the GIF file you wanted"
157 );
158  
159 ### Attach a part... the make the message a multipart automatically:
160 $msg->attach(
161 Type =>'image/gif',
162 Path =>'aaa000123.gif',
163 Filename =>'logo.gif'
164 );
165  
166  
167 =head2 Attach a pre-prepared part to a message
168  
169 ### Create a standalone part:
170 $part = MIME::Lite->new(
171 Type =>'text/html',
172 Data =>'<H1>Hello</H1>',
173 );
174 $part->attr('content-type.charset' => 'UTF8');
175 $part->add('X-Comment' => 'A message for you');
176  
177 ### Attach it to any message:
178 $msg->attach($part);
179  
180  
181 =head2 Print a message to a filehandle
182  
183 ### Write it to a filehandle:
184 $msg->print(\*STDOUT);
185  
186 ### Write just the header:
187 $msg->print_header(\*STDOUT);
188  
189 ### Write just the encoded body:
190 $msg->print_body(\*STDOUT);
191  
192  
193 =head2 Print a message into a string
194  
195 ### Get entire message as a string:
196 $str = $msg->as_string;
197  
198 ### Get just the header:
199 $str = $msg->header_as_string;
200  
201 ### Get just the encoded body:
202 $str = $msg->body_as_string;
203  
204  
205 =head2 Send a message
206  
207 ### Send in the "best" way (the default is to use "sendmail"):
208 $msg->send;
209  
210  
211 =head2 Send an HTML document... with images included!
212  
213 $msg = MIME::Lite->new(
214 To =>'you@yourhost.com',
215 Subject =>'HTML with in-line images!',
216 Type =>'multipart/related'
217 );
218 $msg->attach(
219 Type => 'text/html',
220 Data => qq{
221 <body>
222 Here's <i>my</i> image:
223 <img src="cid:myimage.gif">
224 </body>
225 },
226 );
227 $msg->attach(
228 Type => 'image/gif',
229 Id => 'myimage.gif',
230 Path => '/path/to/somefile.gif',
231 );
232 $msg->send();
233  
234  
235 =head2 Change how messages are sent
236  
237 ### Do something like this in your 'main':
238 if ($I_DONT_HAVE_SENDMAIL) {
239 MIME::Lite->send('smtp', $host, Timeout=>60
240 AuthUser=>$user, AuthPass=>$pass);
241 }
242  
243 ### Now this will do the right thing:
244 $msg->send; ### will now use Net::SMTP as shown above
245  
246 =head1 PUBLIC INTERFACE
247  
248 =head2 Global configuration
249  
250 To alter the way the entire module behaves, you have the following
251 methods/options:
252  
253 =over 4
254  
255  
256 =item MIME::Lite->field_order()
257  
258 When used as a L<classmethod|/field_order>, this changes the default
259 order in which headers are output for I<all> messages.
260 However, please consider using the instance method variant instead,
261 so you won't stomp on other message senders in the same application.
262  
263  
264 =item MIME::Lite->quiet()
265  
266 This L<classmethod|/quiet> can be used to suppress/unsuppress
267 all warnings coming from this module.
268  
269  
270 =item MIME::Lite->send()
271  
272 When used as a L<classmethod|/send>, this can be used to specify
273 a different default mechanism for sending message.
274 The initial default is:
275  
276 MIME::Lite->send("sendmail", "/usr/lib/sendmail -t -oi -oem");
277  
278 However, you should consider the similar but smarter and taint-safe variant:
279  
280 MIME::Lite->send("sendmail");
281  
282 Or, for non-Unix users:
283  
284 MIME::Lite->send("smtp");
285  
286  
287 =item $MIME::Lite::AUTO_CC
288  
289 If true, automatically send to the Cc/Bcc addresses for send_by_smtp().
290 Default is B<true>.
291  
292  
293 =item $MIME::Lite::AUTO_CONTENT_TYPE
294  
295 If true, try to automatically choose the content type from the file name
296 in C<new()>/C<build()>. In other words, setting this true changes the
297 default C<Type> from C<"TEXT"> to C<"AUTO">.
298  
299 Default is B<false>, since we must maintain backwards-compatibility
300 with prior behavior. B<Please> consider keeping it false,
301 and just using Type 'AUTO' when you build() or attach().
302  
303  
304 =item $MIME::Lite::AUTO_ENCODE
305  
306 If true, automatically choose the encoding from the content type.
307 Default is B<true>.
308  
309  
310 =item $MIME::Lite::AUTO_VERIFY
311  
312 If true, check paths to attachments right before printing, raising an exception
313 if any path is unreadable.
314 Default is B<true>.
315  
316  
317 =item $MIME::Lite::PARANOID
318  
319 If true, we won't attempt to use MIME::Base64, MIME::QuotedPrint,
320 or MIME::Types, even if they're available.
321 Default is B<false>. Please consider keeping it false,
322 and trusting these other packages to do the right thing.
323  
324  
325 =back
326  
327 =cut
328  
329  
330 6 require 5.004; ### for /c modifier in m/\G.../gc modifier
331  
332 6 ▶use Carp();
Subroutine BEGIN: called CC=1 SCAR=0.0
333 6 ▶use FileHandle;
Subroutine BEGIN: called CC=1 SCAR=0.0
334  
335 6 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
336 6 use vars qw(
337 $AUTO_CC
338 $AUTO_CONTENT_TYPE
339 $AUTO_ENCODE
340 $AUTO_VERIFY
341 $PARANOID
342 $QUIET
343 $VANILLA
344 $VERSION
345 $DEBUG
346 6 ▶);
Subroutine BEGIN: called CC=1 SCAR=0.0
347  
348  
349 #==============================
350 #==============================
351 #
352 # GLOBALS, EXTERNAL/CONFIGURATION...
353 6 $VERSION = "3.01_05";
354 6 $VERSION = eval $VERSION;
355  
356 ### Automatically interpret CC/BCC for SMTP:
357 6 $AUTO_CC = 1;
358  
359 ### Automatically choose content type from file name:
360 6 $AUTO_CONTENT_TYPE = 0;
361  
362 ### Automatically choose encoding from content type:
363 6 $AUTO_ENCODE = 1;
364  
365 ### Check paths right before printing:
366 6 $AUTO_VERIFY = 1;
367  
368 ### Set this true if you don't want to use MIME::Base64/QuotedPrint/Types:
369 6 $PARANOID = 0;
370  
371 ### Don't warn me about dangerous activities:
372 6 $QUIET = undef;
373  
374 ### Unsupported (for tester use): don't qualify boundary with time/pid:
375 6 $VANILLA = 0;
376  
377 6 $MIME::Lite::DEBUG = 0;
378  
379 #==============================
380 #==============================
381 #
382 # GLOBALS, INTERNAL...
383  
384 6 my $Sender = "";
385 6 my $SENDMAIL = "";
386  
387 6 ▶if ( $^O =~ /win32/i ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($^O =~ /win32/i) { } 0 6 6
388 0 $Sender = "smtp";
389 } else {
390 ### Find sendmail:
391 6 $Sender = "sendmail";
392 6 $SENDMAIL = "/usr/lib/sendmail";
393 6 ▶ ( -x $SENDMAIL ) or ( $SENDMAIL = "/usr/sbin/sendmail" );
Branch: 1 branch
BranchTrueFalseTotal
-x $SENDMAIL or $SENDMAIL = "/usr/sbin/sendmail" 6 0 6
394 6 ▶ ( -x $SENDMAIL ) or ( $SENDMAIL = "sendmail" );
Branch: 1 branch
BranchTrueFalseTotal
-x $SENDMAIL or $SENDMAIL = "sendmail" 6 0 6
395 }
396  
397 ### Our sending facilities:
398 6 my %SenderArgs = (
399 "sendmail" => ["$SENDMAIL -t -oi -oem"],
400 "smtp" => [],
401 "sub" => [],
402 );
403  
404 ### Boundary counter:
405 6 my $BCount = 0;
406  
407 ### Known Mail/MIME fields... these, plus some general forms like
408 ### "x-*", are recognized by build():
409 6 my %KnownField = map { $_ => 1 }
410 qw(
411 bcc cc comments date encrypted
412 from keywords message-id mime-version organization
413 received references reply-to return-path sender
414 subject to
415  
416 approved
417 );
418  
419 ### What external packages do we use for encoding?
420 6 my @Uses;
421  
422 ### Header order:
423 my @FieldOrder;
424  
425 ### See if we have File::Basename
426 6 my $HaveFileBasename = 0;
427 6 ▶if ( eval "require File::Basename" ) { # not affected by $PARANOID, core Perl
Branch: 1 branch
BranchTrueFalseTotal
if (eval "require File::Basename") 6 0 6
428 6 $HaveFileBasename = 1;
429 6 push @Uses, "F$File::Basename::VERSION";
430 }
431  
432 ### See if we have/want MIME::Types
433 6 my $HaveMimeTypes = 0;
434 6 ▶if ( !$PARANOID and eval "require MIME::Types; MIME::Types->VERSION(1.004);" ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $MIME::Lite::PARANOID and eval "require MIME::Types; MIME::Types->VERSION(1.004);") 6 0 6
Condition33%1/3
not $MIME::Lite::PARANOID and eval "require MIME::Types; MIME::Types->VERSION(1.004);"
!ll&&!rl&&r
006
MC/DC0%0/2
not $MIME::Lite::PARANOID and eval "require MIME::Types; MIME::Types->VERSION(1.004);"
not $MIME::Lite::PARANOID eval "require MIME::Types; MIME::Types->VERSION(1.004);"
Truth table33%1/3
not(A) and B
A= not $MIME::Lite::PARANOIDB= eval "require MIME::Types; MIME::Types->VERSION(1.004);"
ABresult
0X0
100
111
435 6 $HaveMimeTypes = 1;
436 6 push @Uses, "T$MIME::Types::VERSION";
437 }
438  
439 #==============================
440 #==============================
441 #
442 # PRIVATE UTILITY FUNCTIONS...
443  
444 #------------------------------
445 #
446 # fold STRING
447 #
448 # Make STRING safe as a field value. Remove leading/trailing whitespace,
449 # and make sure newlines are represented as newline+space
450  
451 sub fold {
452 0 ▶ my $str = shift;
Subroutine fold: not called CC=1 SCAR=6.9
Pod undocumented
453 0 $str =~ s/^\s*|\s*$//g; ### trim
454 0 $str =~ s/\n/\n /g;
455 0 $str;
456 }
457  
458 #------------------------------
459 #
460 # gen_boundary
461 #
462 # Generate a new boundary to use.
463 # The unsupported $VANILLA is for test purposes only.
464  
465 sub gen_boundary {
466 5 ▶ return ( "_----------=_" . ( $VANILLA ? '' : int(time) . $$ ) . $BCount++ );
Subroutine gen_boundary: called CC=2 SCAR=7.6
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
$MIME::Lite::VANILLA ? : 5 0 5
467 }
468  
469 #------------------------------
470 #
471 # is_mime_field FIELDNAME
472 #
473 # Is this a field I manage?
474  
475 sub is_mime_field {
476 37 ▶ $_[0] =~ /^(mime\-|content\-)/i;
Subroutine is_mime_field: called CC=1 SCAR=0.0
Pod undocumented
477 }
478  
479 #------------------------------
480 #
481 # extract_full_addrs STRING
482 # extract_only_addrs STRING
483 #
484 # Split STRING into an array of email addresses: somewhat of a KLUDGE.
485 #
486 # Unless paranoid, we try to load the real code before supplying our own.
487 BEGIN {
488 6 ▶ my $ATOM = '[^ \000-\037()<>@,;:\134"\056\133\135]+';
Subroutine BEGIN: called CC=1 SCAR=0.0
489 6 my $QSTR = '".*?"';
490 6 my $WORD = '(?:' . $QSTR . '|' . $ATOM . ')';
491 6 my $DOMAIN = '(?:' . $ATOM . '(?:' . '\\.' . $ATOM . ')*' . ')';
492 6 my $LOCALPART = '(?:' . $WORD . '(?:' . '\\.' . $WORD . ')*' . ')';
493 6 my $ADDR = '(?:' . $LOCALPART . '@' . $DOMAIN . ')';
494 6 my $PHRASE = '(?:' . $WORD . ')+';
495 6 my $SEP = "(?:^\\s*|\\s*,\\s*)"; ### before elems in a list
496  
497 sub my_extract_full_addrs {
498 0 ▶ my $str = shift;
Subroutine my_extract_full_addrs: not called CC=6 SCAR=37.4
Pod undocumented
499 0 my @addrs;
500 0 $str =~ s/\s/ /g; ### collapse whitespace
501  
502 0 pos($str) = 0;
503 0 ▶ while ( $str !~ m{\G\s*\Z}gco ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($str =~ /\G\s*\Z/cog) 0 0 0
504 ### print STDERR "TACKLING: ".substr($str, pos($str))."\n";
505 0 ▶ if ( $str =~ m{\G$SEP($PHRASE)\s*<\s*($ADDR)\s*>}gco ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($str =~ /\G$SEP($PHRASE)\s*<\s*($ADDR)\s*>/cog) { } 0 0 0
elsif ($str =~ /\G$SEP($ADDR)/cog or $str =~ /\G$SEP($ATOM)/cog) { } 0 0 0
506 0 push @addrs, "$1 <$2>";
507 ▶ } elsif ( $str =~ m{\G$SEP($ADDR)}gco or $str =~ m{\G$SEP($ATOM)}gco ) {
Condition0%0/3
$str =~ /\G$SEP($ADDR)/cog or $str =~ /\G$SEP($ATOM)/cog
l!l&&r!l&&!r
000
MC/DC0%0/2
$str =~ /\G$SEP($ADDR)/cog or $str =~ /\G$SEP($ATOM)/cog
$str =~ /\G$SEP($ADDR)/cog $str =~ /\G$SEP($ATOM)/cog
Truth table0%0/3
A or B
A= $str =~ /\G$SEP($ADDR)/cogB= $str =~ /\G$SEP($ATOM)/cog
ABresult
1X1
011
000
508 0 push @addrs, $1;
509 } else {
510 0 my $problem = substr( $str, pos($str) );
511 0 die "can't extract address at <$problem> in <$str>\n";
512 }
513 }
514 0 ▶ return wantarray ? @addrs : $addrs[0];
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
515 }
516  
517 sub my_extract_only_addrs {
518 0 ▶ my @ret = map { /<([^>]+)>/ ? $1 : $_ } my_extract_full_addrs(@_);
Subroutine my_extract_only_addrs: not called CC=3 SCAR=24.8
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
/<([^>]+)>/ ? : 0 0 0
519 0 ▶ return wantarray ? @ret : $ret[0];
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
520 }
521 }
522 #------------------------------
523  
524  
525 6 ▶if ( !$PARANOID and eval "require Mail::Address" ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $MIME::Lite::PARANOID and eval 'require Mail::Address') { } 6 0 6
Condition33%1/3
not $MIME::Lite::PARANOID and eval "require Mail::Address"
!ll&&!rl&&r
006
MC/DC0%0/2
not $MIME::Lite::PARANOID and eval "require Mail::Address"
not $MIME::Lite::PARANOID eval "require Mail::Address"
Truth table33%1/3
not(A) and B
A= not $MIME::Lite::PARANOIDB= eval "require Mail::Address"
ABresult
0X0
100
111
526 6 push @Uses, "A$Mail::Address::VERSION";
527 0 ▶ eval q{
Subroutine extract_full_addrs: not called CC=2 SCAR=9.7
Subroutine extract_only_addrs: called CC=2 SCAR=9.7
Pod undocumented
Pod undocumented
Branch: 2 branches
BranchTrueFalseTotal
wantarray ? : 0 0 0
wantarray ? : 10 0 10
528 sub extract_full_addrs {
529 my @ret=map { $_->format } Mail::Address->parse($_[0]);
530 return wantarray ? @ret : $ret[0]
531 }
532 sub extract_only_addrs {
533 my @ret=map { $_->address } Mail::Address->parse($_[0]);
534 return wantarray ? @ret : $ret[0]
535 }
536 }; ### q
537 } else {
538 0 eval q{
539 *extract_full_addrs=*my_extract_full_addrs;
540 *extract_only_addrs=*my_extract_only_addrs;
541 }; ### q
542 } ### if
543  
544 #==============================
545 #==============================
546 #
547 # PRIVATE ENCODING FUNCTIONS...
548  
549 #------------------------------
550 #
551 # encode_base64 STRING
552 #
553 # Encode the given string using BASE64.
554 # Unless paranoid, we try to load the real code before supplying our own.
555  
556 6 ▶if ( !$PARANOID and eval "require MIME::Base64" ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $MIME::Lite::PARANOID and eval 'require MIME::Base64') { } 6 0 6
Condition33%1/3
not $MIME::Lite::PARANOID and eval "require MIME::Base64"
!ll&&!rl&&r
006
MC/DC0%0/2
not $MIME::Lite::PARANOID and eval "require MIME::Base64"
not $MIME::Lite::PARANOID eval "require MIME::Base64"
Truth table33%1/3
not(A) and B
A= not $MIME::Lite::PARANOIDB= eval "require MIME::Base64"
ABresult
0X0
100
111
557 6 import MIME::Base64 qw(encode_base64);
558 6 push @Uses, "B$MIME::Base64::VERSION";
559 } else {
560 0 eval q{
561 sub encode_base64 {
562 my $res = "";
563 my $eol = "\n";
564  
565 pos($_[0]) = 0; ### thanks, Andreas!
566 while ($_[0] =~ /(.{1,45})/gs) {
567 $res .= substr(pack('u', $1), 1);
568 chop($res);
569 }
570 $res =~ tr|` -_|AA-Za-z0-9+/|;
571  
572 ### Fix padding at the end:
573 my $padding = (3 - length($_[0]) % 3) % 3;
574 $res =~ s/.{$padding}$/'=' x $padding/e if $padding;
575  
576 ### Break encoded string into lines of no more than 76 characters each:
577 $res =~ s/(.{1,76})/$1$eol/g if (length $eol);
578 return $res;
579 } ### sub
580 } ### q
581 } ### if
582  
583 #------------------------------
584 #
585 # encode_qp STRING
586 #
587 # Encode the given string, LINE BY LINE, using QUOTED-PRINTABLE.
588 # Stolen from MIME::QuotedPrint by Gisle Aas, with a slight bug fix: we
589 # break lines earlier. Notice that this seems not to work unless
590 # encoding line by line.
591 #
592 # Unless paranoid, we try to load the real code before supplying our own.
593  
594 6 ▶if ( !$PARANOID and eval "require MIME::QuotedPrint" ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $MIME::Lite::PARANOID and eval 'require MIME::QuotedPrint') { } 6 0 6
Condition33%1/3
not $MIME::Lite::PARANOID and eval "require MIME::QuotedPrint"
!ll&&!rl&&r
006
MC/DC0%0/2
not $MIME::Lite::PARANOID and eval "require MIME::QuotedPrint"
not $MIME::Lite::PARANOID eval "require MIME::QuotedPrint"
Truth table33%1/3
not(A) and B
A= not $MIME::Lite::PARANOIDB= eval "require MIME::QuotedPrint"
ABresult
0X0
100
111
595 6 import MIME::QuotedPrint qw(encode_qp);
596 6 push @Uses, "Q$MIME::QuotedPrint::VERSION";
597 } else {
598 0 eval q{
599 sub encode_qp {
600 my $res = shift;
601 local($_);
602 $res =~ s/([^ \t\n!-<>-~])/sprintf("=%02X", ord($1))/eg; ### rule #2,#3
603 $res =~ s/([ \t]+)$/
604 join('', map { sprintf("=%02X", ord($_)) }
605 split('', $1)
606 )/egm; ### rule #3 (encode whitespace at eol)
607  
608 ### rule #5 (lines shorter than 76 chars, but can't break =XX escapes:
609 my $brokenlines = "";
610 $brokenlines .= "$1=\n" while $res =~ s/^(.{70}([^=]{2})?)//; ### 70 was 74
611 $brokenlines =~ s/=\n$// unless length $res;
612 "$brokenlines$res";
613 } ### sub
614 } ### q
615 } ### if
616  
617  
618 #------------------------------
619 #
620 # encode_8bit STRING
621 #
622 # Encode the given string using 8BIT.
623 # This breaks long lines into shorter ones.
624  
625 sub encode_8bit {
626 13 ▶ my $str = shift;
Subroutine encode_8bit: called CC=1 SCAR=0.0
Pod undocumented
627 13 $str =~ s/^(.{990})/$1\n/mg;
628 13 $str;
629 }
630  
631 #------------------------------
632 #
633 # encode_7bit STRING
634 #
635 # Encode the given string using 7BIT.
636 # This NO LONGER protects people through encoding.
637  
638 sub encode_7bit {
639 0 ▶ my $str = shift;
Subroutine encode_7bit: not called CC=1 SCAR=6.9
Pod undocumented
640 0 $str =~ s/[\x80-\xFF]//g;
641 0 $str =~ s/^(.{990})/$1\n/mg;
642 0 $str;
643 }
644  
645 #==============================
646 #==============================
647  
648 =head2 Construction
649  
650 =over 4
651  
652 =cut
653  
654  
655 #------------------------------
656  
657 =item new [PARAMHASH]
658  
659 I<Class method, constructor.>
660 Create a new message object.
661  
662 If any arguments are given, they are passed into C<build()>; otherwise,
663 just the empty object is created.
664  
665 =cut
666  
667  
668 sub new {
669 24 ▶ my $class = shift;
Subroutine new: called CC=2 SCAR=6.9
Pod documented
670  
671 ### Create basic object:
672 24 my $self = { Attrs => {}, ### MIME attributes
673 SubAttrs => {}, ### MIME sub-attributes
674 Header => [], ### explicit message headers
675 Parts => [], ### array of parts
676 };
677 24 bless $self, $class;
678  
679 ### Build, if needed:
680 24 ▶ return ( @_ ? $self->build(@_) : $self );
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 14 10 24
681 }
682  
683  
684 #------------------------------
685  
686 =item attach PART
687  
688 =item attach PARAMHASH...
689  
690 I<Instance method.>
691 Add a new part to this message, and return the new part.
692  
693 If you supply a single PART argument, it will be regarded
694 as a MIME::Lite object to be attached. Otherwise, this
695 method assumes that you are giving in the pairs of a PARAMHASH
696 which will be sent into C<new()> to create the new part.
697  
698 One of the possibly-quite-useful hacks thrown into this is the
699 "attach-to-singlepart" hack: if you attempt to attach a part (let's
700 call it "part 1") to a message that doesn't have a content-type
701 of "multipart" or "message", the following happens:
702  
703 =over 4
704  
705 =item *
706  
707 A new part (call it "part 0") is made.
708  
709 =item *
710  
711 The MIME attributes and data (but I<not> the other headers)
712 are cut from the "self" message, and pasted into "part 0".
713  
714 =item *
715  
716 The "self" is turned into a "multipart/mixed" message.
717  
718 =item *
719  
720 The new "part 0" is added to the "self", and I<then> "part 1" is added.
721  
722 =back
723  
724 One of the nice side-effects is that you can create a text message
725 and then add zero or more attachments to it, much in the same way
726 that a user agent like Netscape allows you to do.
727  
728 =cut
729  
730  
731 sub attach {
732 10 ▶ my $self = shift;
Subroutine attach: called CC=6 SCAR=18.0
Pod documented
733 10 my $attrs = $self->{Attrs};
734 10 my $sub_attrs = $self->{SubAttrs};
735  
736 ### Create new part, if necessary:
737 10 ▶ my $part1 = ( ( @_ == 1 ) ? shift: ref($self)->new( Top => 0, @_ ) );
Branch: 1 branch
BranchTrueFalseTotal
@_ == 1 ? : 0 10 10
738  
739 ### Do the "attach-to-singlepart" hack:
740 10 ▶ if ( $attrs->{'content-type'} !~ m{^(multipart|message)/}i ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($attrs->{"content-type"} =~ m[^(multipart|message)/]i) 5 5 10
741  
742 ### Create part zero:
743 5 my $part0 = ref($self)->new;
744  
745 ### Cut MIME stuff from self, and paste into part zero:
746 5 foreach (qw(SubAttrs Attrs Data Path FH)) {
747 25 $part0->{$_} = $self->{$_};
748 25 delete( $self->{$_} );
749 }
750 5 $part0->top_level(0); ### clear top-level attributes
751  
752 ### Make self a top-level multipart:
753 5 ▶ $attrs = $self->{Attrs} ||= {}; ### reset (sam: bug? this doesn't reset anything since Attrs is already a hash-ref)
Condition50%1/2
$self->{"Attrs"} ||= {}
l!l
05
MC/DC0%0/1
$self->{"Attrs"} ||= {}
$self->{"Attrs"}
Truth table50%1/2
A
A= $self->{"Attrs"}
Aresult
11
00
754 5 ▶ $sub_attrs = $self->{SubAttrs} ||= {}; ### reset
Condition50%1/2
$self->{"SubAttrs"} ||= {}
l!l
05
MC/DC0%0/1
$self->{"SubAttrs"} ||= {}
$self->{"SubAttrs"}
Truth table50%1/2
A
A= $self->{"SubAttrs"}
Aresult
11
00
755 5 $attrs->{'content-type'} = 'multipart/mixed';
756 5 $sub_attrs->{'content-type'}{'boundary'} = gen_boundary();
757 5 $attrs->{'content-transfer-encoding'} = '7bit';
758 5 $self->top_level(1); ### activate top-level attributes
759  
760 ### Add part 0:
761 5 push @{ $self->{Parts} }, $part0;
762 }
763  
764 ### Add the new part:
765 10 push @{ $self->{Parts} }, $part1;
766 10 $part1;
767 }
768  
769 #------------------------------
770  
771 =item build [PARAMHASH]
772  
773 I<Class/instance method, initializer.>
774 Create (or initialize) a MIME message object.
775 Normally, you'll use the following keys in PARAMHASH:
776  
777 * Data, FH, or Path (either one of these, or none if multipart)
778 * Type (e.g., "image/jpeg")
779 * From, To, and Subject (if this is the "top level" of a message)
780  
781 The PARAMHASH can contain the following keys:
782  
783 =over 4
784  
785 =item (fieldname)
786  
787 Any field you want placed in the message header, taken from the
788 standard list of header fields (you don't need to worry about case):
789  
790 Approved Encrypted Received Sender
791 Bcc From References Subject
792 Cc Keywords Reply-To To
793 Comments Message-ID Resent-* X-*
794 Content-* MIME-Version Return-Path
795 Date Organization
796  
797 To give experienced users some veto power, these fields will be set
798 I<after> the ones I set... so be careful: I<don't set any MIME fields>
799 (like C<Content-type>) unless you know what you're doing!
800  
801 To specify a fieldname that's I<not> in the above list, even one that's
802 identical to an option below, just give it with a trailing C<":">,
803 like C<"My-field:">. When in doubt, that I<always> signals a mail
804 field (and it sort of looks like one too).
805  
806 =item Data
807  
808 I<Alternative to "Path" or "FH".>
809 The actual message data. This may be a scalar or a ref to an array of
810 strings; if the latter, the message consists of a simple concatenation
811 of all the strings in the array.
812  
813 =item Datestamp
814  
815 I<Optional.>
816 If given true (or omitted), we force the creation of a C<Date:> field
817 stamped with the current date/time if this is a top-level message.
818 You may want this if using L<send_by_smtp()|/send_by_smtp>.
819 If you don't want this to be done, either provide your own Date
820 or explicitly set this to false.
821  
822 =item Disposition
823  
824 I<Optional.>
825 The content disposition, C<"inline"> or C<"attachment">.
826 The default is C<"inline">.
827  
828 =item Encoding
829  
830 I<Optional.>
831 The content transfer encoding that should be used to encode your data:
832  
833 Use encoding: | If your message contains:
834 ------------------------------------------------------------
835 7bit | Only 7-bit text, all lines <1000 characters
836 8bit | 8-bit text, all lines <1000 characters
837 quoted-printable | 8-bit text or long lines (more reliable than "8bit")
838 base64 | Largely non-textual data: a GIF, a tar file, etc.
839  
840 The default is taken from the Type; generally it is "binary" (no
841 encoding) for text/*, message/*, and multipart/*, and "base64" for
842 everything else. A value of C<"binary"> is generally I<not> suitable
843 for sending anything but ASCII text files with lines under 1000
844 characters, so consider using one of the other values instead.
845  
846 In the case of "7bit"/"8bit", long lines are automatically chopped to
847 legal length; in the case of "7bit", all 8-bit characters are
848 automatically I<removed>. This may not be what you want, so pick your
849 encoding well! For more info, see L<"A MIME PRIMER">.
850  
851 =item FH
852  
853 I<Alternative to "Data" or "Path".>
854 Filehandle containing the data, opened for reading.
855 See "ReadNow" also.
856  
857 =item Filename
858  
859 I<Optional.>
860 The name of the attachment. You can use this to supply a
861 recommended filename for the end-user who is saving the attachment
862 to disk. You only need this if the filename at the end of the
863 "Path" is inadequate, or if you're using "Data" instead of "Path".
864 You should I<not> put path information in here (e.g., no "/"
865 or "\" or ":" characters should be used).
866  
867 =item Id
868  
869 I<Optional.>
870 Same as setting "content-id".
871  
872 =item Length
873  
874 I<Optional.>
875 Set the content length explicitly. Normally, this header is automatically
876 computed, but only under certain circumstances (see L<"Limitations">).
877  
878 =item Path
879  
880 I<Alternative to "Data" or "FH".>
881 Path to a file containing the data... actually, it can be any open()able
882 expression. If it looks like a path, the last element will automatically
883 be treated as the filename.
884 See "ReadNow" also.
885  
886 =item ReadNow
887  
888 I<Optional, for use with "Path".>
889 If true, will open the path and slurp the contents into core now.
890 This is useful if the Path points to a command and you don't want
891 to run the command over and over if outputting the message several
892 times. B<Fatal exception> raised if the open fails.
893  
894 =item Top
895  
896 I<Optional.>
897 If defined, indicates whether or not this is a "top-level" MIME message.
898 The parts of a multipart message are I<not> top-level.
899 Default is true.
900  
901 =item Type
902  
903 I<Optional.>
904 The MIME content type, or one of these special values (case-sensitive):
905  
906 "TEXT" means "text/plain"
907 "BINARY" means "application/octet-stream"
908 "AUTO" means attempt to guess from the filename, falling back
909 to 'application/octet-stream'. This is good if you have
910 MIME::Types on your system and you have no idea what
911 file might be used for the attachment.
912  
913 The default is C<"TEXT">, but it will be C<"AUTO"> if you set
914 $AUTO_CONTENT_TYPE to true (sorry, but you have to enable
915 it explicitly, since we don't want to break code which depends
916 on the old behavior).
917  
918 =back
919  
920 A picture being worth 1000 words (which
921 is of course 2000 bytes, so it's probably more of an "icon" than a "picture",
922 but I digress...), here are some examples:
923  
924 $msg = MIME::Lite->build(
925 From => 'yelling@inter.com',
926 To => 'stocking@fish.net',
927 Subject => "Hi there!",
928 Type => 'TEXT',
929 Encoding => '7bit',
930 Data => "Just a quick note to say hi!"
931 );
932  
933 $msg = MIME::Lite->build(
934 From => 'dorothy@emerald-city.oz',
935 To => 'gesundheit@edu.edu.edu',
936 Subject => "A gif for U"
937 Type => 'image/gif',
938 Path => "/home/httpd/logo.gif"
939 );
940  
941 $msg = MIME::Lite->build(
942 From => 'laughing@all.of.us',
943 To => 'scarlett@fiddle.dee.de',
944 Subject => "A gzipp'ed tar file",
945 Type => 'x-gzip',
946 Path => "gzip < /usr/inc/somefile.tar |",
947 ReadNow => 1,
948 Filename => "somefile.tgz"
949 );
950  
951 To show you what's really going on, that last example could also
952 have been written:
953  
954 $msg = new MIME::Lite;
955 $msg->build(
956 Type => 'x-gzip',
957 Path => "gzip < /usr/inc/somefile.tar |",
958 ReadNow => 1,
959 Filename => "somefile.tgz"
960 );
961 $msg->add(From => "laughing@all.of.us");
962 $msg->add(To => "scarlett@fiddle.dee.de");
963 $msg->add(Subject => "A gzipp'ed tar file");
964  
965 =cut
966  
967  
968 sub build {
969 19 ▶ my $self = shift;
Subroutine build: called CC=36 SCAR=42.1
Pod documented
970 19 my %params = @_;
971 19 my @params = @_;
972 19 my $key;
973  
974 ### Miko's note: reorganized to check for exactly one of Data, Path, or FH
975 19 ▶ ( defined( $params{Data} ) + defined( $params{Path} ) + defined( $params{FH} ) <= 1 )
Branch: 1 branch
BranchTrueFalseTotal
defined($params{"Data"}) + defined($params{"Path"}) + defined($params{"FH"}) <= 1 or Carp::croak("supply exactly zero or one of (Data|Path|FH).\n") 0 19 19
976 or Carp::croak "supply exactly zero or one of (Data|Path|FH).\n";
977  
978 ### Create new instance, if necessary:
979 19 ▶ ref($self) or $self = $self->new;
Branch: 1 branch
BranchTrueFalseTotal
ref $self or $self = $self->new 5 14 19
980  
981  
982 ### CONTENT-TYPE....
983 ###
984  
985 ### Get content-type or content-type-macro:
986 19 ▶ my $type = ( $params{Type} || ( $AUTO_CONTENT_TYPE ? 'AUTO' : 'TEXT' ) );
Branch: 1 branch
BranchTrueFalseTotal
$MIME::Lite::AUTO_CONTENT_TYPE ? : 0 13 13
Condition66%2/3
$params{'Type'} || ($MIME::Lite::AUTO_CONTENT_TYPE ? 'AUTO' : 'TEXT')
l!l&&r!l&&!r
6130
MC/DC0%0/2
$params{'Type'} || ($MIME::Lite::AUTO_CONTENT_TYPE ? 'AUTO' : 'TEXT')
$params{'Type'} ($MIME::Lite::AUTO_CONTENT_TYPE ? 'AUTO' : 'TEXT')
Truth table66%2/3
A || B
A= $params{'Type'}B= ($MIME::Lite::AUTO_CONTENT_TYPE ? 'AUTO' : 'TEXT')
ABresult
1X1
011
000
987  
988 ### Interpret content-type-macros:
989 19 ▶ if ( $type eq 'TEXT' ) { $type = 'text/plain'; }
Branch: 4 branches
BranchTrueFalseTotal
if ($type eq 'TEXT') { } 13 6 19
elsif ($type eq 'HTML') { } 0 6 6
elsif ($type eq 'BINARY') { } 0 6 6
elsif ($type eq 'AUTO') { } 1 5 6
990 0 elsif ( $type eq 'HTML' ) { $type = 'text/html'; }
991 0 elsif ( $type eq 'BINARY' ) { $type = 'application/octet-stream' }
992 1 elsif ( $type eq 'AUTO' ) { $type = $self->suggest_type( $params{Path} ); }
993  
994 ### We now have a content-type; set it:
995 19 $type = lc($type);
996 19 my $attrs = $self->{Attrs};
997 19 my $sub_attrs = $self->{SubAttrs};
998 19 $attrs->{'content-type'} = $type;
999  
1000 ### Get some basic attributes from the content type:
1001 19 my $is_multipart = ( $type =~ m{^(multipart)/}i );
1002  
1003 ### Add in the multipart boundary:
1004 19 ▶ if ($is_multipart) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_multipart) 0 19 19
1005 0 my $boundary = gen_boundary();
1006 0 $sub_attrs->{'content-type'}{'boundary'} = $boundary;
1007 }
1008  
1009  
1010 ### CONTENT-ID...
1011 ###
1012 19 ▶ if ( defined $params{Id} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params{"Id"}) 0 19 19
1013 0 my $id = $params{Id};
1014 0 ▶ $id = "<$id>" unless $id =~ /\A\s*<.*>\s*\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $id =~ /\A\s*<.*>\s*\z/ 0 0 0
1015 0 $attrs->{'content-id'} = $id;
1016 }
1017  
1018  
1019 ### DATA OR PATH...
1020 ### Note that we must do this *after* we get the content type,
1021 ### in case read_now() is invoked, since it needs the binmode().
1022  
1023 ### Get data, as...
1024 ### ...either literal data:
1025 19 ▶ if ( defined( $params{Data} ) ) {
Branch: 3 branches
BranchTrueFalseTotal
if (defined $params{'Data'}) { } 13 6 19
elsif (defined $params{'Path'}) { } 4 2 6
elsif (defined $params{'FH'}) { } 0 2 2
1026 13 $self->data( $params{Data} );
1027 }
1028 ### ...or a path to data:
1029 elsif ( defined( $params{Path} ) ) {
1030 4 $self->path( $params{Path} ); ### also sets filename
1031 4 ▶ $self->read_now if $params{ReadNow};
Branch: 1 branch
BranchTrueFalseTotal
if $params{"ReadNow"} 1 3 4
1032 }
1033 ### ...or a filehandle to data:
1034 ### Miko's note: this part works much like the path routine just above,
1035 elsif ( defined( $params{FH} ) ) {
1036 0 $self->fh( $params{FH} );
1037 0 ▶ $self->read_now if $params{ReadNow}; ### implement later
Branch: 1 branch
BranchTrueFalseTotal
if $params{"ReadNow"} 0 0 0
1038 }
1039  
1040  
1041 ### FILENAME... (added by Ian Smith <ian@safeway.dircon.co.uk> on 8/4/97)
1042 ### Need this to make sure the filename is added. The Filename
1043 ### attribute is ignored, otherwise.
1044 19 ▶ if ( defined( $params{Filename} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params{"Filename"}) 1 18 19
1045 1 $self->filename( $params{Filename} );
1046 }
1047  
1048  
1049 ### CONTENT-TRANSFER-ENCODING...
1050 ###
1051  
1052 ### Get it:
1053 my $enc =
1054 19 ▶ ( $params{Encoding} || ( $AUTO_ENCODE and $self->suggest_encoding($type) ) || 'binary' );
Condition37%3/8
$params{'Encoding'} || $MIME::Lite::AUTO_ENCODE && $self->suggest_encoding($type) || 'binary'
l!l
190
$params{"Encoding"} or $MIME::Lite::AUTO_ENCODE and $self->suggest_encoding($type)
l!l&&r!l&&!r
0190
$MIME::Lite::AUTO_ENCODE and $self->suggest_encoding($type)
!ll&&!rl&&r
0019
MC/DC0%0/3
$params{'Encoding'} || $MIME::Lite::AUTO_ENCODE && $self->suggest_encoding($type) || 'binary'
$params{"Encoding"} $MIME::Lite::AUTO_ENCODE $self->suggest_encoding($type)
Truth table25%1/4
A or B and C
A= $params{"Encoding"}B= $MIME::Lite::AUTO_ENCODEC= $self->suggest_encoding($type)
ABCresult
1XX1
0111
00X0
0100
1055 19 $attrs->{'content-transfer-encoding'} = lc($enc);
1056  
1057 ### Sanity check:
1058 19 ▶ if ( $type =~ m{^(multipart|message)/} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type =~ m[^(multipart|message)/]) 0 19 19
1059 0 ▶ ( $enc =~ m{^(7bit|8bit|binary)\Z} )
Branch: 1 branch
BranchTrueFalseTotal
$enc =~ /^(7bit|8bit|binary)\Z/ or Carp::croak('illegal MIME: ' . "can't have encoding $enc with type $type\n") 0 0 0
1060 or Carp::croak( "illegal MIME: " . "can't have encoding $enc with type $type\n" );
1061 }
1062  
1063 ### CONTENT-DISPOSITION...
1064 ### Default is inline for single, none for multis:
1065 ###
1066 19 ▶ my $disp = ( $params{Disposition} or ( $is_multipart ? undef: 'inline' ) );
Branch: 1 branch
BranchTrueFalseTotal
$is_multipart ? : 0 19 19
Condition33%1/3
$params{'Disposition'} || ($is_multipart ? undef : 'inline')
l!l&&r!l&&!r
0190
MC/DC0%0/2
$params{'Disposition'} || ($is_multipart ? undef : 'inline')
$params{'Disposition'} ($is_multipart ? undef : 'inline')
Truth table33%1/3
A || B
A= $params{'Disposition'}B= ($is_multipart ? undef : 'inline')
ABresult
1X1
011
000
1067 19 $attrs->{'content-disposition'} = $disp;
1068  
1069 ### CONTENT-LENGTH...
1070 ###
1071 19 my $length;
1072 19 ▶ if ( exists( $params{Length} ) ) { ### given by caller:
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{'Length'}) { } 0 19 19
1073 0 $attrs->{'content-length'} = $params{Length};
1074 } else { ### compute it ourselves
1075 19 $self->get_length;
1076 }
1077  
1078 ### Init the top-level fields:
1079 19 ▶ my $is_top = defined( $params{Top} ) ? $params{Top} : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $params{'Top'} ? : 10 9 19
1080 19 $self->top_level($is_top);
1081  
1082 ### Datestamp if desired:
1083 19 my $ds_wanted = $params{Datestamp};
1084 19 ▶ my $ds_defaulted = ( $is_top and !exists( $params{Datestamp} ) );
Condition66%2/3
$is_top && !exists $params{'Datestamp'}
!ll&&!rl&&r
1009
MC/DC50%1/2
$is_top && !exists $params{'Datestamp'}
$is_top !exists $params{'Datestamp'}
Truth table66%2/3
A && not(B)
A= $is_topB= !exists $params{'Datestamp'}
ABresult
0X0
100
111
1085 19 ▶ if ( ( $ds_wanted or $ds_defaulted ) and !exists( $params{Date} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ds_wanted || $ds_defaulted and not exists $params{"Date"}) 9 10 19
Condition66%4/6
$ds_wanted || $ds_defaulted and not exists $params{"Date"}
!ll&&!rl&&r
1009
$ds_wanted or $ds_defaulted
l!l&&r!l&&!r
0910
MC/DC33%1/3
$ds_wanted || $ds_defaulted and not exists $params{"Date"}
$ds_wanted $ds_defaulted not exists $params{"Date"}
Truth table40%2/5
A or B and not(C)
A= $ds_wantedB= $ds_defaultedC= not exists $params{"Date"}
ABCresult
00X0
1X00
0100
1X11
0111
1086 # Updated to use local time and numeric offset per RFC 2822
1087 # Calculate offset from UTC
1088 6 ▶ use Time::Local; # ships w/ Perl so should be OK to assume presence
Subroutine BEGIN: called CC=1 SCAR=0.0
1089 9 my $t0 = timegm( 0, 0, 0, 2, 0, 70 ); # one day from epoch
1090 9 my $t1 = timelocal( 0, 0, 0, 2, 0, 70 );
1091 9 my $offset = $t0 - $t1;
1092 9 my $offset_hrs = int( $offset / 3600 );
1093 9 my $offset_min = int( $offset / 60 ) - $offset_hrs * 60;
1094 9 my $offset_str = sprintf "%+.2d%02d", $offset_hrs, $offset_min;
1095 9 my ( $u_wdy, $u_mon, $u_mdy, $u_time, $u_y4 ) =
1096 split /\s+/, localtime() . ""; ### should be non-locale-dependent
1097 9 my $date = "$u_wdy, $u_mdy $u_mon $u_y4 $u_time $offset_str";
1098 9 $self->add( "date", $date );
1099 }
1100  
1101 ### Set message headers:
1102 19 my @paramz = @params;
1103 19 my $field;
1104 19 ▶ while (@paramz) {
Branch: 1 branch
BranchTrueFalseTotal
if (@paramz) 48 19 67
1105 48 my ( $tag, $value ) = ( shift(@paramz), shift(@paramz) );
1106 48 my $lc_tag = lc($tag);
1107  
1108 ### Get tag, if a tag:
1109 48 ▶ if ( $lc_tag =~ /^-(.*)/ ) { ### old style, backwards-compatibility
Branch: 3 branches
BranchTrueFalseTotal
if ($lc_tag =~ /^-(.*)/) { } 0 48 48
elsif ($lc_tag =~ /^(.*):$/) { } 0 48 48
elsif ($KnownField{$lc_tag} or $lc_tag =~ /^(content|resent|x)-./) { } 13 35 48
1110 0 $field = $1;
1111 } elsif ( $lc_tag =~ /^(.*):$/ ) { ### new style
1112 0 $field = $1;
1113 ▶ } elsif ( $KnownField{$lc_tag} or
Condition66%2/3
$KnownField{$lc_tag} or $lc_tag =~ /^(content|resent|x)-./
l!l&&r!l&&!r
13035
MC/DC50%1/2
$KnownField{$lc_tag} or $lc_tag =~ /^(content|resent|x)-./
$KnownField{$lc_tag} $lc_tag =~ /^(content|resent|x)-./
Truth table66%2/3
A or B
A= $KnownField{$lc_tag}B= $lc_tag =~ /^(content|resent|x)-./
ABresult
1X1
011
000
1114 $lc_tag =~ m{^(content|resent|x)-.} ){
1115 13 $field = $lc_tag;
1116 } else { ### not a field:
1117 35 next;
1118 }
1119  
1120 ### Add it:
1121 13 $self->add( $field, $value );
1122 }
1123  
1124 ### Done!
1125 19 $self;
1126 }
1127  
1128 =back
1129  
1130 =cut
1131  
1132  
1133 #==============================
1134 #==============================
1135  
1136 =head2 Setting/getting headers and attributes
1137  
1138 =over 4
1139  
1140 =cut
1141  
1142  
1143 #------------------------------
1144 #
1145 # top_level ONOFF
1146 #
1147 # Set/unset the top-level attributes and headers.
1148 # This affects "MIME-Version" and "X-Mailer".
1149  
1150 sub top_level {
1151 29 ▶ my ( $self, $onoff ) = @_;
Subroutine top_level: called CC=4 SCAR=14.0
Pod undocumented
1152 29 my $attrs = $self->{Attrs};
1153 29 ▶ if ($onoff) {
Branch: 1 branch
BranchTrueFalseTotal
if ($onoff) { } 14 15 29
1154 14 $attrs->{'MIME-Version'} = '1.0';
1155 14 ▶ my $uses = ( @Uses ? ( "(" . join( "; ", @Uses ) . ")" ) : '' );
Branch: 1 branch
BranchTrueFalseTotal
@Uses ? : 14 0 14
1156 14 ▶ $self->replace( 'X-Mailer' => "MIME::Lite $VERSION $uses" )
Branch: 1 branch
BranchTrueFalseTotal
unless $MIME::Lite::VANILLA 0 14 14
1157 unless $VANILLA;
1158 } else {
1159 15 delete $attrs->{'MIME-Version'};
1160 15 $self->delete('X-Mailer');
1161 }
1162 }
1163  
1164 #------------------------------
1165  
1166 =item add TAG,VALUE
1167  
1168 I<Instance method.>
1169 Add field TAG with the given VALUE to the end of the header.
1170 The TAG will be converted to all-lowercase, and the VALUE
1171 will be made "safe" (returns will be given a trailing space).
1172  
1173 B<Beware:> any MIME fields you "add" will override any MIME
1174 attributes I have when it comes time to output those fields.
1175 Normally, you will use this method to add I<non-MIME> fields:
1176  
1177 $msg->add("Subject" => "Hi there!");
1178  
1179 Giving VALUE as an arrayref will cause all those values to be added.
1180 This is only useful for special multiple-valued fields like "Received":
1181  
1182 $msg->add("Received" => ["here", "there", "everywhere"]
1183  
1184 Giving VALUE as the empty string adds an invisible placeholder
1185 to the header, which can be used to suppress the output of
1186 the "Content-*" fields or the special "MIME-Version" field.
1187 When suppressing fields, you should use replace() instead of add():
1188  
1189 $msg->replace("Content-disposition" => "");
1190  
1191 I<Note:> add() is probably going to be more efficient than C<replace()>,
1192 so you're better off using it for most applications if you are
1193 certain that you don't need to delete() the field first.
1194  
1195 I<Note:> the name comes from Mail::Header.
1196  
1197 =cut
1198  
1199  
1200 sub add {
1201 25 ▶ my $self = shift;
Subroutine add: called CC=6 SCAR=18.3
Pod documented
1202 25 my $tag = lc(shift);
1203 25 my $value = shift;
1204  
1205 ### If a dangerous option, warn them:
1206 25 ▶ Carp::carp "Explicitly setting a MIME header field ($tag) is dangerous:\n"
Branch: 1 branch
BranchTrueFalseTotal
if is_mime_field($tag) and not $MIME::Lite::QUIET 0 25 25
Condition33%1/3
is_mime_field($tag) and not $MIME::Lite::QUIET
!ll&&!rl&&r
2500
MC/DC0%0/2
is_mime_field($tag) and not $MIME::Lite::QUIET
is_mime_field($tag) not $MIME::Lite::QUIET
Truth table33%1/3
A and not(B)
A= is_mime_field($tag)B= not $MIME::Lite::QUIET
ABresult
0X0
100
111
1207 . "use the attr() method instead.\n"
1208 if ( is_mime_field($tag) && !$QUIET );
1209  
1210 ### Get array of clean values:
1211 my @vals = ( ( ref($value) and ( ref($value) eq 'ARRAY' ) )
1212 25 ▶ ? @{$value}
Branch: 1 branch
BranchTrueFalseTotal
ref $value && ref $value eq 'ARRAY' ? : 1 24 25
Condition66%2/3
ref $value and ref $value eq "ARRAY"
!ll&&!rl&&r
2401
MC/DC50%1/2
ref $value and ref $value eq "ARRAY"
ref $value ref $value eq "ARRAY"
Truth table66%2/3
A and B
A= ref $valueB= ref $value eq "ARRAY"
ABresult
0X0
100
111
1213 : ( $value . '' )
1214 );
1215 25 map { s/\n/\n /g } @vals;
1216  
1217 ### Add them:
1218 25 foreach (@vals) {
1219 26 push @{ $self->{Header} }, [ $tag, $_ ];
1220 }
1221 }
1222  
1223 #------------------------------
1224  
1225 =item attr ATTR,[VALUE]
1226  
1227 I<Instance method.>
1228 Set MIME attribute ATTR to the string VALUE.
1229 ATTR is converted to all-lowercase.
1230 This method is normally used to set/get MIME attributes:
1231  
1232 $msg->attr("content-type" => "text/html");
1233 $msg->attr("content-type.charset" => "US-ASCII");
1234 $msg->attr("content-type.name" => "homepage.html");
1235  
1236 This would cause the final output to look something like this:
1237  
1238 Content-type: text/html; charset=US-ASCII; name="homepage.html"
1239  
1240 Note that the special empty sub-field tag indicates the anonymous
1241 first sub-field.
1242  
1243 Giving VALUE as undefined will cause the contents of the named
1244 subfield to be deleted.
1245  
1246 Supplying no VALUE argument just returns the attribute's value:
1247  
1248 $type = $msg->attr("content-type"); ### returns "text/html"
1249 $name = $msg->attr("content-type.name"); ### returns "homepage.html"
1250  
1251 =cut
1252  
1253  
1254 sub attr {
1255 2 ▶ my ( $self, $attr, $value ) = @_;
Subroutine attr: called CC=5 SCAR=16.3
Pod documented
1256 2 my $attrs = $self->{Attrs};
1257  
1258 2 $attr = lc($attr);
1259  
1260 ### Break attribute name up:
1261 2 my ( $tag, $subtag ) = split /\./, $attr;
1262 2 ▶ if (defined($subtag)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $subtag) 2 0 2
1263 2 ▶ $attrs = $self->{SubAttrs}{$tag} ||= {};
Condition100%2/2
$self->{"SubAttrs"}{$tag} ||= {}
l!l
11
MC/DC100%1/1
$self->{"SubAttrs"}{$tag} ||= {}
$self->{"SubAttrs"}{$tag}
Truth table100%2/2
A
A= $self->{"SubAttrs"}{$tag}
Aresult
11
00
1264 2 $tag = $subtag;
1265 }
1266  
1267 ### Set or get?
1268 2 ▶ if ( @_ > 2 ) { ### set:
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 2) 1 1 2
1269 1 ▶ if ( defined($value) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $value) { } 1 0 1
1270 1 $attrs->{$tag} = $value;
1271 } else {
1272 0 delete $attrs->{$tag};
1273 }
1274 }
1275  
1276 ### Return current value:
1277 2 $attrs->{$tag};
1278 }
1279  
1280 sub _safe_attr {
1281 0 ▶ my ( $self, $attr ) = @_;
Subroutine _safe_attr: not called CC=2 SCAR=17.9
1282 0 ▶ return defined $self->{Attrs}{$attr} ? $self->{Attrs}{$attr} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{'Attrs'}{$attr} ? : 0 0 0
1283 }
1284  
1285 #------------------------------
1286  
1287 =item delete TAG
1288  
1289 I<Instance method.>
1290 Delete field TAG with the given VALUE to the end of the header.
1291 The TAG will be converted to all-lowercase.
1292  
1293 $msg->delete("Subject");
1294  
1295 I<Note:> the name comes from Mail::Header.
1296  
1297 =cut
1298  
1299  
1300 sub delete {
1301 17 ▶ my $self = shift;
Subroutine delete: called CC=3 SCAR=11.0
Pod documented
1302 17 my $tag = lc(shift);
1303  
1304 ### Delete from the header:
1305 17 my $hdr = [];
1306 17 my $field;
1307 17 foreach $field ( @{ $self->{Header} } ) {
1308 11 ▶ push @$hdr, $field if ( $field->[0] ne $tag );
Branch: 1 branch
BranchTrueFalseTotal
if $field->[0] ne $tag 7 4 11
1309 }
1310 17 $self->{Header} = $hdr;
1311 17 $self;
1312 }
1313  
1314  
1315 #------------------------------
1316  
1317 =item field_order FIELD,...FIELD
1318  
1319 I<Class/instance method.>
1320 Change the order in which header fields are output for this object:
1321  
1322 $msg->field_order('from', 'to', 'content-type', 'subject');
1323  
1324 When used as a class method, changes the default settings for
1325 all objects:
1326  
1327 MIME::Lite->field_order('from', 'to', 'content-type', 'subject');
1328  
1329 Case does not matter: all field names will be coerced to lowercase.
1330 In either case, supply the empty array to restore the default ordering.
1331  
1332 =cut
1333  
1334  
1335 sub field_order {
1336 1 ▶ my $self = shift;
Subroutine field_order: called CC=2 SCAR=7.9
Pod documented
1337 1 ▶ if ( ref($self) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self) { } 1 0 1
1338 1 $self->{FieldOrder} = [ map { lc($_) } @_ ];
1339 } else {
1340 0 @FieldOrder = map { lc($_) } @_;
1341 }
1342 }
1343  
1344 #------------------------------
1345  
1346 =item fields
1347  
1348 I<Instance method.>
1349 Return the full header for the object, as a ref to an array
1350 of C<[TAG, VALUE]> pairs, where each TAG is all-lowercase.
1351 Note that any fields the user has explicitly set will override the
1352 corresponding MIME fields that we would otherwise generate.
1353 So, don't say...
1354  
1355 $msg->set("Content-type" => "text/html; charset=US-ASCII");
1356  
1357 unless you want the above value to override the "Content-type"
1358 MIME field that we would normally generate.
1359  
1360 I<Note:> I called this "fields" because the header() method of
1361 Mail::Header returns something different, but similar enough to
1362 be confusing.
1363  
1364 You can change the order of the fields: see L</field_order>.
1365 You really shouldn't need to do this, but some people have to
1366 deal with broken mailers.
1367  
1368 =cut
1369  
1370  
1371 sub fields {
1372 16 ▶ my $self = shift;
Subroutine fields: called CC=10 SCAR=23.0
Pod documented
1373 16 my @fields;
1374 16 my $attrs = $self->{Attrs};
1375 16 my $sub_attrs = $self->{SubAttrs};
1376  
1377 ### Get a lookup-hash of all *explicitly-given* fields:
1378 16 my %explicit = map { $_->[0] => 1 } @{ $self->{Header} };
1379  
1380 ### Start with any MIME attributes not given explicitly:
1381 16 my $tag;
1382 16 foreach $tag ( sort keys %{ $self->{Attrs} } ) {
1383  
1384 ### Skip if explicit:
1385 66 ▶ next if ( $explicit{$tag} );
Branch: 1 branch
BranchTrueFalseTotal
if $explicit{$tag} 0 66 66
1386  
1387 # get base attr value or skip if not available
1388 66 my $value = $attrs->{$tag};
1389 66 ▶ defined $value or next;
Branch: 1 branch
BranchTrueFalseTotal
defined $value or next 13 53 66
1390  
1391 ### handle sub-attrs if available
1392 53 ▶ if (my $subs = $sub_attrs->{$tag}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $subs = $sub_attrs->{$tag}) 8 45 53
1393 $value .= '; ' .
1394 8 join('; ', map { qq{$_="$subs->{$_}"} } sort keys %$subs);
1395 }
1396  
1397 # handle stripping \r\n now since we're not doing it in attr()
1398 # anymore
1399 53 $value =~ tr/\r\n//;
1400  
1401 ### Add to running fields;
1402 53 push @fields, [ $tag, $value ];
1403 }
1404  
1405 ### Add remaining fields (note that we duplicate the array for safety):
1406 16 foreach ( @{ $self->{Header} } ) {
1407 16 push @fields, [ @{$_} ];
1408 }
1409  
1410 ### Final step:
1411 ### If a suggested ordering was given, we "sort" by that ordering.
1412 ### The idea is that we give each field a numeric rank, which is
1413 ### (1000 * order(field)) + origposition.
1414 16 ▶ my @order = @{ $self->{FieldOrder} || [] }; ### object-specific
Branch: 1 branch
BranchTrueFalseTotal
$self->{"FieldOrder"} or [] 15 1 16
1415 16 ▶ @order or @order = @FieldOrder; ### no? maybe generic
Branch: 1 branch
BranchTrueFalseTotal
@order or @order = @FieldOrder 15 1 16
1416 16 ▶ if (@order) { ### either?
Branch: 1 branch
BranchTrueFalseTotal
if (@order) 1 15 16
1417  
1418 ### Create hash mapping field names to 1-based rank:
1419 1 my %rank = map { $order[$_] => ( 1 + $_ ) } ( 0 .. $#order );
1420  
1421 ### Create parallel array to @fields, called @ranked.
1422 ### It contains fields tagged with numbers like 2003, where the
1423 ### 3 is the original 0-based position, and 2000 indicates that
1424 ### we wanted ths type of field to go second.
1425 my @ranked = map {
1426 1 ▶ [ ( $_ + 1000 * ( $rank{ lc( $fields[$_][0] ) } || ( 2 + $#order ) ) ), $fields[$_] ]
Condition66%2/3
$rank{lc $fields[$_][0]} || 2 + $#order
l!l&&r!l&&!r
710
MC/DC0%0/2
$rank{lc $fields[$_][0]} || 2 + $#order
$rank{lc $fields[$_][0]} 2 + $#order
Truth table66%2/3
A || B
A= $rank{lc $fields[$_][0]}B= 2 + $#order
ABresult
1X1
011
000
1427 } ( 0 .. $#fields );
1428  
1429 # foreach (@ranked) {
1430 # print STDERR "RANKED: $_->[0] $_->[1][0] $_->[1][1]\n";
1431 # }
1432  
1433 ### That was half the Schwartzian transform. Here's the rest:
1434 8 @fields = map { $_->[1] }
1435 1 sort { $a->[0] <=> $b->[0] } @ranked;
1436 }
1437  
1438 ### Done!
1439 16 return \@fields;
1440 }
1441  
1442  
1443 #------------------------------
1444  
1445 =item filename [FILENAME]
1446  
1447 I<Instance method.>
1448 Set the filename which this data will be reported as.
1449 This actually sets both "standard" attributes.
1450  
1451 With no argument, returns the filename as dictated by the
1452 content-disposition.
1453  
1454 =cut
1455  
1456  
1457 sub filename {
1458 5 ▶ my ( $self, $filename ) = @_;
Subroutine filename: called CC=2 SCAR=7.0
Pod documented
1459 5 my $sub_attrs = $self->{SubAttrs};
1460  
1461 5 ▶ if ( @_ > 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 5 0 5
1462 5 $sub_attrs->{'content-type'}{'name'} = $filename;
1463 5 $sub_attrs->{'content-disposition'}{'filename'} = $filename;
1464 }
1465 5 return $sub_attrs->{'content-disposition'}{'filename'};
1466 }
1467  
1468 #------------------------------
1469  
1470 =item get TAG,[INDEX]
1471  
1472 I<Instance method.>
1473 Get the contents of field TAG, which might have been set
1474 with set() or replace(). Returns the text of the field.
1475  
1476 $ml->get('Subject', 0);
1477  
1478 If the optional 0-based INDEX is given, then we return the INDEX'th
1479 occurence of field TAG. Otherwise, we look at the context:
1480 In a scalar context, only the first (0th) occurence of the
1481 field is returned; in an array context, I<all> occurences are returned.
1482  
1483 I<Warning:> this should only be used with non-MIME fields.
1484 Behavior with MIME fields is TBD, and will raise an exception for now.
1485  
1486 =cut
1487  
1488  
1489 sub get {
1490 12 ▶ my ( $self, $tag, $index ) = @_;
Subroutine get: called CC=5 SCAR=16.1
Pod documented
1491 12 $tag = lc($tag);
1492 12 ▶ Carp::croak "get: can't be used with MIME fields\n" if is_mime_field($tag);
Branch: 1 branch
BranchTrueFalseTotal
if is_mime_field($tag) 0 12 12
1493  
1494 12 ▶ my @all = map { ( $_->[0] eq $tag ) ? $_->[1] : () } @{ $self->{Header} };
Branch: 1 branch
BranchTrueFalseTotal
$_->[0] eq $tag ? : 23 43 66
1495 12 ▶ ( defined($index) ? $all[$index] : ( wantarray ? @all : $all[0] ) );
Branch: 2 branches
BranchTrueFalseTotal
defined $index ? : 7 5 12
wantarray ? : 2 3 5
1496 }
1497  
1498 #------------------------------
1499  
1500 =item get_length
1501  
1502 I<Instance method.>
1503 Recompute the content length for the message I<if the process is trivial>,
1504 setting the "content-length" attribute as a side-effect:
1505  
1506 $msg->get_length;
1507  
1508 Returns the length, or undefined if not set.
1509  
1510 I<Note:> the content length can be difficult to compute, since it
1511 involves assembling the entire encoded body and taking the length
1512 of it (which, in the case of multipart messages, means freezing
1513 all the sub-parts, etc.).
1514  
1515 This method only sets the content length to a defined value if the
1516 message is a singlepart with C<"binary"> encoding, I<and> the body is
1517 available either in-core or as a simple file. Otherwise, the content
1518 length is set to the undefined value.
1519  
1520 Since content-length is not a standard MIME field anyway (that's right, kids:
1521 it's not in the MIME RFCs, it's an HTTP thing), this seems pretty fair.
1522  
1523 =cut
1524  
1525  
1526 #----
1527 # Miko's note: I wasn't quite sure how to handle this, so I waited to hear
1528 # what you think. Given that the content-length isn't always required,
1529 # and given the performance cost of calculating it from a file handle,
1530 # I thought it might make more sense to add some some sort of computelength
1531 # property. If computelength is false, then the length simply isn't
1532 # computed. What do you think?
1533 #
1534 # Eryq's reply: I agree; for now, we can silently leave out the content-type.
1535  
1536 sub get_length {
1537 36 ▶ my $self = shift;
Subroutine get_length: called CC=8 SCAR=20.9
Pod documented
1538 36 my $attrs = $self->{Attrs};
1539  
1540 36 my $is_multipart = ( $attrs->{'content-type'} =~ m{^multipart/}i );
1541 36 ▶ my $enc = lc( $attrs->{'content-transfer-encoding'} || 'binary' );
Condition100%2/2
$attrs->{'content-transfer-encoding'} || 'binary'
l!l
1917
MC/DC100%1/1
$attrs->{'content-transfer-encoding'} || 'binary'
$attrs->{'content-transfer-encoding'}
Truth table100%2/2
A
A= $attrs->{'content-transfer-encoding'}
Aresult
11
00
1542 36 my $length;
1543 36 ▶ if ( !$is_multipart && ( $enc eq "binary" ) ) { ### might figure it out cheap:
Branch: 1 branch
BranchTrueFalseTotal
if (not $is_multipart and $enc eq "binary") 17 19 36
Condition66%2/3
not $is_multipart and $enc eq "binary"
!ll&&!rl&&r
01917
MC/DC50%1/2
not $is_multipart and $enc eq "binary"
not $is_multipart $enc eq "binary"
Truth table66%2/3
not(A) and B
A= not $is_multipartB= $enc eq "binary"
ABresult
0X0
100
111
1544 17 ▶ if ( defined( $self->{Data} ) ) { ### it's in core
Branch: 3 branches
BranchTrueFalseTotal
if (defined $self->{'Data'}) { } 13 4 17
elsif (defined $self->{'FH'}) { } 0 4 4
elsif (defined $self->{'Path'}) { } 4 0 4
1545 13 $length = length( $self->{Data} );
1546 } elsif ( defined( $self->{FH} ) ) { ### it's in a filehandle
1547 ### no-op: it's expensive, so don't bother
1548 } elsif ( defined( $self->{Path} ) ) { ### it's a simple file!
1549 4 ▶ $length = ( -s $self->{Path} ) if ( -e $self->{Path} );
Branch: 1 branch
BranchTrueFalseTotal
if -e $self->{"Path"} 2 2 4
1550 }
1551 }
1552 36 $attrs->{'content-length'} = $length;
1553 36 return $length;
1554 }
1555  
1556 #------------------------------
1557  
1558 =item parts
1559  
1560 I<Instance method.>
1561 Return the parts of this entity, and this entity only.
1562 Returns empty array if this entity has no parts.
1563  
1564 This is B<not> recursive! Parts can have sub-parts; use
1565 parts_DFS() to get everything.
1566  
1567 =cut
1568  
1569  
1570 sub parts {
1571 9 ▶ my $self = shift;
Subroutine parts: called CC=2 SCAR=7.1
Pod documented
1572 9 ▶ @{ $self->{Parts} || [] };
Branch: 1 branch
BranchTrueFalseTotal
$self->{"Parts"} or [] 0 9 9
1573 }
1574  
1575 #------------------------------
1576  
1577 =item parts_DFS
1578  
1579 I<Instance method.>
1580 Return the list of all MIME::Lite objects included in the entity,
1581 starting with the entity itself, in depth-first-search order.
1582 If this object has no parts, it alone will be returned.
1583  
1584 =cut
1585  
1586  
1587 sub parts_DFS {
1588 8 ▶ my $self = shift;
Subroutine parts_DFS: called CC=1 SCAR=0.0
Pod documented
1589 8 return ( $self, map { $_->parts_DFS } $self->parts );
1590 }
1591  
1592 #------------------------------
1593  
1594 =item preamble [TEXT]
1595  
1596 I<Instance method.>
1597 Get/set the preamble string, assuming that this object has subparts.
1598 Set it to undef for the default string.
1599  
1600 =cut
1601  
1602  
1603 sub preamble {
1604 0 ▶ my $self = shift;
Subroutine preamble: not called CC=2 SCAR=17.9
Pod documented
1605 0 ▶ $self->{Preamble} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 0 0
1606 0 $self->{Preamble};
1607 }
1608  
1609 #------------------------------
1610  
1611 =item replace TAG,VALUE
1612  
1613 I<Instance method.>
1614 Delete all occurences of fields named TAG, and add a new
1615 field with the given VALUE. TAG is converted to all-lowercase.
1616  
1617 B<Beware> the special MIME fields (MIME-version, Content-*):
1618 if you "replace" a MIME field, the replacement text will override
1619 the I<actual> MIME attributes when it comes time to output that field.
1620 So normally you use attr() to change MIME fields and add()/replace() to
1621 change I<non-MIME> fields:
1622  
1623 $msg->replace("Subject" => "Hi there!");
1624  
1625 Giving VALUE as the I<empty string> will effectively I<prevent> that
1626 field from being output. This is the correct way to suppress
1627 the special MIME fields:
1628  
1629 $msg->replace("Content-disposition" => "");
1630  
1631 Giving VALUE as I<undefined> will just cause all explicit values
1632 for TAG to be deleted, without having any new values added.
1633  
1634 I<Note:> the name of this method comes from Mail::Header.
1635  
1636 =cut
1637  
1638  
1639 sub replace {
1640 1 ▶ my ( $self, $tag, $value ) = @_;
Subroutine replace: called CC=2 SCAR=7.1
Pod documented
1641 1 $self->delete($tag);
1642 1 ▶ $self->add( $tag, $value ) if defined($value);
Branch: 1 branch
BranchTrueFalseTotal
if defined $value 1 0 1
1643 }
1644  
1645  
1646 #------------------------------
1647  
1648 =item scrub
1649  
1650 I<Instance method.>
1651 B<This is Alpha code. If you use it, please let me know how it goes.>
1652 Recursively goes through the "parts" tree of this message and tries
1653 to find MIME attributes that can be removed.
1654 With an array argument, removes exactly those attributes; e.g.:
1655  
1656 $msg->scrub(['content-disposition', 'content-length']);
1657  
1658 Is the same as recursively doing:
1659  
1660 $msg->replace('Content-disposition' => '');
1661 $msg->replace('Content-length' => '');
1662  
1663 =cut
1664  
1665  
1666 sub scrub {
1667 0 ▶ my ( $self, @a ) = @_;
Subroutine scrub: not called CC=12 SCAR=50.5
Pod documented
1668 0 my ($expl) = @a;
1669 0 local $QUIET = 1;
1670  
1671 ### Scrub me:
1672 0 ▶ if ( !@a ) { ### guess
Branch: 2 branches
BranchTrueFalseTotal
if (not @a) { } 0 0 0
elsif ($expl and ref $expl eq 'ARRAY') { } 0 0 0
1673  
1674 ### Scrub length always:
1675 0 $self->replace( 'content-length', '' );
1676  
1677 ### Scrub disposition if no filename, or if content-type has same info:
1678 0 ▶ if ( !$self->_safe_attr('content-disposition.filename')
Branch: 1 branch
BranchTrueFalseTotal
if (not $self->_safe_attr("content-disposition.filename") or $self->_safe_attr("content-type.name")) 0 0 0
Condition0%0/3
not $self->_safe_attr("content-disposition.filename") or $self->_safe_attr("content-type.name")
l!l&&r!l&&!r
000
MC/DC0%0/2
not $self->_safe_attr("content-disposition.filename") or $self->_safe_attr("content-type.name")
not $self->_safe_attr("content-disposition.filename") $self->_safe_attr("content-type.name")
Truth table0%0/3
not(A) or B
A= not $self->_safe_attr("content-disposition.filename")B= $self->_safe_attr("content-type.name")
ABresult
1X1
011
000
1679 || $self->_safe_attr('content-type.name') )
1680 {
1681 0 $self->replace( 'content-disposition', '' );
1682 }
1683  
1684 ### Scrub encoding if effectively unencoded:
1685 0 ▶ if ( $self->_safe_attr('content-transfer-encoding') =~ /^(7bit|8bit|binary)$/i ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_safe_attr("content-transfer-encoding") =~ /^(7bit|8bit|binary)$/i) 0 0 0
1686 0 $self->replace( 'content-transfer-encoding', '' );
1687 }
1688  
1689 ### Scrub charset if US-ASCII:
1690 0 ▶ if ( $self->_safe_attr('content-type.charset') =~ /^(us-ascii)/i ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_safe_attr("content-type.charset") =~ /^(us-ascii)/i) 0 0 0
1691 0 $self->attr( 'content-type.charset' => undef );
1692 }
1693  
1694 ### TBD: this is not really right for message/digest:
1695 0 ▶ if ( ( keys %{ $self->{Attrs}{'content-type'} } == 1 )
Branch: 1 branch
BranchTrueFalseTotal
if (keys %{$$self{"Attrs"}{"content-type"};} == 1 and $self->_safe_attr("content-type") eq "text/plain") 0 0 0
Condition0%0/3
keys %{$$self{"Attrs"}{"content-type"};} == 1 and $self->_safe_attr("content-type") eq "text/plain"
!ll&&!rl&&r
000
MC/DC0%0/2
keys %{$$self{"Attrs"}{"content-type"};} == 1 and $self->_safe_attr("content-type") eq "text/plain"
keys %{$$self{"Attrs"}{"content-type"};} == 1 $self->_safe_attr("content-type") eq "text/plain"
Truth table0%0/3
A and B
A= keys %{$$self{"Attrs"}{"content-type"};} == 1B= $self->_safe_attr("content-type") eq "text/plain"
ABresult
0X0
100
111
1696 and ( $self->_safe_attr('content-type') eq 'text/plain' ) )
1697 {
1698 0 $self->replace( 'content-type', '' );
1699 }
1700 ▶ } elsif ( $expl and ( ref($expl) eq 'ARRAY' ) ) {
Condition0%0/3
$expl and ref $expl eq "ARRAY"
!ll&&!rl&&r
000
MC/DC0%0/2
$expl and ref $expl eq "ARRAY"
$expl ref $expl eq "ARRAY"
Truth table0%0/3
A and B
A= $explB= ref $expl eq "ARRAY"
ABresult
0X0
100
111
1701 0 foreach ( @{$expl} ) { $self->replace( $_, '' ); }
1702 }
1703  
1704 ### Scrub my kids:
1705 0 foreach ( @{ $self->{Parts} } ) { $_->scrub(@a); }
1706 }
1707  
1708 =back
1709  
1710 =cut
1711  
1712  
1713 #==============================
1714 #==============================
1715  
1716 =head2 Setting/getting message data
1717  
1718 =over 4
1719  
1720 =cut
1721  
1722  
1723 #------------------------------
1724  
1725 =item binmode [OVERRIDE]
1726  
1727 I<Instance method.>
1728 With no argument, returns whether or not it thinks that the data
1729 (as given by the "Path" argument of C<build()>) should be read using
1730 binmode() (for example, when C<read_now()> is invoked).
1731  
1732 The default behavior is that any content type other than
1733 C<text/*> or C<message/*> is binmode'd; this should in general work fine.
1734  
1735 With a defined argument, this method sets an explicit "override"
1736 value. An undefined argument unsets the override.
1737 The new current value is returned.
1738  
1739 =cut
1740  
1741  
1742 sub binmode {
1743 2 ▶ my $self = shift;
Subroutine binmode: called CC=3 SCAR=11.7
Pod documented
1744 2 ▶ $self->{Binmode} = shift if (@_); ### argument? set override
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 2 2
1745 return ( defined( $self->{Binmode} )
1746 ? $self->{Binmode}
1747 2 ▶ : ( $self->{Attrs}{"content-type"} !~ m{^(text|message)/}i )
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{'Binmode'} ? : 0 2 2
1748 );
1749 }
1750  
1751 #------------------------------
1752  
1753 =item data [DATA]
1754  
1755 I<Instance method.>
1756 Get/set the literal DATA of the message. The DATA may be
1757 either a scalar, or a reference to an array of scalars (which
1758 will simply be joined).
1759  
1760 I<Warning:> setting the data causes the "content-length" attribute
1761 to be recomputed (possibly to nothing).
1762  
1763 =cut
1764  
1765  
1766 sub data {
1767 13 ▶ my $self = shift;
Subroutine data: called CC=3 SCAR=11.0
Pod documented
1768 13 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 13 0 13
1769 13 ▶ $self->{Data} = ( ( ref( $_[0] ) eq 'ARRAY' ) ? join( '', @{ $_[0] } ) : $_[0] );
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'ARRAY' ? : 2 11 13
1770 13 $self->get_length;
1771 }
1772 13 $self->{Data};
1773 }
1774  
1775 #------------------------------
1776  
1777 =item fh [FILEHANDLE]
1778  
1779 I<Instance method.>
1780 Get/set the FILEHANDLE which contains the message data.
1781  
1782 Takes a filehandle as an input and stores it in the object.
1783 This routine is similar to path(); one important difference is that
1784 no attempt is made to set the content length.
1785  
1786 =cut
1787  
1788  
1789 sub fh {
1790 0 ▶ my $self = shift;
Subroutine fh: not called CC=2 SCAR=17.9
Pod documented
1791 0 ▶ $self->{FH} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 0 0
1792 0 $self->{FH};
1793 }
1794  
1795 #------------------------------
1796  
1797 =item path [PATH]
1798  
1799 I<Instance method.>
1800 Get/set the PATH to the message data.
1801  
1802 I<Warning:> setting the path recomputes any existing "content-length" field,
1803 and re-sets the "filename" (to the last element of the path if it
1804 looks like a simple path, and to nothing if not).
1805  
1806 =cut
1807  
1808  
1809 sub path {
1810 4 ▶ my $self = shift;
Subroutine path: called CC=5 SCAR=16.4
Pod documented
1811 4 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 4 0 4
1812  
1813 ### Set the path, and invalidate the content length:
1814 4 $self->{Path} = shift;
1815  
1816 ### Re-set filename, extracting it from path if possible:
1817 4 my $filename;
1818 4 ▶ if ( $self->{Path} and ( $self->{Path} !~ /\|$/ ) ) { ### non-shell path:
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"Path"} and not $self->{"Path"} =~ /\|$/) 3 1 4
Condition66%2/3
$self->{"Path"} and not $self->{"Path"} =~ /\|$/
!ll&&!rl&&r
013
MC/DC50%1/2
$self->{"Path"} and not $self->{"Path"} =~ /\|$/
$self->{"Path"} not $self->{"Path"} =~ /\|$/
Truth table66%2/3
A and not(B)
A= $self->{"Path"}B= not $self->{"Path"} =~ /\|$/
ABresult
0X0
100
111
1819 3 ( $filename = $self->{Path} ) =~ s/^<//;
1820  
1821 ### Consult File::Basename, maybe:
1822 3 ▶ if ($HaveFileBasename) {
Branch: 1 branch
BranchTrueFalseTotal
if ($HaveFileBasename) { } 3 0 3
1823 3 $filename = File::Basename::basename($filename);
1824 } else {
1825 0 ($filename) = ( $filename =~ m{([^\/]+)\Z} );
1826 }
1827 }
1828 4 $self->filename($filename);
1829  
1830 ### Reset the length:
1831 4 $self->get_length;
1832 }
1833 4 $self->{Path};
1834 }
1835  
1836 #------------------------------
1837  
1838 =item resetfh [FILEHANDLE]
1839  
1840 I<Instance method.>
1841 Set the current position of the filehandle back to the beginning.
1842 Only applies if you used "FH" in build() or attach() for this message.
1843  
1844 Returns false if unable to reset the filehandle (since not all filehandles
1845 are seekable).
1846  
1847 =cut
1848  
1849  
1850 #----
1851 # Miko's note: With the Data and Path, the same data could theoretically
1852 # be reused. However, file handles need to be reset to be reused,
1853 # so I added this routine.
1854 #
1855 # Eryq reply: beware... not all filehandles are seekable (think about STDIN)!
1856  
1857 sub resetfh {
1858 0 ▶ my $self = shift;
Subroutine resetfh: not called CC=1 SCAR=6.9
Pod documented
1859 0 seek( $self->{FH}, 0, 0 );
1860 }
1861  
1862 #------------------------------
1863  
1864 =item read_now
1865  
1866 I<Instance method.>
1867 Forces data from the path/filehandle (as specified by C<build()>)
1868 to be read into core immediately, just as though you had given it
1869 literally with the C<Data> keyword.
1870  
1871 Note that the in-core data will always be used if available.
1872  
1873 Be aware that everything is slurped into a giant scalar: you may not want
1874 to use this if sending tar files! The benefit of I<not> reading in the data
1875 is that very large files can be handled by this module if left on disk
1876 until the message is output via C<print()> or C<print_body()>.
1877  
1878 =cut
1879  
1880  
1881 sub read_now {
1882 1 ▶ my $self = shift;
Subroutine read_now: called CC=7 SCAR=26.9
Pod documented
1883 1 local $/ = undef;
1884  
1885 1 ▶ if ( $self->{FH} ) { ### data from a filehandle:
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'FH'}) { } 0 1 1
elsif ($self->{'Path'}) { } 1 0 1
1886 0 my $chunk;
1887 my @chunks;
1888 0 ▶ CORE::binmode( $self->{FH} ) if $self->binmode;
Branch: 1 branch
BranchTrueFalseTotal
if $self->binmode 0 0 0
1889 0 ▶ while ( read( $self->{FH}, $chunk, 1024 ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (read $self->{"FH"}, $chunk, 1024) 0 0 0
1890 0 push @chunks, $chunk;
1891 }
1892 0 $self->{Data} = join '', @chunks;
1893 } elsif ( $self->{Path} ) { ### data from a path:
1894 1 ▶ open SLURP, $self->{Path} or Carp::croak "open $self->{Path}: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
open SLURP, $self->{"Path"} or Carp::croak(qq[open $self->{"Path"}: $!\n]) 0 1 1
1895 1 ▶ CORE::binmode(SLURP) if $self->binmode;
Branch: 1 branch
BranchTrueFalseTotal
if $self->binmode 0 1 1
1896 1 $self->{Data} = <SLURP>; ### sssssssssssssslurp...
1897 1 close SLURP; ### ...aaaaaaaaahhh!
1898 }
1899 }
1900  
1901 #------------------------------
1902  
1903 =item sign PARAMHASH
1904  
1905 I<Instance method.>
1906 Sign the message. This forces the message to be read into core,
1907 after which the signature is appended to it.
1908  
1909 =over 4
1910  
1911 =item Data
1912  
1913 As in C<build()>: the literal signature data.
1914 Can be either a scalar or a ref to an array of scalars.
1915  
1916 =item Path
1917  
1918 As in C<build()>: the path to the file.
1919  
1920 =back
1921  
1922 If no arguments are given, the default is:
1923  
1924 Path => "$ENV{HOME}/.signature"
1925  
1926 The content-length is recomputed.
1927  
1928 =cut
1929  
1930  
1931 sub sign {
1932 0 ▶ my $self = shift;
Subroutine sign: not called CC=7 SCAR=40.3
Pod documented
1933 0 my %params = @_;
1934  
1935 ### Default:
1936 0 ▶ @_ or $params{Path} = "$ENV{HOME}/.signature";
Branch: 1 branch
BranchTrueFalseTotal
@_ or $params{"Path"} = qq[$ENV{"HOME"}/.signature] 0 0 0
1937  
1938 ### Force message in-core:
1939 0 ▶ defined( $self->{Data} ) or $self->read_now;
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{"Data"} or $self->read_now 0 0 0
1940  
1941 ### Load signature:
1942 0 my $sig;
1943 0 ▶ if ( !defined( $sig = $params{Data} ) ) { ### not given explicitly:
Branch: 1 branch
BranchTrueFalseTotal
unless (defined($sig = $params{"Data"})) 0 0 0
1944 0 local $/ = undef;
1945 0 ▶ open SIG, $params{Path} or Carp::croak "open sig $params{Path}: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
open SIG, $params{"Path"} or Carp::croak(qq[open sig $params{"Path"}: $!\n]) 0 0 0
1946 0 $sig = <SIG>; ### sssssssssssssslurp...
1947 0 close SIG; ### ...aaaaaaaaahhh!
1948 }
1949 0 ▶ $sig = join( '', @$sig ) if ( ref($sig) and ( ref($sig) eq 'ARRAY' ) );
Branch: 1 branch
BranchTrueFalseTotal
if ref $sig and ref $sig eq "ARRAY" 0 0 0
Condition0%0/3
ref $sig and ref $sig eq "ARRAY"
!ll&&!rl&&r
000
MC/DC0%0/2
ref $sig and ref $sig eq "ARRAY"
ref $sig ref $sig eq "ARRAY"
Truth table0%0/3
A and B
A= ref $sigB= ref $sig eq "ARRAY"
ABresult
0X0
100
111
1950  
1951 ### Append, following Internet conventions:
1952 0 $self->{Data} .= "\n-- \n$sig";
1953  
1954 ### Re-compute length:
1955 0 $self->get_length;
1956 0 1;
1957 }
1958  
1959 #------------------------------
1960 #
1961 # =item suggest_encoding CONTENTTYPE
1962 #
1963 # I<Class/instance method.>
1964 # Based on the CONTENTTYPE, return a good suggested encoding.
1965 # C<text> and C<message> types have their bodies scanned line-by-line
1966 # for 8-bit characters and long lines; lack of either means that the
1967 # message is 7bit-ok. Other types are chosen independent of their body:
1968 #
1969 # Major type: 7bit ok? Suggested encoding:
1970 # ------------------------------------------------------------
1971 # text yes 7bit
1972 # no quoted-printable
1973 # unknown binary
1974 #
1975 # message yes 7bit
1976 # no binary
1977 # unknown binary
1978 #
1979 # multipart n/a binary (in case some parts are not ok)
1980 #
1981 # (other) n/a base64
1982 #
1983 #=cut
1984  
1985 sub suggest_encoding {
1986 19 ▶ my ( $self, $ctype ) = @_;
Subroutine suggest_encoding: called CC=8 SCAR=29.3
Pod undocumented
1987 19 $ctype = lc($ctype);
1988  
1989 ### Consult MIME::Types, maybe:
1990 19 ▶ if ($HaveMimeTypes) {
Branch: 1 branch
BranchTrueFalseTotal
if ($HaveMimeTypes) 19 0 19
1991  
1992 ### Mappings contain [suffix,mimetype,encoding]
1993 19 my @mappings = MIME::Types::by_mediatype($ctype);
1994 19 ▶ if ( scalar(@mappings) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @mappings) 19 0 19
1995 ### Just pick the first one:
1996 19 my ( $suffix, $mimetype, $encoding ) = @{ $mappings[0] };
1997 19 ▶ if ( $encoding
Branch: 1 branch
BranchTrueFalseTotal
if ($encoding and $encoding =~ /^(base64|binary|[78]bit|quoted-printable)$/i) 19 0 19
Condition33%1/3
$encoding and $encoding =~ /^(base64|binary|[78]bit|quoted-printable)$/i
!ll&&!rl&&r
0019
MC/DC0%0/2
$encoding and $encoding =~ /^(base64|binary|[78]bit|quoted-printable)$/i
$encoding $encoding =~ /^(base64|binary|[78]bit|quoted-printable)$/i
Truth table33%1/3
A and B
A= $encodingB= $encoding =~ /^(base64|binary|[78]bit|quoted-printable)$/i
ABresult
0X0
100
111
1998 && $encoding =~ /^(base64|binary|[78]bit|quoted-printable)$/i )
1999 {
2000 19 return lc($encoding); ### sanity check
2001 }
2002 }
2003 }
2004  
2005 ### If we got here, then MIME::Types was no help.
2006 ### Extract major type:
2007 0 my ($type) = split '/', $ctype;
2008 0 ▶ if ( ( $type eq 'text' ) || ( $type eq 'message' ) ) { ### scan message body?
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq 'text' or $type eq 'message') { } 0 0 0
Condition0%0/3
$type eq "text" or $type eq "message"
l!l&&r!l&&!r
000
MC/DC0%0/2
$type eq "text" or $type eq "message"
$type eq "text" $type eq "message"
Truth table0%0/3
A or B
A= $type eq "text"B= $type eq "message"
ABresult
1X1
011
000
2009 0 return 'binary';
2010 } else {
2011 0 ▶ return ( $type eq 'multipart' ) ? 'binary' : 'base64';
Branch: 1 branch
BranchTrueFalseTotal
$type eq 'multipart' ? : 0 0 0
2012 }
2013 }
2014  
2015 #------------------------------
2016 #
2017 # =item suggest_type PATH
2018 #
2019 # I<Class/instance method.>
2020 # Suggest the content-type for this attached path.
2021 # We always fall back to "application/octet-stream" if no good guess
2022 # can be made, so don't use this if you don't mean it!
2023 #
2024 sub suggest_type {
2025 1 ▶ my ( $self, $path ) = @_;
Subroutine suggest_type: called CC=5 SCAR=18.9
Pod undocumented
2026  
2027 ### If there's no path, bail:
2028 1 ▶ $path or return 'application/octet-stream';
Branch: 1 branch
BranchTrueFalseTotal
$path or return "application/octet-stream" 0 1 1
2029  
2030 ### Consult MIME::Types, maybe:
2031 1 ▶ if ($HaveMimeTypes) {
Branch: 1 branch
BranchTrueFalseTotal
if ($HaveMimeTypes) 1 0 1
2032  
2033 # Mappings contain [mimetype,encoding]:
2034 1 my ( $mimetype, $encoding ) = MIME::Types::by_suffix($path);
2035 1 ▶ return $mimetype if ( $mimetype && $mimetype =~ /^\S+\/\S+$/ ); ### sanity check
Branch: 1 branch
BranchTrueFalseTotal
if $mimetype and $mimetype =~ m[^\S+/\S+$] 1 0 1
Condition33%1/3
$mimetype and $mimetype =~ m[^\S+/\S+$]
!ll&&!rl&&r
001
MC/DC0%0/2
$mimetype and $mimetype =~ m[^\S+/\S+$]
$mimetype $mimetype =~ m[^\S+/\S+$]
Truth table33%1/3
A and B
A= $mimetypeB= $mimetype =~ m[^\S+/\S+$]
ABresult
0X0
100
111
2036 }
2037 ### If we got here, then MIME::Types was no help.
2038 ### The correct thing to fall back to is the most-generic content type:
2039 0 return 'application/octet-stream';
2040 }
2041  
2042 #------------------------------
2043  
2044 =item verify_data
2045  
2046 I<Instance method.>
2047 Verify that all "paths" to attached data exist, recursively.
2048 It might be a good idea for you to do this before a print(), to
2049 prevent accidental partial output if a file might be missing.
2050 Raises exception if any path is not readable.
2051  
2052 =cut
2053  
2054  
2055 sub verify_data {
2056 35 ▶ my $self = shift;
Subroutine verify_data: called CC=5 SCAR=16.1
Pod documented
2057  
2058 ### Verify self:
2059 35 my $path = $self->{Path};
2060 35 ▶ if ( $path and ( $path !~ /\|$/ ) ) { ### non-shell path:
Branch: 1 branch
BranchTrueFalseTotal
if ($path and not $path =~ /\|$/) 4 31 35
Condition100%3/3
$path and not $path =~ /\|$/
!ll&&!rl&&r
3014
MC/DC100%2/2
$path and not $path =~ /\|$/
$path not $path =~ /\|$/
Truth table100%3/3
A and not(B)
A= $pathB= not $path =~ /\|$/
ABresult
0X0
100
111
2061 4 $path =~ s/^<//;
2062 4 ▶ ( -r $path ) or die "$path: not readable\n";
Branch: 1 branch
BranchTrueFalseTotal
-r $path or die "${path}: not readable\n" 1 3 4
2063 }
2064  
2065 ### Verify parts:
2066 34 foreach my $part ( @{ $self->{Parts} } ) { $part->verify_data }
2067 33 1;
2068 }
2069  
2070 =back
2071  
2072 =cut
2073  
2074  
2075 #==============================
2076 #==============================
2077  
2078 =head2 Output
2079  
2080 =over 4
2081  
2082 =cut
2083  
2084  
2085 #------------------------------
2086  
2087 =item print [OUTHANDLE]
2088  
2089 I<Instance method.>
2090 Print the message to the given output handle, or to the currently-selected
2091 filehandle if none was given.
2092  
2093 All OUTHANDLE has to be is a filehandle (possibly a glob ref), or
2094 any object that responds to a print() message.
2095  
2096 =cut
2097  
2098  
2099 sub print {
2100 15 ▶ my ( $self, $out ) = @_;
Subroutine print: called CC=2 SCAR=7.0
Pod documented
2101  
2102 ### Coerce into a printable output handle:
2103 15 $out = MIME::Lite::IO_Handle->wrap($out);
2104  
2105 ### Output head, separator, and body:
2106 15 ▶ $self->verify_data if $AUTO_VERIFY; ### prevents missing parts!
Branch: 1 branch
BranchTrueFalseTotal
if $MIME::Lite::AUTO_VERIFY 15 0 15
2107 15 $out->print( $self->header_as_string, "\n" );
2108 15 $self->print_body($out);
2109 }
2110  
2111 #------------------------------
2112 #
2113 # print_for_smtp
2114 #
2115 # Instance method, private.
2116 # Print, but filter out the topmost "Bcc" field.
2117 # This is because qmail apparently doesn't do this for us!
2118 #
2119 sub print_for_smtp {
2120 0 ▶ my ( $self, $out ) = @_;
Subroutine print_for_smtp: not called CC=1 SCAR=6.9
Pod undocumented
2121  
2122 ### Coerce into a printable output handle:
2123 0 $out = MIME::Lite::IO_Handle->wrap($out);
2124  
2125 ### Create a safe head:
2126 0 my @fields = grep { $_->[0] ne 'bcc' } @{ $self->fields };
2127 0 my $header = $self->fields_as_string( \@fields );
2128  
2129 ### Output head, separator, and body:
2130 0 $out->print( $header, "\n" );
2131 0 $self->print_body( $out, '1' );
2132 }
2133  
2134 #------------------------------
2135  
2136 =item print_body [OUTHANDLE] [IS_SMTP]
2137  
2138 I<Instance method.>
2139 Print the body of a message to the given output handle, or to
2140 the currently-selected filehandle if none was given.
2141  
2142 All OUTHANDLE has to be is a filehandle (possibly a glob ref), or
2143 any object that responds to a print() message.
2144  
2145 B<Fatal exception> raised if unable to open any of the input files,
2146 or if a part contains no data, or if an unsupported encoding is
2147 encountered.
2148  
2149 IS_SMPT is a special option to handle SMTP mails a little more
2150 intelligently than other send mechanisms may require. Specifically this
2151 ensures that the last byte sent is NOT '\n' (octal \012) if the last two
2152 bytes are not '\r\n' (\015\012) as this will cause some SMTP servers to
2153 hang.
2154  
2155 =cut
2156  
2157  
2158 sub print_body {
2159 15 ▶ my ( $self, $out, $is_smtp ) = @_;
Subroutine print_body: called CC=7 SCAR=22.6
Pod documented
2160 15 my $attrs = $self->{Attrs};
2161 15 my $sub_attrs = $self->{SubAttrs};
2162  
2163 ### Coerce into a printable output handle:
2164 15 $out = MIME::Lite::IO_Handle->wrap($out);
2165  
2166 ### Output either the body or the parts.
2167 ### Notice that we key off of the content-type! We expect fewer
2168 ### accidents that way, since the syntax will always match the MIME type.
2169 15 my $type = $attrs->{'content-type'};
2170 15 ▶ if ( $type =~ m{^multipart/}i ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($type =~ m[^multipart/]i) { } 3 12 15
elsif ($type =~ m[^message/]) { } 0 12 12
2171 3 my $boundary = $sub_attrs->{'content-type'}{'boundary'};
2172  
2173 ### Preamble:
2174 $out->print( defined( $self->{Preamble} )
2175 ? $self->{Preamble}
2176 3 ▶ : "This is a multi-part message in MIME format.\n"
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{'Preamble'} ? : 0 3 3
2177 );
2178  
2179 ### Parts:
2180 3 my $part;
2181 3 foreach $part ( @{ $self->{Parts} } ) {
2182 9 $out->print("\n--$boundary\n");
2183 9 $part->print($out);
2184 }
2185  
2186 ### Epilogue:
2187 3 $out->print("\n--$boundary--\n\n");
2188 } elsif ( $type =~ m{^message/} ) {
2189 0 my @parts = @{ $self->{Parts} };
2190  
2191 ### It's a toss-up; try both data and parts:
2192 0 ▶ if ( @parts == 0 ) { $self->print_simple_body( $out, $is_smtp ) }
Branch: 2 branches
BranchTrueFalseTotal
if (@parts == 0) { } 0 0 0
elsif (@parts == 1) { } 0 0 0
2193 0 elsif ( @parts == 1 ) { $parts[0]->print($out) }
2194 0 else { Carp::croak "can't handle message with >1 part\n"; }
2195 } else {
2196 12 $self->print_simple_body( $out, $is_smtp );
2197 }
2198 15 1;
2199 }
2200  
2201 #------------------------------
2202 #
2203 # print_simple_body [OUTHANDLE]
2204 #
2205 # I<Instance method, private.>
2206 # Print the body of a simple singlepart message to the given
2207 # output handle, or to the currently-selected filehandle if none
2208 # was given.
2209 #
2210 # Note that if you want to print "the portion after
2211 # the header", you don't want this method: you want
2212 # L<print_body()|/print_body>.
2213 #
2214 # All OUTHANDLE has to be is a filehandle (possibly a glob ref), or
2215 # any object that responds to a print() message.
2216 #
2217 # B<Fatal exception> raised if unable to open any of the input files,
2218 # or if a part contains no data, or if an unsupported encoding is
2219 # encountered.
2220 #
2221 sub print_simple_body {
2222 12 ▶ my ( $self, $out, $is_smtp ) = @_;
Subroutine print_simple_body: called CC=31 SCAR=56.8
Pod undocumented
2223 12 my $attrs = $self->{Attrs};
2224  
2225 ### Coerce into a printable output handle:
2226 12 $out = MIME::Lite::IO_Handle->wrap($out);
2227  
2228 ### Get content-transfer-encoding:
2229 12 my $encoding = uc( $attrs->{'content-transfer-encoding'} );
2230 12 ▶ warn "M::L >>> Encoding using $encoding, is_smtp=" . ( $is_smtp || 0 ) . "\n"
Branch: 1 branch
BranchTrueFalseTotal
if $MIME::Lite::DEBUG 0 12 12
Condition0%0/2
$is_smtp || 0
l!l
00
MC/DC0%0/1
$is_smtp || 0
$is_smtp
Truth table0%0/2
A
A= $is_smtp
Aresult
11
00
2231 if $MIME::Lite::DEBUG;
2232  
2233 ### Notice that we don't just attempt to slurp the data in from a file:
2234 ### by processing files piecemeal, we still enable ourselves to prepare
2235 ### very large MIME messages...
2236  
2237 ### Is the data in-core? If so, blit it out...
2238 12 ▶ if ( defined( $self->{Data} ) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $self->{'Data'}) { } 11 1 12
elsif (defined $self->{'Path'} or defined $self->{'FH'}) { } 1 0 1
2239 DATA:
2240 {
2241 11 local $_ = $encoding;
2242  
2243 11 ▶ /^BINARY$/ and do {
Branch: 1 branch
BranchTrueFalseTotal
/^BINARY$/ and do { $is_smtp and $self->{"Data"} =~ s/(?!\r)\n\z/\r/; $out->print($self->{"Data"}); last DATA } 0 11 11
2244 0 ▶ $is_smtp and $self->{Data} =~ s/(?!\r)\n\z/\r/;
Branch: 1 branch
BranchTrueFalseTotal
$is_smtp and $self->{"Data"} =~ s/(?!\r)\n\z/\r/ 0 0 0
2245 0 $out->print( $self->{Data} );
2246 0 last DATA;
2247 };
2248 11 ▶ /^8BIT$/ and do {
Branch: 1 branch
BranchTrueFalseTotal
/^8BIT$/ and do { $out->print(encode_8bit($self->{"Data"})); last DATA } 11 0 11
2249 11 $out->print( encode_8bit( $self->{Data} ) );
2250 11 last DATA;
2251 };
2252 0 ▶ /^7BIT$/ and do {
Branch: 1 branch
BranchTrueFalseTotal
/^7BIT$/ and do { $out->print(encode_7bit($self->{"Data"})); last DATA } 0 0 0
2253 0 $out->print( encode_7bit( $self->{Data} ) );
2254 0 last DATA;
2255 };
2256 0 ▶ /^QUOTED-PRINTABLE$/ and do {
Branch: 1 branch
BranchTrueFalseTotal
/^QUOTED-PRINTABLE$/ and do { my($untainted) = $self->{"Data"} =~ /\A(.*)\Z/s; while ($untainted =~ /^(.*[\r\n]*)/gms) { $out->print(&encode_qp($1)); } ; last DATA } 0 0 0
2257 ### UNTAINT since m//mg on tainted data loops forever:
2258 0 my ($untainted) = ( $self->{Data} =~ m/\A(.*)\Z/s );
2259  
2260 ### Encode it line by line:
2261 0 ▶ while ( $untainted =~ m{^(.*[\r\n]*)}smg ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($untainted =~ /^(.*[\r\n]*)/gms) 0 0 0
2262 0 $out->print( encode_qp($1) ); ### have to do it line by line...
2263 }
2264 0 last DATA;
2265 };
2266 0 ▶ /^BASE64/ and do {
Branch: 1 branch
BranchTrueFalseTotal
/^BASE64/ and do { $out->print(&encode_base64($self->{"Data"})); last DATA } 0 0 0
2267 0 $out->print( encode_base64( $self->{Data} ) );
2268 0 last DATA;
2269 };
2270 0 Carp::croak "unsupported encoding: `$_'\n";
2271 }
2272 }
2273  
2274 ### Else, is the data in a file? If so, output piecemeal...
2275 ### Miko's note: this routine pretty much works the same with a path
2276 ### or a filehandle. the only difference in behaviour is that it does
2277 ### not attempt to open anything if it already has a filehandle
2278 ▶ elsif ( defined( $self->{Path} ) || defined( $self->{FH} ) ) {
Condition33%1/3
defined $self->{"Path"} or defined $self->{"FH"}
l!l&&r!l&&!r
100
MC/DC0%0/2
defined $self->{"Path"} or defined $self->{"FH"}
defined $self->{"Path"} defined $self->{"FH"}
Truth table33%1/3
A or B
A= defined $self->{"Path"}B= defined $self->{"FH"}
ABresult
1X1
011
000
2279 6 ▶ no strict 'refs'; ### in case FH is not an object
Subroutine BEGIN: called CC=1 SCAR=0.0
2280 1 my $DATA;
2281  
2282 ### Open file if necessary:
2283 1 ▶ if ( defined( $self->{Path} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{'Path'}) { } 1 0 1
2284 1 ▶ $DATA = new FileHandle || Carp::croak "can't get new filehandle\n";
Condition33%1/3
'FileHandle'->new || Carp::croak("can't get new filehandle\n")
l!l&&r!l&&!r
100
MC/DC0%0/2
'FileHandle'->new || Carp::croak("can't get new filehandle\n")
'FileHandle'->new Carp::croak("can't get new filehandle\n")
Truth table33%1/3
A || B
A= 'FileHandle'->newB= Carp::croak("can't get new filehandle\n")
ABresult
1X1
011
000
2285 1 ▶ $DATA->open("$self->{Path}")
Branch: 1 branch
BranchTrueFalseTotal
$DATA->open(qq[$self->{"Path"}]) or Carp::croak(qq[open $self->{"Path"}: $!\n]) 0 1 1
2286 or Carp::croak "open $self->{Path}: $!\n";
2287 } else {
2288 0 $DATA = $self->{FH};
2289 }
2290 1 ▶ CORE::binmode($DATA) if $self->binmode;
Branch: 1 branch
BranchTrueFalseTotal
if $self->binmode 0 1 1
2291  
2292 ### Encode piece by piece:
2293 PATH:
2294 {
2295 1 local $_ = $encoding;
2296  
2297 1 ▶ /^BINARY$/ and do {
Branch: 1 branch
BranchTrueFalseTotal
/^BINARY$/ and do { my $last = ""; while (read $DATA, $_, 2048) { $out->print($last) if length $last; $last = $_; } ; if (length $last) { $is_smtp and $last =~ s/(?!\r)\n\z/\r/; $out->print($last); } ; last PATH } 0 1 1
2298 0 my $last = "";
2299 0 ▶ while ( read( $DATA, $_, 2048 ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (read $DATA, $_, 2048) 0 0 0
2300 0 ▶ $out->print($last) if length $last;
Branch: 1 branch
BranchTrueFalseTotal
if length $last 0 0 0
2301 0 $last = $_;
2302 }
2303 0 ▶ if ( length $last ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $last) 0 0 0
2304 0 ▶ $is_smtp and $last =~ s/(?!\r)\n\z/\r/;
Branch: 1 branch
BranchTrueFalseTotal
$is_smtp and $last =~ s/(?!\r)\n\z/\r/ 0 0 0
2305 0 $out->print($last);
2306 }
2307 0 last PATH;
2308 };
2309 1 ▶ /^8BIT$/ and do {
Branch: 1 branch
BranchTrueFalseTotal
/^8BIT$/ and do { $out->print(encode_8bit($_)) while defined($_ = readline $DATA); last PATH } 1 0 1
2310 1 ▶ $out->print( encode_8bit($_) ) while (<$DATA>);
Branch: 1 branch
BranchTrueFalseTotal
defined($_ = readline $DATA) and do { $out->print(encode_8bit($_)) } 2 1 3
2311 1 last PATH;
2312 };
2313 0 ▶ /^7BIT$/ and do {
Branch: 1 branch
BranchTrueFalseTotal
/^7BIT$/ and do { $out->print(encode_7bit($_)) while defined($_ = readline $DATA); last PATH } 0 0 0
2314 0 ▶ $out->print( encode_7bit($_) ) while (<$DATA>);
Branch: 1 branch
BranchTrueFalseTotal
defined($_ = readline $DATA) and do { $out->print(encode_7bit($_)) } 0 0 0
2315 0 last PATH;
2316 };
2317 0 ▶ /^QUOTED-PRINTABLE$/ and do {
Branch: 1 branch
BranchTrueFalseTotal
/^QUOTED-PRINTABLE$/ and do { $out->print(&encode_qp($_)) while defined($_ = readline $DATA); last PATH } 0 0 0
2318 0 ▶ $out->print( encode_qp($_) ) while (<$DATA>);
Branch: 1 branch
BranchTrueFalseTotal
defined($_ = readline $DATA) and do { $out->print(&encode_qp($_)) } 0 0 0
2319 0 last PATH;
2320 };
2321 0 ▶ /^BASE64$/ and do {
Branch: 1 branch
BranchTrueFalseTotal
/^BASE64$/ and do { $out->print(&encode_base64($_)) while read $DATA, $_, 45; last PATH } 0 0 0
2322 0 ▶ $out->print( encode_base64($_) ) while ( read( $DATA, $_, 45 ) );
Branch: 1 branch
BranchTrueFalseTotal
read $DATA, $_, 45 and do { $out->print(&encode_base64($_)) } 0 0 0
2323 0 last PATH;
2324 };
2325 0 Carp::croak "unsupported encoding: `$_'\n";
2326 }
2327  
2328 ### Close file:
2329 1 ▶ close $DATA if defined( $self->{Path} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"Path"} 1 0 1
2330 }
2331  
2332 else {
2333 0 Carp::croak "no data in this part\n";
2334 }
2335 12 1;
2336 }
2337  
2338 #------------------------------
2339  
2340 =item print_header [OUTHANDLE]
2341  
2342 I<Instance method.>
2343 Print the header of the message to the given output handle,
2344 or to the currently-selected filehandle if none was given.
2345  
2346 All OUTHANDLE has to be is a filehandle (possibly a glob ref), or
2347 any object that responds to a print() message.
2348  
2349 =cut
2350  
2351  
2352 sub print_header {
2353 0 ▶ my ( $self, $out ) = @_;
Subroutine print_header: not called CC=1 SCAR=6.9
Pod documented
2354  
2355 ### Coerce into a printable output handle:
2356 0 $out = MIME::Lite::IO_Handle->wrap($out);
2357  
2358 ### Output the header:
2359 0 $out->print( $self->header_as_string );
2360 0 1;
2361 }
2362  
2363 #------------------------------
2364  
2365 =item as_string
2366  
2367 I<Instance method.>
2368 Return the entire message as a string, with a header and an encoded body.
2369  
2370 =cut
2371  
2372  
2373 sub as_string {
2374 6 ▶ my $self = shift;
Subroutine as_string: called CC=1 SCAR=0.0
Pod documented
2375 6 my $buf = "";
2376 6 my $io = ( wrap MIME::Lite::IO_Scalar \$buf);
2377 6 $self->print($io);
2378 6 return $buf;
2379 }
2380 6 *stringify = \&as_string; ### backwards compatibility
2381 6 *stringify = \&as_string; ### ...twice to avoid warnings :)
2382  
2383 #------------------------------
2384  
2385 =item body_as_string
2386  
2387 I<Instance method.>
2388 Return the encoded body as a string.
2389 This is the portion after the header and the blank line.
2390  
2391 I<Note:> actually prepares the body by "printing" to a scalar.
2392 Proof that you can hand the C<print*()> methods any blessed object
2393 that responds to a C<print()> message.
2394  
2395 =cut
2396  
2397  
2398 sub body_as_string {
2399 0 ▶ my $self = shift;
Subroutine body_as_string: not called CC=1 SCAR=6.9
Pod documented
2400 0 my $buf = "";
2401 0 my $io = ( wrap MIME::Lite::IO_Scalar \$buf);
2402 0 $self->print_body($io);
2403 0 return $buf;
2404 }
2405 6 *stringify_body = \&body_as_string; ### backwards compatibility
2406 6 *stringify_body = \&body_as_string; ### ...twice to avoid warnings :)
2407  
2408 #------------------------------
2409 #
2410 # fields_as_string FIELDS
2411 #
2412 # PRIVATE! Return a stringified version of the given header
2413 # fields, where FIELDS is an arrayref like that returned by fields().
2414 #
2415 sub fields_as_string {
2416 15 ▶ my ( $self, $fields ) = @_;
Subroutine fields_as_string: called CC=3 SCAR=11.0
Pod undocumented
2417 15 my $out = "";
2418 15 foreach (@$fields) {
2419 61 my ( $tag, $value ) = @$_;
2420 61 ▶ next if ( $value eq '' ); ### skip empties
Branch: 1 branch
BranchTrueFalseTotal
if $value eq "" 0 61 61
2421 61 $tag =~ s/\b([a-z])/uc($1)/ge; ### make pretty
2422 61 $tag =~ s/^mime-/MIME-/i; ### even prettier
2423 61 $out .= "$tag: $value\n";
2424 }
2425 15 return $out;
2426 }
2427  
2428 #------------------------------
2429  
2430 =item header_as_string
2431  
2432 I<Instance method.>
2433 Return the header as a string.
2434  
2435 =cut
2436  
2437  
2438 sub header_as_string {
2439 15 ▶ my $self = shift;
Subroutine header_as_string: called CC=1 SCAR=0.0
Pod documented
2440 15 $self->fields_as_string( $self->fields );
2441 }
2442 6 *stringify_header = \&header_as_string; ### backwards compatibility
2443 6 *stringify_header = \&header_as_string; ### ...twice to avoid warnings :)
2444  
2445 =back
2446  
2447 =cut
2448  
2449  
2450 #==============================
2451 #==============================
2452  
2453 =head2 Sending
2454  
2455 =over 4
2456  
2457 =cut
2458  
2459  
2460 #------------------------------
2461  
2462 =item send
2463  
2464 =item send HOW, HOWARGS...
2465  
2466 I<Class/instance method.>
2467 This is the principal method for sending mail, and for configuring
2468 how mail will be sent.
2469  
2470 I<As a class method> with a HOW argument and optional HOWARGS, it sets
2471 the default sending mechanism that the no-argument instance method
2472 will use. The HOW is a facility name (B<see below>),
2473 and the HOWARGS is interpreted by the facilty.
2474 The class method returns the previous HOW and HOWARGS as an array.
2475  
2476 MIME::Lite->send('sendmail', "d:\\programs\\sendmail.exe");
2477 ...
2478 $msg = MIME::Lite->new(...);
2479 $msg->send;
2480  
2481 I<As an instance method with arguments>
2482 (a HOW argument and optional HOWARGS), sends the message in the
2483 requested manner; e.g.:
2484  
2485 $msg->send('sendmail', "d:\\programs\\sendmail.exe");
2486  
2487 I<As an instance method with no arguments,> sends the
2488 message by the default mechanism set up by the class method.
2489 Returns whatever the mail-handling routine returns: this
2490 should be true on success, false/exception on error:
2491  
2492 $msg = MIME::Lite->new(From=>...);
2493 $msg->send || die "you DON'T have mail!";
2494  
2495 On Unix systems (or rather non-Win32 systems), the default
2496 setting is equivalent to:
2497  
2498 MIME::Lite->send("sendmail", "/usr/lib/sendmail -t -oi -oem");
2499  
2500 On Win32 systems the default setting is equivalent to:
2501  
2502 MIME::Lite->send("smtp");
2503  
2504 The assumption is that on Win32 your site/lib/Net/libnet.cfg
2505 file will be preconfigured to use the appropriate SMTP
2506 server. See below for configuring for authentication.
2507  
2508 There are three facilities:
2509  
2510 =over 4
2511  
2512 =item "sendmail", ARGS...
2513  
2514 Send a message by piping it into the "sendmail" command.
2515 Uses the L<send_by_sendmail()|/send_by_sendmail> method, giving it the ARGS.
2516 This usage implements (and deprecates) the C<sendmail()> method.
2517  
2518 =item "smtp", [HOSTNAME, [NAMEDPARMS] ]
2519  
2520 Send a message by SMTP, using optional HOSTNAME as SMTP-sending host.
2521 Uses the L<send_by_smtp()|/send_by_smtp> method. Any additional
2522 arguments passed in will also be passed through to send_by_smtp.
2523 This is useful for things like mail servers requiring authentication
2524 where you can say something like the following
2525  
2526 MIME::List->send('smtp', $host, AuthUser=>$user, AuthPass=>$pass);
2527  
2528 which will configure things so future uses of
2529  
2530 $msg->send();
2531  
2532 do the right thing.
2533  
2534 =item "sub", \&SUBREF, ARGS...
2535  
2536 Sends a message MSG by invoking the subroutine SUBREF of your choosing,
2537 with MSG as the first argument, and ARGS following.
2538  
2539 =back
2540  
2541 I<For example:> let's say you're on an OS which lacks the usual Unix
2542 "sendmail" facility, but you've installed something a lot like it, and
2543 you need to configure your Perl script to use this "sendmail.exe" program.
2544 Do this following in your script's setup:
2545  
2546 MIME::Lite->send('sendmail', "d:\\programs\\sendmail.exe");
2547  
2548 Then, whenever you need to send a message $msg, just say:
2549  
2550 $msg->send;
2551  
2552 That's it. Now, if you ever move your script to a Unix box, all you
2553 need to do is change that line in the setup and you're done.
2554 All of your $msg-E<gt>send invocations will work as expected.
2555  
2556 After sending, the method last_send_successful() can be used to determine
2557 if the send was succesful or not.
2558  
2559 =cut
2560  
2561  
2562 sub send {
2563 0 ▶ my $self = shift;
Subroutine send: not called CC=7 SCAR=40.3
Pod documented
2564 0 my $meth = shift;
2565  
2566 0 ▶ if ( ref($self) ) { ### instance method:
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self) { } 0 0 0
2567 0 my ( $method, @args );
2568 0 ▶ if (@_) { ### args; use them just this once
Branch: 1 branch
BranchTrueFalseTotal
if (@_) { } 0 0 0
2569 0 $method = 'send_by_' . $meth;
2570 0 @args = @_;
2571 } else { ### no args; use defaults
2572 0 $method = "send_by_$Sender";
2573 0 ▶ @args = @{ $SenderArgs{$Sender} || [] };
Branch: 1 branch
BranchTrueFalseTotal
$SenderArgs{$Sender} or [] 0 0 0
2574 }
2575 0 ▶ $self->verify_data if $AUTO_VERIFY; ### prevents missing parts!
Branch: 1 branch
BranchTrueFalseTotal
if $MIME::Lite::AUTO_VERIFY 0 0 0
2576 0 ▶ Carp::croak "Unknown send method '$meth'" unless $self->can($method);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->can($method) 0 0 0
2577 0 return $self->$method(@args);
2578 } else { ### class method:
2579 0 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) { } 0 0 0
2580 0 my @old = ( $Sender, @{ $SenderArgs{$Sender} } );
2581 0 $Sender = $meth;
2582 0 $SenderArgs{$Sender} = [@_]; ### remaining args
2583 0 return @old;
2584 } else {
2585 0 Carp::croak "class method send must have HOW... arguments\n";
2586 }
2587 }
2588 }
2589  
2590  
2591 #------------------------------
2592  
2593 =item send_by_sendmail SENDMAILCMD
2594  
2595 =item send_by_sendmail PARAM=>VALUE, ARRAY, HASH...
2596  
2597 I<Instance method.>
2598 Send message via an external "sendmail" program
2599 (this will probably only work out-of-the-box on Unix systems).
2600  
2601 Returns true on success, false or exception on error.
2602  
2603 You can specify the program and all its arguments by giving a single
2604 string, SENDMAILCMD. Nothing fancy is done; the message is simply
2605 piped in.
2606  
2607 However, if your needs are a little more advanced, you can specify
2608 zero or more of the following PARAM/VALUE pairs (or a reference to hash
2609 or array of such arguments as well as any combination thereof); a
2610 Unix-style, taint-safe "sendmail" command will be constructed for you:
2611  
2612 =over 4
2613  
2614 =item Sendmail
2615  
2616 Full path to the program to use.
2617 Default is "/usr/lib/sendmail".
2618  
2619 =item BaseArgs
2620  
2621 Ref to the basic array of arguments we start with.
2622 Default is C<["-t", "-oi", "-oem"]>.
2623  
2624 =item SetSender
2625  
2626 Unless this is I<explicitly> given as false, we attempt to automatically
2627 set the C<-f> argument to the first address that can be extracted from
2628 the "From:" field of the message (if there is one).
2629  
2630 I<What is the -f, and why do we use it?>
2631 Suppose we did I<not> use C<-f>, and you gave an explicit "From:"
2632 field in your message: in this case, the sendmail "envelope" would
2633 indicate the I<real> user your process was running under, as a way
2634 of preventing mail forgery. Using the C<-f> switch causes the sender
2635 to be set in the envelope as well.
2636  
2637 I<So when would I NOT want to use it?>
2638 If sendmail doesn't regard you as a "trusted" user, it will permit
2639 the C<-f> but also add an "X-Authentication-Warning" header to the message
2640 to indicate a forged envelope. To avoid this, you can either
2641 (1) have SetSender be false, or
2642 (2) make yourself a trusted user by adding a C<T> configuration
2643 command to your I<sendmail.cf> file
2644 (e.g.: C<Teryq> if the script is running as user "eryq").
2645  
2646 =item FromSender
2647  
2648 If defined, this is identical to setting SetSender to true,
2649 except that instead of looking at the "From:" field we use
2650 the address given by this option.
2651 Thus:
2652  
2653 FromSender => 'me@myhost.com'
2654  
2655 =back
2656  
2657 After sending, the method last_send_successful() can be used to determine
2658 if the send was succesful or not.
2659  
2660 =cut
2661  
2662  
2663 sub send_by_sendmail {
2664 0 ▶ my $self = shift;
Subroutine send_by_sendmail: not called CC=18 SCAR=58.3
Pod documented
2665 0 my $return;
2666 0 ▶ if ( @_ == 1 and !ref $_[0] ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 1 and not ref $_[0]) { } 0 0 0
Condition0%0/3
@_ == 1 and not ref $_[0]
!ll&&!rl&&r
000
MC/DC0%0/2
@_ == 1 and not ref $_[0]
@_ == 1 not ref $_[0]
Truth table0%0/3
A and not(B)
A= @_ == 1B= not ref $_[0]
ABresult
0X0
100
111
2667 ### Use the given command...
2668 0 my $sendmailcmd = shift @_;
2669  
2670 ### Do it:
2671 0 local *SENDMAIL;
2672 0 ▶ open SENDMAIL, "|$sendmailcmd" or Carp::croak "open |$sendmailcmd: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
open SENDMAIL, "|$sendmailcmd" or Carp::croak("open |${sendmailcmd}: $!\n") 0 0 0
2673 0 $self->print( \*SENDMAIL );
2674 0 close SENDMAIL;
2675 0 ▶ $return = ( ( $? >> 8 ) ? undef: 1 );
Branch: 1 branch
BranchTrueFalseTotal
$? >> 8 ? : 0 0 0
2676 } else { ### Build the command...
2677 my %p =
2678 0 ▶ map { UNIVERAL::isa( $_, 'ARRAY' ) ? @$_ : UNIVERAL::isa( $_, 'HASH' ) ? %$_ : $_ } @_;
Branch: 2 branches
BranchTrueFalseTotal
UNIVERAL::isa($_, 'ARRAY') ? : 0 0 0
UNIVERAL::isa($_, 'HASH') ? : 0 0 0
2679  
2680 0 ▶ $p{Sendmail} = $SENDMAIL unless defined $p{Sendmail};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $p{"Sendmail"} 0 0 0
2681  
2682 ### Start with the command and basic args:
2683 0 ▶ my @cmd = ( $p{Sendmail}, @{ $p{BaseArgs} || [ '-t', '-oi', '-oem' ] } );
Branch: 1 branch
BranchTrueFalseTotal
$p{"BaseArgs"} or ["-t", "-oi", "-oem"] 0 0 0
2684  
2685 ### See if we are forcibly setting the sender:
2686 0 ▶ $p{SetSender} ||= defined( $p{FromSender} );
Condition0%0/3
$p{"SetSender"} ||= defined $p{"FromSender"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$p{"SetSender"} ||= defined $p{"FromSender"}
$p{"SetSender"} defined $p{"FromSender"}
Truth table0%0/3
A ||= B
A= $p{"SetSender"}B= defined $p{"FromSender"}
ABresult
1X1
011
000
2687  
2688 ### Add the -f argument, unless we're explicitly told NOT to:
2689 0 ▶ if ( $p{SetSender} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($p{"SetSender"}) 0 0 0
2690 0 ▶ my $from = $p{FromSender} || ( $self->get('From') )[0];
Condition0%0/3
$p{'FromSender'} || ($self->get('From'))[0]
l!l&&r!l&&!r
000
MC/DC0%0/2
$p{'FromSender'} || ($self->get('From'))[0]
$p{'FromSender'} ($self->get('From'))[0]
Truth table0%0/3
A || B
A= $p{'FromSender'}B= ($self->get('From'))[0]
ABresult
1X1
011
000
2691 0 ▶ if ($from) {
Branch: 1 branch
BranchTrueFalseTotal
if ($from) 0 0 0
2692 0 my ($from_addr) = extract_full_addrs($from);
2693 0 ▶ push @cmd, "-f$from_addr" if $from_addr;
Branch: 1 branch
BranchTrueFalseTotal
if $from_addr 0 0 0
2694 }
2695 }
2696  
2697 ### Open the command in a taint-safe fashion:
2698 0 my $pid = open SENDMAIL, "|-";
2699 0 ▶ defined($pid) or die "open of pipe failed: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
defined $pid or die "open of pipe failed: $!\n" 0 0 0
2700 0 ▶ if ( !$pid ) { ### child
Branch: 1 branch
BranchTrueFalseTotal
if (not $pid) { } 0 0 0
2701 0 ▶ exec(@cmd) or die "can't exec $p{Sendmail}: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
exec @cmd or die qq[can't exec $p{"Sendmail"}: $!\n] 0 0 0
2702 ### NOTREACHED
2703 } else { ### parent
2704 0 $self->print( \*SENDMAIL );
2705 0 ▶ close SENDMAIL || die "error closing $p{Sendmail}: $! (exit $?)\n";
Branch: 1 branch
BranchTrueFalseTotal
close SENDMAIL or die qq[error closing $p{"Sendmail"}: $! (exit $?)\n] 0 0 0
2706 0 $return = 1;
2707 }
2708 }
2709 0 return $self->{last_send_successful} = $return;
2710 }
2711  
2712 #------------------------------
2713  
2714 =item send_by_smtp HOST, ARGS...
2715  
2716 =item send_by_smtp REF, HOST, ARGS
2717  
2718 I<Instance method.>
2719 Send message via SMTP, using Net::SMTP.
2720  
2721 HOST is the name of SMTP server to connect to, or undef to have
2722 L<Net::SMTP|Net::SMTP> use the defaults in Libnet.cfg.
2723  
2724 ARGS are a list of key value pairs which may be selected from the list
2725 below. Many of these are just passed through to specific
2726 L<Net::SMTP|Net::SMTP> commands and you should review that module for
2727 details.
2728  
2729 Please see L<Good-vs-bad email addresses with send_by_smtp()|/Good-vs-bad email addresses with send_by_smtp()>
2730  
2731 =over 4
2732  
2733 =item Hello
2734  
2735 =item LocalAddr
2736  
2737 =item LocalPort
2738  
2739 =item Timeout
2740  
2741 =item ExactAddresses
2742  
2743 =item Debug
2744  
2745 See L<Net::SMTP::new()|Net::SMTP/"mail"> for details.
2746  
2747 =item Size
2748  
2749 =item Return
2750  
2751 =item Bits
2752  
2753 =item Transaction
2754  
2755 =item Envelope
2756  
2757 See L<Net::SMTP::mail()|Net::SMTP/mail> for details.
2758  
2759 =item SkipBad
2760  
2761 If true doesnt throw an error when multiple email addresses are provided
2762 and some are not valid. See L<Net::SMTP::recipient()|Net::SMTP/recipient>
2763 for details.
2764  
2765 =item AuthUser
2766  
2767 Authenticate with L<Net::SMTP::auth()|Net::SMTP/auth> using this username.
2768  
2769 =item AuthPass
2770  
2771 Authenticate with L<Net::SMTP::auth()|Net::SMTP/auth> using this password.
2772  
2773 =item NoAuth
2774  
2775 Normally if AuthUser and AuthPass are defined MIME::Lite will attempt to
2776 use them with the L<Net::SMTP::auth()|Net::SMTP/auth> command to
2777 authenticate the connection, however if this value is true then no
2778 authentication occurs.
2779  
2780 =item To
2781  
2782 Sets the addresses to send to. Can be a string or a reference to an
2783 array of strings. Normally this is extracted from the To: (and Cc: and
2784 Bcc: fields if $AUTO_CC is true).
2785  
2786 This value overrides that.
2787  
2788 =item From
2789  
2790 Sets the email address to send from. Normally this value is extracted
2791 from the Return-Path: or From: field of the mail itself (in that order).
2792  
2793 This value overides that.
2794  
2795 =back
2796  
2797 I<Returns:>
2798 True on success, croaks with an error message on failure.
2799  
2800 After sending, the method last_send_successful() can be used to determine
2801 if the send was succesful or not.
2802  
2803 =cut
2804  
2805  
2806 # Derived from work by Andrew McRae. Version 0.2 anm 09Sep97
2807 # Copyright 1997 Optimation New Zealand Ltd.
2808 # May be modified/redistributed under the same terms as Perl.
2809  
2810 # external opts
2811 6 my @_mail_opts = qw( Size Return Bits Transaction Envelope );
2812 6 my @_recip_opts = qw( SkipBad );
2813 6 my @_net_smtp_opts = qw( Hello LocalAddr LocalPort Timeout
2814 ExactAddresses Debug );
2815 # internal: qw( NoAuth AuthUser AuthPass To From Host);
2816  
2817 sub __opts {
2818 0 ▶ my $args=shift;
Subroutine __opts: not called CC=2 SCAR=17.9
2819 0 ▶ return map { exists $args->{$_} ? ( $_ => $args->{$_} ) : () } @_;
Branch: 1 branch
BranchTrueFalseTotal
exists $args->{$_} ? : 0 0 0
2820 }
2821  
2822 sub send_by_smtp {
2823 0 ▶ require Net::SMTP;
Subroutine send_by_smtp: not called CC=20 SCAR=60.4
Pod documented
2824 0 my ($self,$hostname,%args) = @_;
2825 # We may need the "From:" and "To:" headers to pass to the
2826 # SMTP mailer also.
2827 0 $self->{last_send_successful}=0;
2828  
2829 0 my @hdr_to = extract_only_addrs( scalar $self->get('To') );
2830 0 ▶ if ($AUTO_CC) {
Branch: 1 branch
BranchTrueFalseTotal
if ($MIME::Lite::AUTO_CC) 0 0 0
2831 0 foreach my $field (qw(Cc Bcc)) {
2832 0 my $value = $self->get($field);
2833 0 ▶ push @hdr_to, extract_only_addrs($value)
Branch: 1 branch
BranchTrueFalseTotal
if defined $value 0 0 0
2834 if defined($value);
2835 }
2836 }
2837 0 ▶ Carp::croak "send_by_smtp: nobody to send to for host '$hostname'?!\n"
Branch: 1 branch
BranchTrueFalseTotal
unless @hdr_to 0 0 0
2838 unless @hdr_to;
2839  
2840 0 ▶ $args{To} ||= \@hdr_to;
Condition0%0/2
$args{"To"} ||= \@hdr_to
l!l
00
MC/DC0%0/1
$args{"To"} ||= \@hdr_to
$args{"To"}
Truth table0%0/2
A
A= $args{"To"}
Aresult
11
00
2841 0 ▶ $args{From} ||= extract_only_addrs( scalar $self->get('Return-Path') );
Condition0%0/3
$args{"From"} ||= extract_only_addrs(scalar $self->get("Return-Path"))
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{"From"} ||= extract_only_addrs(scalar $self->get("Return-Path"))
$args{"From"} extract_only_addrs(scalar $self->get("Return-Path"))
Truth table0%0/3
A ||= B
A= $args{"From"}B= extract_only_addrs(scalar $self->get("Return-Path"))
ABresult
1X1
011
000
2842 0 ▶ $args{From} ||= extract_only_addrs( scalar $self->get('From') ) ;
Condition0%0/3
$args{"From"} ||= extract_only_addrs(scalar $self->get("From"))
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{"From"} ||= extract_only_addrs(scalar $self->get("From"))
$args{"From"} extract_only_addrs(scalar $self->get("From"))
Truth table0%0/3
A ||= B
A= $args{"From"}B= extract_only_addrs(scalar $self->get("From"))
ABresult
1X1
011
000
2843  
2844 # Create SMTP client.
2845 # MIME::Lite::SMTP is just a wrapper giving a print method
2846 # to the SMTP object.
2847  
2848 0 my %opts = __opts(\%args, @_net_smtp_opts);
2849 0 ▶ my $smtp = MIME::Lite::SMTP->new( $hostname, %opts )
Branch: 1 branch
BranchTrueFalseTotal
my $smtp = "MIME::Lite::SMTP"->new($hostname, %opts) or Carp::croak("SMTP Failed to connect to mail server: $!\n") 0 0 0
2850 or Carp::croak "SMTP Failed to connect to mail server: $!\n";
2851  
2852 # Possibly authenticate
2853 0 ▶ if ( defined $args{AuthUser} and defined $args{AuthPass}
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"AuthUser"} and defined $args{"AuthPass"} and not $args{"NoAuth"}) 0 0 0
Condition0%0/6
defined $args{"AuthUser"} and defined $args{"AuthPass"} and not $args{"NoAuth"}
!ll&&!rl&&r
000
defined $args{"AuthUser"} and defined $args{"AuthPass"}
!ll&&!rl&&r
000
MC/DC0%0/3
defined $args{"AuthUser"} and defined $args{"AuthPass"} and not $args{"NoAuth"}
defined $args{"AuthUser"} defined $args{"AuthPass"} not $args{"NoAuth"}
Truth table0%0/4
A and B and not(C)
A= defined $args{"AuthUser"}B= defined $args{"AuthPass"}C= not $args{"NoAuth"}
ABCresult
0XX0
10X0
1100
1111
2854 and !$args{NoAuth} )
2855 {
2856 0 ▶ if ($smtp->supports('AUTH',500,["Command unknown: 'AUTH'"])) {
Branch: 1 branch
BranchTrueFalseTotal
if ($smtp->supports('AUTH', 500, [q[Command unknown: 'AUTH']])) { } 0 0 0
2857 $smtp->auth( $args{AuthUser}, $args{AuthPass} )
2858 0 ▶ or die "SMTP auth() command failed: $!\n"
Branch: 1 branch
BranchTrueFalseTotal
$smtp->auth($args{"AuthUser"}, $args{"AuthPass"}) or die "SMTP auth() command failed: $!\n" . $smtp->message . "\n" 0 0 0
2859 . $smtp->message . "\n";
2860 } else {
2861 0 die "SMTP auth() command not supported on $hostname\n";
2862 }
2863 }
2864  
2865 # Send the mail command
2866 0 %opts = __opts( \%args, @_mail_opts);
2867 0 ▶ $smtp->mail( $args{From}, %opts ? \%opts : () )
Branch: 2 branches
BranchTrueFalseTotal
$smtp->mail($args{"From"}, %opts ? \%opts : ()) or die "SMTP mail() command failed: $!\n" . $smtp->message . "\n" 0 0 0
%opts ? : 0 0 0
2868 or die "SMTP mail() command failed: $!\n"
2869 . $smtp->message . "\n";
2870  
2871 # Send the recipients command
2872 0 %opts = __opts( \%args, @_recip_opts);
2873 0 ▶ $smtp->recipient( @{ $args{To} }, %opts ? \%opts : () )
Branch: 2 branches
BranchTrueFalseTotal
$smtp->recipient(@{$args{"To"};}, %opts ? \%opts : ()) or die "SMTP recipient() command failed: $!\n" . $smtp->message . "\n" 0 0 0
%opts ? : 0 0 0
2874 or die "SMTP recipient() command failed: $!\n"
2875 . $smtp->message . "\n";
2876  
2877 # Send the data
2878 0 ▶ $smtp->data()
Branch: 1 branch
BranchTrueFalseTotal
$smtp->data or die "SMTP data() command failed: $!\n" . $smtp->message . "\n" 0 0 0
2879 or die "SMTP data() command failed: $!\n"
2880 . $smtp->message . "\n";
2881 0 $self->print_for_smtp($smtp);
2882  
2883 # Finish the mail
2884 0 ▶ $smtp->dataend()
Branch: 1 branch
BranchTrueFalseTotal
$smtp->dataend or Carp::croak("Net::CMD (Net::SMTP) DATAEND command failed.\nLast server message was:" . $smtp->message . 'This probably represents a problem with newline encoding ') 0 0 0
2885 or Carp::croak "Net::CMD (Net::SMTP) DATAEND command failed.\n"
2886 . "Last server message was:"
2887 . $smtp->message
2888 . "This probably represents a problem with newline encoding ";
2889  
2890 # terminate the session
2891 0 $smtp->quit;
2892  
2893 0 return $self->{last_send_successful} = 1;
2894 }
2895  
2896 =item last_send_successful
2897  
2898 This method will return TRUE if the last send() or send_by_XXX() method call was
2899 successful. It will return defined but false if it was not successful, and undefined
2900 if the object had not been used to send yet.
2901  
2902 =cut
2903  
2904  
2905 sub last_send_successful {
2906 0 ▶ my $self = shift;
Subroutine last_send_successful: not called CC=1 SCAR=6.9
Pod documented
2907 0 return $self->{last_send_successful};
2908 }
2909  
2910  
2911 ### Provided by Andrew McRae. Version 0.2 anm 09Sep97
2912 ### Copyright 1997 Optimation New Zealand Ltd.
2913 ### May be modified/redistributed under the same terms as Perl.
2914 ### Aditional changes by Yves.
2915 ### Until 3.01_03 this was send_by_smtp()
2916 sub send_by_smtp_simple {
2917 0 ▶ my ( $self, @args ) = @_;
Subroutine send_by_smtp_simple: not called CC=11 SCAR=48.8
Pod undocumented
2918 0 $self->{last_send_successful} = 0;
2919 ### We need the "From:" and "To:" headers to pass to the SMTP mailer:
2920 0 my $hdr = $self->fields();
2921  
2922 0 my $from_header = $self->get('From');
2923 0 my ($from) = extract_only_addrs($from_header);
2924  
2925 0 ▶ warn "M::L>>> $from_header => $from" if $MIME::Lite::DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $MIME::Lite::DEBUG 0 0 0
2926  
2927  
2928 0 my $to = $self->get('To');
2929  
2930 ### Sanity check:
2931 0 ▶ defined($to)
Branch: 1 branch
BranchTrueFalseTotal
defined $to or Carp::croak("send_by_smtp: missing 'To:' address\n") 0 0 0
2932 or Carp::croak "send_by_smtp: missing 'To:' address\n";
2933  
2934 ### Get the destinations as a simple array of addresses:
2935 0 my @to_all = extract_only_addrs($to);
2936 0 ▶ if ($AUTO_CC) {
Branch: 1 branch
BranchTrueFalseTotal
if ($MIME::Lite::AUTO_CC) 0 0 0
2937 0 foreach my $field (qw(Cc Bcc)) {
2938 0 my $value = $self->get($field);
2939 0 ▶ push @to_all, extract_only_addrs($value)
Branch: 1 branch
BranchTrueFalseTotal
if defined $value 0 0 0
2940 if defined($value);
2941 }
2942 }
2943  
2944 ### Create SMTP client:
2945 0 require Net::SMTP;
2946 0 ▶ my $smtp = MIME::Lite::SMTP->new(@args)
Branch: 1 branch
BranchTrueFalseTotal
my $smtp = "MIME::Lite::SMTP"->new(@args) or Carp::croak("Failed to connect to mail server: $!\n") 0 0 0
2947 or Carp::croak("Failed to connect to mail server: $!\n");
2948 0 ▶ $smtp->mail($from)
Branch: 1 branch
BranchTrueFalseTotal
$smtp->mail($from) or Carp::croak("SMTP MAIL command failed: $!\n" . $smtp->message . "\n") 0 0 0
2949 or Carp::croak( "SMTP MAIL command failed: $!\n" . $smtp->message . "\n" );
2950 0 ▶ $smtp->to(@to_all)
Branch: 1 branch
BranchTrueFalseTotal
$smtp->to(@to_all) or Carp::croak("SMTP RCPT command failed: $!\n" . $smtp->message . "\n") 0 0 0
2951 or Carp::croak( "SMTP RCPT command failed: $!\n" . $smtp->message . "\n" );
2952 0 ▶ $smtp->data()
Branch: 1 branch
BranchTrueFalseTotal
$smtp->data or Carp::croak("SMTP DATA command failed: $!\n" . $smtp->message . "\n") 0 0 0
2953 or Carp::croak( "SMTP DATA command failed: $!\n" . $smtp->message . "\n" );
2954  
2955 ### MIME::Lite can print() to anything with a print() method:
2956 0 $self->print_for_smtp($smtp);
2957  
2958 0 ▶ $smtp->dataend()
Branch: 1 branch
BranchTrueFalseTotal
$smtp->dataend or Carp::croak("Net::CMD (Net::SMTP) DATAEND command failed.\nLast server message was:" . $smtp->message . 'This probably represents a problem with newline encoding ') 0 0 0
2959 or Carp::croak( "Net::CMD (Net::SMTP) DATAEND command failed.\n"
2960 . "Last server message was:"
2961 . $smtp->message
2962 . "This probably represents a problem with newline encoding " );
2963 0 $smtp->quit;
2964 0 $self->{last_send_successful} = 1;
2965 0 1;
2966 }
2967  
2968 #------------------------------
2969 #
2970 # send_by_sub [\&SUBREF, [ARGS...]]
2971 #
2972 # I<Instance method, private.>
2973 # Send the message via an anonymous subroutine.
2974 #
2975 sub send_by_sub {
2976 0 ▶ my ( $self, $subref, @args ) = @_;
Subroutine send_by_sub: not called CC=1 SCAR=6.9
Pod undocumented
2977 0 $self->{last_send_successful} = &$subref( $self, @args );
2978  
2979 }
2980  
2981 #------------------------------
2982  
2983 =item sendmail COMMAND...
2984  
2985 I<Class method, DEPRECATED.>
2986 Declare the sender to be "sendmail", and set up the "sendmail" command.
2987 I<You should use send() instead.>
2988  
2989 =cut
2990  
2991  
2992 sub sendmail {
2993 0 ▶ my $self = shift;
Subroutine sendmail: not called CC=1 SCAR=6.9
Pod documented
2994 0 $self->send( 'sendmail', join( ' ', @_ ) );
2995 }
2996  
2997 =back
2998  
2999 =cut
3000  
3001  
3002 #==============================
3003 #==============================
3004  
3005 =head2 Miscellaneous
3006  
3007 =over 4
3008  
3009 =cut
3010  
3011  
3012 #------------------------------
3013  
3014 =item quiet ONOFF
3015  
3016 I<Class method.>
3017 Suppress/unsuppress all warnings coming from this module.
3018  
3019 MIME::Lite->quiet(1); ### I know what I'm doing
3020  
3021 I recommend that you include that comment as well. And while
3022 you type it, say it out loud: if it doesn't feel right, then maybe
3023 you should reconsider the whole line. C<;-)>
3024  
3025 =cut
3026  
3027  
3028 sub quiet {
3029 0 ▶ my $class = shift;
Subroutine quiet: not called CC=2 SCAR=17.9
Pod documented
3030 0 ▶ $QUIET = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 0 0
3031 0 $QUIET;
3032 }
3033  
3034 =back
3035  
3036 =cut
3037  
3038  
3039 #============================================================
3040  
3041 package MIME::Lite::SMTP;
3042  
3043 #============================================================
3044 # This class just adds a print() method to Net::SMTP.
3045 # Notice that we don't use/require it until it's needed!
3046  
3047 6 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3048 6 ▶use vars qw( @ISA );
Subroutine BEGIN: called CC=1 SCAR=0.0
3049 6 @ISA = qw(Net::SMTP);
3050  
3051 # some of the below is borrowed from Data::Dumper
3052 6 my %esc = ( "\a" => "\\a",
3053 "\b" => "\\b",
3054 "\t" => "\\t",
3055 "\n" => "\\n",
3056 "\f" => "\\f",
3057 "\r" => "\\r",
3058 "\e" => "\\e",
3059 );
3060  
3061 sub _hexify {
3062 0 ▶ local $_ = shift;
Subroutine _hexify: not called CC=2 SCAR=17.9
3063 0 my @split = m/(.{1,16})/gs;
3064 0 foreach my $split (@split) {
3065 0 ( my $txt = $split ) =~ s/([\a\b\t\n\f\r\e])/$esc{$1}/sg;
3066 0 $split =~ s/(.)/sprintf("%02X ",ord($1))/sge;
3067 0 print STDERR "M::L >>> $split : $txt\n";
3068 }
3069 }
3070  
3071 sub print {
3072 0 ▶ my $smtp = shift;
Subroutine print: not called CC=3 SCAR=24.8
3073 0 ▶ $MIME::Lite::DEBUG and _hexify( join( "", @_ ) );
Branch: 1 branch
BranchTrueFalseTotal
$MIME::Lite::DEBUG and _hexify(join("", @_)) 0 0 0
3074 0 ▶ $smtp->datasend(@_)
Branch: 1 branch
BranchTrueFalseTotal
$smtp->datasend(@_) or Carp::croak("Net::CMD (Net::SMTP) DATASEND command failed.\nLast server message was:" . $smtp->message . 'This probably represents a problem with newline encoding ') 0 0 0
3075 or Carp::croak( "Net::CMD (Net::SMTP) DATASEND command failed.\n"
3076 . "Last server message was:"
3077 . $smtp->message
3078 . "This probably represents a problem with newline encoding " );
3079 }
3080  
3081  
3082 #============================================================
3083  
3084 package MIME::Lite::IO_Handle;
3085  
3086 #============================================================
3087  
3088 ### Wrap a non-object filehandle inside a blessed, printable interface:
3089 ### Does nothing if the given $fh is already a blessed object.
3090 sub wrap {
3091 42 ▶ my ( $class, $fh ) = @_;
Subroutine wrap: called CC=5 SCAR=18.1
3092 6 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
3093  
3094 ### Get default, if necessary:
3095 42 ▶ $fh or $fh = select; ### no filehandle means selected one
Branch: 1 branch
BranchTrueFalseTotal
$fh or $fh = select 0 42 42
3096 42 ▶ ref($fh) or $fh = \*$fh; ### scalar becomes a globref
Branch: 1 branch
BranchTrueFalseTotal
ref $fh or $fh = \*$fh 0 42 42
3097  
3098 ### Stop right away if already a printable object:
3099 42 ▶ return $fh if ( ref($fh) and ( ref($fh) ne 'GLOB' ) );
Branch: 1 branch
BranchTrueFalseTotal
if ref $fh and ref $fh ne "GLOB" 42 0 42
Condition33%1/3
ref $fh and ref $fh ne "GLOB"
!ll&&!rl&&r
0042
MC/DC0%0/2
ref $fh and ref $fh ne "GLOB"
ref $fh ref $fh ne "GLOB"
Truth table33%1/3
A and B
A= ref $fhB= ref $fh ne "GLOB"
ABresult
0X0
100
111
3100  
3101 ### Get and return a printable interface:
3102 0 bless \$fh, $class; ### wrap it in a printable interface
3103 }
3104  
3105 ### Print:
3106 sub print {
3107 0 ▶ my $self = shift;
Subroutine print: not called CC=1 SCAR=6.9
3108 0 print {$$self} @_;
3109 }
3110  
3111  
3112 #============================================================
3113  
3114 package MIME::Lite::IO_Scalar;
3115  
3116 #============================================================
3117  
3118 ### Wrap a scalar inside a blessed, printable interface:
3119 sub wrap {
3120 6 ▶ my ( $class, $scalarref ) = @_;
Subroutine wrap: called CC=2 SCAR=7.1
3121 6 ▶ defined($scalarref) or $scalarref = \"";
Branch: 1 branch
BranchTrueFalseTotal
defined $scalarref or $scalarref = \"" 0 6 6
3122 6 bless $scalarref, $class;
3123 }
3124  
3125 ### Print:
3126 sub print {
3127 43 ▶ ${$_[0]} .= join( '', @_[1..$#_] );
Subroutine print: called CC=1 SCAR=0.0
3128 43 1;
3129 }
3130  
3131  
3132 #============================================================
3133  
3134 package MIME::Lite::IO_ScalarArray;
3135  
3136 #============================================================
3137  
3138 ### Wrap an array inside a blessed, printable interface:
3139 sub wrap {
3140 0 ▶ my ( $class, $arrayref ) = @_;
Subroutine wrap: not called CC=2 SCAR=17.9
3141 0 ▶ defined($arrayref) or $arrayref = [];
Branch: 1 branch
BranchTrueFalseTotal
defined $arrayref or $arrayref = [] 0 0 0
3142 0 bless $arrayref, $class;
3143 }
3144  
3145 ### Print:
3146 sub print {
3147 0 ▶ my $self = shift;
Subroutine print: not called CC=1 SCAR=6.9
3148 0 push @$self, @_;
3149 0 1;
3150 }
3151  
3152 6 1;
3153 __END__
↑ Summary blib/lib/MIME/Lite.pm »