File Coverage

lib/MIME/Lite.pm
Criterion Covered Total %
statement 361 655 55.1
branch 136 368 36.9
condition 38 107 35.5
subroutine 45 74 60.8
pod 37 54 68.5
total 617 1258 49.0


line stmt bran cond sub pod time code
1             package MIME::Lite;
2 8     8   13056 use strict;
  8         51  
  8         608  
3             require 5.004; ### for /c modifier in m/\G.../gc modifier
4              
5             =head1 NAME
6              
7             MIME::Lite - low-calorie MIME generator
8              
9             =head1 WAIT!
10              
11             MIME::Lite is not recommended by its current maintainer. There are a number of
12             alternatives, like Email::MIME or MIME::Entity and Email::Sender, which you
13             should probably use instead. MIME::Lite continues to accrue weird bug reports,
14             and it is not receiving a large amount of refactoring due to the availability
15             of better alternatives. Please consider using something else.
16              
17             =head1 SYNOPSIS
18              
19             Create and send using the default send method for your OS a single-part message:
20              
21             use MIME::Lite;
22             ### Create a new single-part message, to send a GIF file:
23             $msg = MIME::Lite->new(
24             From => 'me@myhost.com',
25             To => 'you@yourhost.com',
26             Cc => 'some@other.com, some@more.com',
27             Subject => 'Helloooooo, nurse!',
28             Type => 'image/gif',
29             Encoding => 'base64',
30             Path => 'hellonurse.gif'
31             );
32             $msg->send; # send via default
33              
34             Create a multipart message (i.e., one with attachments) and send it via SMTP
35              
36             ### Create a new multipart message:
37             $msg = MIME::Lite->new(
38             From => 'me@myhost.com',
39             To => 'you@yourhost.com',
40             Cc => 'some@other.com, some@more.com',
41             Subject => 'A message with 2 parts...',
42             Type => 'multipart/mixed'
43             );
44              
45             ### Add parts (each "attach" has same arguments as "new"):
46             $msg->attach(
47             Type => 'TEXT',
48             Data => "Here's the GIF file you wanted"
49             );
50             $msg->attach(
51             Type => 'image/gif',
52             Path => 'aaa000123.gif',
53             Filename => 'logo.gif',
54             Disposition => 'attachment'
55             );
56             ### use Net::SMTP to do the sending
57             $msg->send('smtp','some.host', Debug=>1 );
58              
59             Output a message:
60              
61             ### Format as a string:
62             $str = $msg->as_string;
63              
64             ### Print to a filehandle (say, a "sendmail" stream):
65             $msg->print(\*SENDMAIL);
66              
67             Send a message:
68              
69             ### Send in the "best" way (the default is to use "sendmail"):
70             $msg->send;
71             ### Send a specific way:
72             $msg->send('type',@args);
73              
74             Specify default send method:
75              
76             MIME::Lite->send('smtp','some.host',Debug=>0);
77              
78             with authentication
79              
80             MIME::Lite->send('smtp','some.host', AuthUser=>$user, AuthPass=>$pass);
81              
82             using SSL
83              
84             MIME::Lite->send('smtp','some.host', SSL => 1, Port => 465 );
85              
86             =head1 DESCRIPTION
87              
88             In the never-ending quest for great taste with fewer calories,
89             we proudly present: I.
90              
91             MIME::Lite is intended as a simple, standalone module for generating
92             (not parsing!) MIME messages... specifically, it allows you to
93             output a simple, decent single- or multi-part message with text or binary
94             attachments. It does not require that you have the Mail:: or MIME::
95             modules installed, but will work with them if they are.
96              
97             You can specify each message part as either the literal data itself (in
98             a scalar or array), or as a string which can be given to open() to get
99             a readable filehandle (e.g., "
100              
101             You don't need to worry about encoding your message data:
102             this module will do that for you. It handles the 5 standard MIME encodings.
103              
104             =head1 EXAMPLES
105              
106             =head2 Create a simple message containing just text
107              
108             $msg = MIME::Lite->new(
109             From =>'me@myhost.com',
110             To =>'you@yourhost.com',
111             Cc =>'some@other.com, some@more.com',
112             Subject =>'Helloooooo, nurse!',
113             Data =>"How's it goin', eh?"
114             );
115              
116             =head2 Create a simple message containing just an image
117              
118             $msg = MIME::Lite->new(
119             From =>'me@myhost.com',
120             To =>'you@yourhost.com',
121             Cc =>'some@other.com, some@more.com',
122             Subject =>'Helloooooo, nurse!',
123             Type =>'image/gif',
124             Encoding =>'base64',
125             Path =>'hellonurse.gif'
126             );
127              
128              
129             =head2 Create a multipart message
130              
131             ### Create the multipart "container":
132             $msg = MIME::Lite->new(
133             From =>'me@myhost.com',
134             To =>'you@yourhost.com',
135             Cc =>'some@other.com, some@more.com',
136             Subject =>'A message with 2 parts...',
137             Type =>'multipart/mixed'
138             );
139              
140             ### Add the text message part:
141             ### (Note that "attach" has same arguments as "new"):
142             $msg->attach(
143             Type =>'TEXT',
144             Data =>"Here's the GIF file you wanted"
145             );
146              
147             ### Add the image part:
148             $msg->attach(
149             Type =>'image/gif',
150             Path =>'aaa000123.gif',
151             Filename =>'logo.gif',
152             Disposition => 'attachment'
153             );
154              
155              
156             =head2 Attach a GIF to a text message
157              
158             This will create a multipart message exactly as above, but using the
159             "attach to singlepart" hack:
160              
161             ### Start with a simple text message:
162             $msg = MIME::Lite->new(
163             From =>'me@myhost.com',
164             To =>'you@yourhost.com',
165             Cc =>'some@other.com, some@more.com',
166             Subject =>'A message with 2 parts...',
167             Type =>'TEXT',
168             Data =>"Here's the GIF file you wanted"
169             );
170              
171             ### Attach a part... the make the message a multipart automatically:
172             $msg->attach(
173             Type =>'image/gif',
174             Path =>'aaa000123.gif',
175             Filename =>'logo.gif'
176             );
177              
178              
179             =head2 Attach a pre-prepared part to a message
180              
181             ### Create a standalone part:
182             $part = MIME::Lite->new(
183             Top => 0,
184             Type =>'text/html',
185             Data =>'

Hello

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