]>
git.ipfire.org Git - ipfire-2.x.git/blob - config/nettraffic/sendEmail_nettraffic
2 ##############################################################################
4 ## Written by: Brandon Zehm <caspian@dotconf.net>
7 ## sendEmail (hereafter referred to as "program") is free software;
8 ## you can redistribute it and/or modify it under the terms of the GNU General
9 ## Public License as published by the Free Software Foundation; either version
10 ## 2 of the License, or (at your option) any later version.
11 ## When redistributing modified versions of this source code it is recommended
12 ## that that this disclaimer and the above coder's names are included in the
16 ## This program is provided with no warranty of any kind, either expressed or
17 ## implied. It is the responsibility of the user (you) to fully research and
18 ## comprehend the usage of this program. As with any tool, it can be misused,
19 ## either intentionally (you're a vandal) or unintentionally (you're a moron).
20 ## THE AUTHOR(S) IS(ARE) NOT RESPONSIBLE FOR ANYTHING YOU DO WITH THIS PROGRAM
21 ## or anything that happens because of your use (or misuse) of this program,
22 ## including but not limited to anything you, your lawyers, or anyone else
23 ## can dream up. And now, a relevant quote directly from the GPL:
27 ## 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
28 ## FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
29 ## OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
30 ## PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
31 ## OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
32 ## MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
33 ## TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
34 ## PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
35 ## REPAIR OR CORRECTION.
37 ##############################################################################
42 ########################
43 ## Global Variables ##
44 ########################
48 "programName" => $0 , ## The name of this program
49 "version" => '1.54' , ## The version of this program
50 "authorName" => 'Brandon Zehm' , ## Author's Name
51 "authorEmail" => 'caspian @dotconf .net' , ## Author's Email Address
52 "timezone" => '+0000 (GMT)' , ## We always use +0000 for the time zone
53 "hostname" => 'localhost' , ## Used in printmsg() for all output, and in SMTP EHLO.
54 "debug" => 0 , ## Default debug level
55 "error" => '' , ## Error messages will often be stored here
59 "logging" => 0 , ## If this is true the printmsg function prints to the log file
60 "logFile" => '' , ## If this is specified (form the command line via -l) this file will be used for logging.
63 "server" => 'localhost' , ## Default SMTP server
64 "port" => 25 , ## Default port
65 "alarm" => '' , ## Default timeout for connects and reads, this gets set from $opt{'timeout'}
66 "tls_client" => 0 , ## If TLS is supported by the client (us)
67 "tls_server" => 0 , ## If TLS is supported by the remote SMTP server
70 "delimiter" => "----MIME delimiter for sendEmail-" ## MIME Delimiter
71 . rand ( 1000000 ), ## Add some randomness to the delimiter
72 "Message-ID" => rand ( 1000000 ) . "-sendEmail" , ## Message-ID for email header
77 ## This hash stores the options passed on the command line via the -o option.
80 "reply-to" => '' , ## Reply-To field
83 "message-file" => '' , ## File to read message body from
84 "message-header" => '' , ## Additional email header line(s)
85 "message-format" => 'normal' , ## If "raw" is specified the message is sent unmodified
86 "message-charset" => 'iso-8859-1' , ## Message character-set
89 "timeout" => 60 , ## Default timeout for connects and reads, this is copied to $conf{'alarm'} later.
92 "username" => '' , ## Username used in SMTP Auth
93 "password" => '' , ## Password used in SMTP Auth
94 "tls" => 'auto' , ## Enable or disable TLS support. Options: auto, yes, no
98 ## More variables used later in the program
100 my $CRLF = " \015\012 " ;
108 my @attachments = ();
109 my @attachments_names = ();
111 ## For printing colors to the console
112 my ${ colorRed
} = " \033 [31;1m" ;
113 my ${ colorGreen
} = " \033 [32;1m" ;
114 my ${ colorCyan
} = " \033 [36;1m" ;
115 my ${ colorWhite
} = " \033 [37;1m" ;
116 my ${ colorNormal
} = " \033 [m" ;
117 my ${ colorBold
} = " \033 [1m" ;
118 my ${ colorNoBold
} = " \033 [0m" ;
120 ## Don't use shell escape codes on Windows systems
122 ${ colorRed
} = "" ; ${ colorGreen
} = "" ; ${ colorCyan
} = "" ;
123 ${ colorWhite
} = "" ; ${ colorNormal
} = "" ; ${ colorBold
} = "" ; ${ colorNoBold
} = "" ;
126 ## Load IO::Socket::SSL if it's available
127 eval { require IO
:: Socket
:: SSL
; };
128 if ($ @
) { $conf { 'tls_client' } = 0 ; }
129 else { $conf { 'tls_client' } = 1 ; }
141 #############################
145 #############################
151 ###############################################################################################
152 ## Function: initialize ()
154 ## Does all the script startup jibberish.
156 ###############################################################################################
159 ## Set STDOUT to flush immediatly after each print
163 $SIG { 'QUIT' } = sub { quit
( "EXITING: Received SIG $_ [0]" , 1 ); };
164 $SIG { 'INT' } = sub { quit
( "EXITING: Received SIG $_ [0]" , 1 ); };
165 $SIG { 'KILL' } = sub { quit
( "EXITING: Received SIG $_ [0]" , 1 ); };
166 $SIG { 'TERM' } = sub { quit
( "EXITING: Received SIG $_ [0]" , 1 ); };
168 ## ALARM and HUP signals are not supported in Win32
169 unless ($^ O
=~ /win/i ) {
170 $SIG { 'HUP' } = sub { quit
( "EXITING: Received SIG $_ [0]" , 1 ); };
171 $SIG { 'ALRM' } = sub { quit
( "EXITING: Received SIG $_ [0]" , 1 ); };
174 ## Fixup $conf{'programName'}
175 $conf { 'programName' } =~ s/(.)*[\/,\\]/ /;
176 $0 = $conf { 'programName' } . " " . join ( " " , @ARGV );
178 ## Fixup $conf{'hostname'}
179 if ( $conf { 'hostname' } eq 'localhost' ) {
180 $conf { 'hostname' } = "" ;
182 if ( $ENV { 'HOSTNAME' }) {
183 $conf { 'hostname' } = lc ( $ENV { 'HOSTNAME' });
185 elsif ( $ENV { 'COMPUTERNAME' }) {
186 $conf { 'hostname' } = lc ( $ENV { 'COMPUTERNAME' });
189 ## Try the hostname module
191 $conf { 'hostname' } = lc ( hostname
());
194 ## Assign a name of "localhost" if it can't find anything else.
195 if (! $conf { 'hostname' }) {
196 $conf { 'hostname' } = 'localhost' ;
199 $conf { 'hostname' } =~ s/\..*$// ; ## Remove domain name if it's present
219 ###############################################################################################
220 ## Function: processCommandLine ()
222 ## Processes command line storing important data in global vars (usually %conf)
224 ###############################################################################################
225 sub processCommandLine
{
228 ############################
229 ## Process command line ##
230 ############################
232 my @ARGS = @ARGV ; ## This is so later we can re-parse the command line args later if we need to
234 help
() unless ( $numargv );
237 for ( $counter = 0 ; $counter < $numargv ; $counter ++) {
239 if ( $ARGS [ $counter ] =~ /^-h$/i ) { ## Help ##
243 elsif ( $ARGS [ $counter ] eq "" ) { ## Ignore null arguments
247 elsif ( $ARGS [ $counter ] =~ /^--help/ ) { ## Topical Help ##
249 if ( $ARGS [ $counter ] && $ARGS [ $counter ] !~ /^-/ ) {
250 helpTopic
( $ARGS [ $counter ]);
257 elsif ( $ARGS [ $counter ] =~ /^-o$/i ) { ## Options specified with -o ##
259 ## Loop through each option passed after the -o
260 while ( $ARGS [ $counter ] && $ARGS [ $counter ] !~ /^-/ ) {
262 if ( $ARGS [ $counter ] !~ /(\S+)=(\S.*)/ ) {
263 printmsg
( "WARNING => Name/Value pair [ $ARGS [ $counter ]] is not properly formatted" , 0 );
264 printmsg
( "WARNING => Arguments proceeding -o should be in the form of \" name=value \" " , 0 );
267 if ( exists ( $opt { $1 })) {
268 if ( $1 eq 'message-header' ) {
269 $opt { $1 } .= $2 . $CRLF ;
274 printmsg
( "DEBUG => Assigned \ $opt {} key/value: $1 => $2 " , 3 );
277 printmsg
( "WARNING => Name/Value pair [ $ARGS [ $counter ]] will be ignored: unknown key [ $1 ]" , 0 );
278 printmsg
( "HINT => Try the --help option to find valid command line arguments" , 1 );
285 elsif ( $ARGS [ $counter ] =~ /^-f$/ ) { ## From ##
287 if ( $ARGS [ $counter ] && $ARGS [ $counter ] !~ /^-/ ) { $from = $ARGS [ $counter ]; }
288 else { printmsg
( "WARNING => The argument after -f was not an email address!" , 0 ); $counter --; }
291 elsif ( $ARGS [ $counter ] =~ /^-t$/ ) { ## To ##
293 while ( $ARGS [ $counter ] && ( $ARGS [ $counter ] !~ /^-/ )) {
294 if ( $ARGS [ $counter ] =~ /[;,]/ ) {
295 push ( @to , split ( /[;,]/ , $ARGS [ $counter ]));
298 push ( @to , $ARGS [ $counter ]);
304 elsif ( $ARGS [ $counter ] =~ /^-cc$/ ) { ## Cc ##
306 while ( $ARGS [ $counter ] && ( $ARGS [ $counter ] !~ /^-/ )) {
307 if ( $ARGS [ $counter ] =~ /[;,]/ ) {
308 push ( @cc , split ( /[;,]/ , $ARGS [ $counter ]));
311 push ( @cc , $ARGS [ $counter ]);
317 elsif ( $ARGS [ $counter ] =~ /^-bcc$/ ) { ## Bcc ##
319 while ( $ARGS [ $counter ] && ( $ARGS [ $counter ] !~ /^-/ )) {
320 if ( $ARGS [ $counter ] =~ /[;,]/ ) {
321 push ( @bcc , split ( /[;,]/ , $ARGS [ $counter ]));
324 push ( @bcc , $ARGS [ $counter ]);
330 elsif ( $ARGS [ $counter ] =~ /^-m$/ ) { ## Message ##
333 while ( $ARGS [ $counter ] && $ARGS [ $counter ] !~ /^-/ ) {
334 if ( $message ) { $message .= " " ; }
335 $message .= $ARGS [ $counter ];
339 ## Replace '\n' with $CRLF.
340 ## This allows newlines with messages sent on the command line
341 $message =~ s/\\n/$CRLF/g ;
344 elsif ( $ARGS [ $counter ] =~ /^-u$/ ) { ## Subject ##
347 while ( $ARGS [ $counter ] && $ARGS [ $counter ] !~ /^-/ ) {
348 if ( $subject ) { $subject .= " " ; }
349 $subject .= $ARGS [ $counter ];
354 elsif ( $ARGS [ $counter ] =~ /^-s$/ ) { ## Server ##
356 if ( $ARGS [ $counter ] && $ARGS [ $counter ] !~ /^-/ ) {
357 $conf { 'server' } = $ARGS [ $counter ];
358 if ( $conf { 'server' } =~ /:/ ) { ## Port ##
359 ( $conf { 'server' }, $conf { 'port' }) = split ( ":" , $conf { 'server' });
362 else { printmsg
( "WARNING - The argument after -s was not the server!" , 0 ); $counter --; }
365 elsif ( $ARGS [ $counter ] =~ /^-a$/ ) { ## Attachments ##
367 while ( $ARGS [ $counter ] && ( $ARGS [ $counter ] !~ /^-/ )) {
368 push ( @attachments , $ARGS [ $counter ]);
373 elsif ( $ARGS [ $counter ] =~ /^-xu$/ ) { ## AuthSMTP Username ##
375 if ( $ARGS [ $counter ] && $ARGS [ $counter ] !~ /^-/ ) {
376 $opt { 'username' } = $ARGS [ $counter ];
379 printmsg
( "WARNING => The argument after -xu was not valid username!" , 0 );
384 elsif ( $ARGS [ $counter ] =~ /^-xp$/ ) { ## AuthSMTP Password ##
386 if ( $ARGS [ $counter ] && $ARGS [ $counter ] !~ /^-/ ) {
387 $opt { 'password' } = $ARGS [ $counter ];
390 printmsg
( "WARNING => The argument after -xp was not valid password!" , 0 );
395 elsif ( $ARGS [ $counter ] =~ /^-l$/ ) { ## Logging ##
397 $conf { 'logging' } = 1 ;
398 if ( $ARGS [ $counter ] && $ARGS [ $counter ] !~ /^-/ ) { $conf { 'logFile' } = $ARGS [ $counter ]; }
399 else { printmsg
( "WARNING - The argument after -l was not the log file!" , 0 ); $counter --; }
402 elsif ( $ARGS [ $counter ] =~ s/^-v+//i ) { ## Verbosity ##
403 my $tmp = ( length ($&) - 1 );
404 $conf { 'debug' } += $tmp ;
407 elsif ( $ARGS [ $counter ] =~ /^-q$/ ) { ## Quiet ##
412 printmsg
( "Error: \" $ARGS [ $counter ] \" is not a recognized option!" , 0 );
425 ###################################################
426 ## Verify required variables are set correctly ##
427 ###################################################
429 if (! $conf { 'server' }) {
430 $conf { 'server' } = 'localhost' ;
432 if (! $conf { 'port' }) {
436 quit
( "ERROR => You must specify a 'from' field! Try --help." , 1 );
438 if ( (( scalar ( @to )) + ( scalar ( @cc )) + ( scalar ( @bcc ))) <= 0 ) {
439 quit
( "ERROR => You must specify at least one recipient via -t, -cc, or -bcc" , 1 );
442 ## Make sure email addresses look OK.
443 foreach my $addr ( @to , @cc , @bcc , $from , $opt { 'reply-to' }) {
445 if (! returnAddressParts
( $addr )) {
446 printmsg
( "ERROR => Can't use improperly formatted email address: $addr " , 0 );
447 printmsg
( "HINT => Try viewing the extended help on addressing with \" --help addressing \" " , 1 );
453 ## Make sure all attachments exist.
454 foreach my $file ( @attachments ) {
455 if ( (! - f
$file ) or (! - r
$file ) ) {
456 printmsg
( "ERROR => The attachment [ $file ] doesn't exist!" , 0 );
457 printmsg
( "HINT => Try specifying the full path to the file or reading extended help with \" --help message \" " , 1 );
462 if ( $conf { 'logging' } and (! $conf { 'logFile' })) {
463 quit
( "ERROR => You used -l to enable logging but didn't specify a log file!" , 1 );
466 if ( $opt { 'username' } ) {
467 if (! $opt { 'password' }) {
468 ## Prompt for a password since one wasn't specified with the -xp option.
469 $SIG { 'ALRM' } = sub { quit
( "ERROR => Timeout waiting for password inpupt" , 1 ); };
470 alarm ( 60 ) if ($^ O
!~ /win/i ); ## alarm() doesn't work in win32
472 $opt { 'password' } = < STDIN
>; chomp $opt { 'password' };
473 if (! $opt { 'password' }) {
474 quit
( "ERROR => A username for SMTP authentication was specified, but no password!" , 1 );
479 ## Validate the TLS setting
480 $opt { 'tls' } = lc ( $opt { 'tls' });
481 if ( $opt { 'tls' } !~ /^(auto|yes|no)$/ ) {
482 quit
( "ERROR => Invalid TLS setting ( $opt {'tls'}). Must be one of auto, yes, or no." , 1 );
485 ## If TLS is set to "yes", make sure sendEmail loaded the libraries needed.
486 if ( $opt { 'tls' } eq 'yes' and $conf { 'tls_client' } == 0 ) {
487 quit
( "ERROR => No TLS support! SendEmail can't load required libraries. (try installing Net::SSLeay and IO::Socket::SSL)" , 1 );
509 ## getline($socketRef)
511 my ( $socketRef ) = @_ ;
513 return $ $socketRef -> getline ;
519 ## Receive a (multiline?) SMTP response from ($socketRef)
521 my ( $socketRef ) = @_ ;
524 return undef unless defined ( $tmp = getline
( $socketRef ));
525 return ( "getResponse() socket is not open" ) unless ($ $socketRef -> opened );
526 ## Keep reading lines if it's a multi-line response
527 while ( $tmp =~ /^\d{3}-/o ) {
529 return undef unless defined ( $tmp = getline
( $socketRef ));
532 $reply =~ s/\r?\n$//o ;
539 ###############################################################################################
540 ## Function: SMTPchat ( [string $command] )
542 ## Description: Sends $command to the SMTP server (on SERVER) and awaits a successful
543 ## reply form the server. If the server returns an error, or does not reply
544 ## within $conf{'alarm'} seconds an error is generated.
545 ## NOTE: $command is optional, if no command is specified then nothing will
546 ## be sent to the server, but a valid response is still required from the server.
548 ## Input: [$command] A (optional) valid SMTP command (ex. "HELO")
551 ## Output: Returns zero on success, or non-zero on error.
552 ## Error messages will be stored in $conf{'error'}
553 ## A copy of the last SMTP response is stored in the global variable
554 ## $conf{'SMTPchat_response'}
557 ## Example: SMTPchat ("HELO mail.isp.net");
558 ###############################################################################################
562 printmsg
( "INFO => Sending: \t $command " , 1 ) if ( $command );
565 print $SERVER " $command $CRLF " if ( $command );
567 ## Read a response from the server
568 $SIG { 'ALRM' } = sub { $conf { 'error' } = "alarm" ; $SERVER -> close (); };
569 alarm ( $conf { 'alarm' }) if ($^ O
!~ /win/i ); ## alarm() doesn't work in win32;
570 my $result = $conf { 'SMTPchat_response' } = getResponse
( \
$SERVER );
571 alarm ( 0 ) if ($^ O
!~ /win/i ); ## alarm() doesn't work in win32;
573 ## Generate an alert if we timed out
574 if ( $conf { 'error' } eq "alarm" ) {
575 $conf { 'error' } = "ERROR => Timeout while reading from $conf {'server'}: $conf {'port'} There was no response after $conf {'alarm'} seconds." ;
579 ## Make sure the server actually responded
581 $conf { 'error' } = "ERROR => $conf {'server'}: $conf {'port'} returned a zero byte response to our query." ;
585 ## Validate the response
586 if ( evalSMTPresponse
( $result )) {
587 ## conf{'error'} will already be set here
591 ## Print the success messsage
592 printmsg
( $conf { 'error' }, 1 );
609 ###############################################################################################
610 ## Function: evalSMTPresponse (string $message )
612 ## Description: Searches $message for either an SMTP success or error code, and returns
613 ## 0 on success, and the actual error code on error.
616 ## Input: $message Data received from a SMTP server (ex. "220
619 ## Output: Returns zero on success, or non-zero on error.
620 ## Error messages will be stored in $conf{'error'}
623 ## Example: SMTPchat ("HELO mail.isp.net");
624 ###############################################################################################
625 sub evalSMTPresponse
{
630 $conf { 'error' } = "ERROR => No message was passed to evalSMTPresponse(). What happened?" ;
634 printmsg
( "DEBUG => evalSMTPresponse() - Checking for SMTP success or error status in the message: $message " , 3 );
636 ## Look for a SMTP success code
637 if ( $message =~ /^([23]\d\d)/ ) {
638 printmsg
( "DEBUG => evalSMTPresponse() - Found SMTP success code: $1 " , 2 );
639 $conf { 'error' } = "SUCCESS => Received: \t $message " ;
643 ## Look for a SMTP error code
644 if ( $message =~ /^([45]\d\d)/ ) {
645 printmsg
( "DEBUG => evalSMTPresponse() - Found SMTP error code: $1 " , 2 );
646 $conf { 'error' } = "ERROR => Received: \t $message " ;
650 ## If no SMTP codes were found return an error of 1
651 $conf { 'error' } = "ERROR => Received a message with no success or error code. The message received was: $message " ;
665 #########################################################
666 # SUB: &return_month(0,1,etc)
667 # returns the name of the month that corrosponds
668 # with the number. returns 0 on error.
669 #########################################################
672 if ( $x == 0 ) { return 'Jan' ; }
673 if ( $x == 1 ) { return 'Feb' ; }
674 if ( $x == 2 ) { return 'Mar' ; }
675 if ( $x == 3 ) { return 'Apr' ; }
676 if ( $x == 4 ) { return 'May' ; }
677 if ( $x == 5 ) { return 'Jun' ; }
678 if ( $x == 6 ) { return 'Jul' ; }
679 if ( $x == 7 ) { return 'Aug' ; }
680 if ( $x == 8 ) { return 'Sep' ; }
681 if ( $x == 9 ) { return 'Oct' ; }
682 if ( $x == 10 ) { return 'Nov' ; }
683 if ( $x == 11 ) { return 'Dec' ; }
702 #########################################################
703 # SUB: &return_day(0,1,etc)
704 # returns the name of the day that corrosponds
705 # with the number. returns 0 on error.
706 #########################################################
709 if ( $x == 0 ) { return 'Sun' ; }
710 if ( $x == 1 ) { return 'Mon' ; }
711 if ( $x == 2 ) { return 'Tue' ; }
712 if ( $x == 3 ) { return 'Wed' ; }
713 if ( $x == 4 ) { return 'Thu' ; }
714 if ( $x == 5 ) { return 'Fri' ; }
715 if ( $x == 6 ) { return 'Sat' ; }
734 ###############################################################################################
735 ## Function: returnAddressParts(string $address)
737 ## Description: Returns a two element array containing the "Name" and "Address" parts of
740 ## Example: "Brandon Zehm <caspian@dotconf.net>"
741 ## would return: ("Brandon Zehm", "caspian@dotconf.net");
743 ## "caspian@dotconf.net"
744 ## would return: ("caspian@dotconf.net", "caspian@dotconf.net")
745 ###############################################################################################
746 sub returnAddressParts
{
751 ## Make sure to fail if it looks totally invalid
752 if ( $input !~ /(\S+\@\S+)/ ) {
753 $conf { 'error' } = "ERROR => The address [ $input ] doesn't look like a valid email address, ignoring it" ;
757 ## Check 1, should find addresses like: "Brandon Zehm <caspian@dotconf.net>"
758 elsif ( $input =~ /^\s*(\S(.*\S)?)\s*<(\S+\@\S+)>/o ) {
759 ( $name , $address ) = ( $1 , $3 );
762 ## Otherwise if that failed, just get the address: <caspian@dotconf.net>
763 elsif ( $input =~ /<(\S+\@\S+)>/o ) {
764 $name = $address = $1 ;
767 ## Or maybe it was formatted this way: caspian@dotconf.net
768 elsif ( $input =~ /(\S+\@\S+)/o ) {
769 $name = $address = $1 ;
772 ## Something stupid happened, just return an error.
773 unless ( $name and $address ) {
774 printmsg
( "ERROR => Couldn't parse the address: $input " , 0 );
775 printmsg
( "HINT => If you think this should work, consider reporting this as a bug to $conf {'authorEmail'}" , 1 );
779 ## Make sure there aren't invalid characters in the address, and return it.
780 my $ctrl = ' \000 - \037 ' ;
781 my $nonASCII = ' \x80 - \xff ' ;
782 if ( $address =~ /[<> ,;:"'\[\]\\$ctrl$nonASCII]/ ) {
783 printmsg
( "WARNING => The address [ $address ] seems to contain invalid characters: continuing anyway" , 0 );
785 return ( $name , $address );
803 ###############################################################################################
804 ## Function: base64_encode(string $data)
806 ## Description: Returns $data as a base64 encoded string
807 ## If the encoded data is returned in 76 character long lines with the final
809 ###############################################################################################
816 ###################################
817 ## Convert binary data to base64 ##
818 ###################################
819 while ( $data =~ s/(.{45})//s ) { ## Get 45 bytes from the binary string
820 $tmp = substr ( pack ( 'u' , $&), 1 ); ## Convert the binary to uuencoded text
822 $tmp =~ tr
| ` -_|AA-Za-z0-9+/|; ## Translate from uuencode to base64
826 ###################################
827 ## Encode and send the leftovers ##
828 ###################################
830 if ( ( $data ) and (length( $data ) >= 1) ) {
831 $padding = (3 - length( $data ) % 3) % 3; ## Set flag if binary data isn't divisible by 3
832 $tmp = substr(pack('u', $data ), 1); ## Convert the binary to uuencoded text
834 $tmp =~ tr|` - _
| AA
- Za
- z0
- 9 +/|; ## Translate from uuencode to base64
838 ############################
839 ## Fix padding at the end ##
840 ############################
842 $base64 =~ s/.{$padding}$/'=' x $padding/e if $padding ; ## Fix the end padding if flag (from above) is set
843 while ( $base64 =~ s/(.{1,76})//s ) { ## Put $CRLF after each 76 characters
859 #########################################################
860 # SUB: send_attachment("/path/filename")
861 # Sends the mime headers and base64 encoded file
862 # to the email server.
863 #########################################################
864 sub send_attachment
{
865 my ( $filename ) = @_ ; ## Get filename passed
866 my ( @fields , $y , $filename_name , $encoding , ## Local variables
867 @attachlines , $content_type );
870 @fields = split ( /\/ | \\ /, $filename ); ## Get the actual filename without the path
871 $filename_name = pop ( @fields );
872 push @attachments_names , $filename_name ; ## FIXME: This is only used later for putting in the log file
874 ##########################
875 ## Autodetect Mime Type ##
876 ##########################
878 @fields = split ( /\./ , $filename_name );
879 $encoding = $fields [ $#fields ];
881 if ( $encoding =~ /txt|text|log|conf|^c$|cpp|^h$|inc|m3u/i ) { $content_type = 'text/plain' ; }
882 elsif ( $encoding =~ /html|htm|shtml|shtm|asp|php|cfm/i ) { $content_type = 'text/html' ; }
883 elsif ( $encoding =~ /sh$/i ) { $content_type = 'application/x-sh' ; }
884 elsif ( $encoding =~ /tcl/i ) { $content_type = 'application/x-tcl' ; }
885 elsif ( $encoding =~ /pl$/i ) { $content_type = 'application/x-perl' ; }
886 elsif ( $encoding =~ /js$/i ) { $content_type = 'application/x-javascript' ; }
887 elsif ( $encoding =~ /man/i ) { $content_type = 'application/x-troff-man' ; }
888 elsif ( $encoding =~ /gif/i ) { $content_type = 'image/gif' ; }
889 elsif ( $encoding =~ /jpg|jpeg|jpe|jfif|pjpeg|pjp/i ) { $content_type = 'image/jpeg' ; }
890 elsif ( $encoding =~ /tif|tiff/i ) { $content_type = 'image/tiff' ; }
891 elsif ( $encoding =~ /xpm/i ) { $content_type = 'image/x-xpixmap' ; }
892 elsif ( $encoding =~ /bmp/i ) { $content_type = 'image/x-MS-bmp' ; }
893 elsif ( $encoding =~ /pcd/i ) { $content_type = 'image/x-photo-cd' ; }
894 elsif ( $encoding =~ /png/i ) { $content_type = 'image/png' ; }
895 elsif ( $encoding =~ /aif|aiff/i ) { $content_type = 'audio/x-aiff' ; }
896 elsif ( $encoding =~ /wav/i ) { $content_type = 'audio/x-wav' ; }
897 elsif ( $encoding =~ /mp2|mp3|mpa/i ) { $content_type = 'audio/x-mpeg' ; }
898 elsif ( $encoding =~ /ra$|ram/i ) { $content_type = 'audio/x-pn-realaudio' ; }
899 elsif ( $encoding =~ /mpeg|mpg/i ) { $content_type = 'video/mpeg' ; }
900 elsif ( $encoding =~ /mov|qt$/i ) { $content_type = 'video/quicktime' ; }
901 elsif ( $encoding =~ /avi/i ) { $content_type = 'video/x-msvideo' ; }
902 elsif ( $encoding =~ /zip/i ) { $content_type = 'application/x-zip-compressed' ; }
903 elsif ( $encoding =~ /tar/i ) { $content_type = 'application/x-tar' ; }
904 elsif ( $encoding =~ /jar/i ) { $content_type = 'application/java-archive' ; }
905 elsif ( $encoding =~ /exe|bin/i ) { $content_type = 'application/octet-stream' ; }
906 elsif ( $encoding =~ /ppt|pot|ppa|pps|pwz/i ) { $content_type = 'application/vnd.ms-powerpoint' ; }
907 elsif ( $encoding =~ /mdb|mda|mde/i ) { $content_type = 'application/vnd.ms-access' ; }
908 elsif ( $encoding =~ /xls|xlt|xlm|xld|xla|xlc|xlw|xll/i ) { $content_type = 'application/vnd.ms-excel' ; }
909 elsif ( $encoding =~ /doc|dot/i ) { $content_type = 'application/msword' ; }
910 elsif ( $encoding =~ /rtf/i ) { $content_type = 'application/rtf' ; }
911 elsif ( $encoding =~ /pdf/i ) { $content_type = 'application/pdf' ; }
912 elsif ( $encoding =~ /tex/i ) { $content_type = 'application/x-tex' ; }
913 elsif ( $encoding =~ /latex/i ) { $content_type = 'application/x-latex' ; }
914 elsif ( $encoding =~ /vcf/i ) { $content_type = 'application/x-vcard' ; }
915 else { $content_type = 'application/octet-stream' ; }
918 ############################
919 ## Process the attachment ##
920 ############################
922 #####################################
923 ## Generate and print MIME headers ##
924 #####################################
926 $y = " $CRLF -- $conf {'delimiter'} $CRLF " ;
927 $y .= "Content-Type: $content_type ; $CRLF " ;
928 $y .= " name= \" $filename_name \" $CRLF " ;
929 $y .= "Content-Transfer-Encoding: base64 $CRLF " ;
930 $y .= "Content-Disposition: attachment; filename= \" $filename_name \" $CRLF " ;
935 ###########################################################
936 ## Convert the file to base64 and print it to the server ##
937 ###########################################################
939 open ( FILETOATTACH
, $filename ) || do {
940 printmsg
( "ERROR => Opening the file [ $filename ] for attachment failed with the error: $!" , 0 );
943 binmode ( FILETOATTACH
); ## Hack to make Win32 work
948 while (< FILETOATTACH
>) { ## Read a line from the (binary) file
951 ###################################
952 ## Convert binary data to base64 ##
953 ###################################
954 while ( $res =~ s/(.{45})//s ) { ## Get 45 bytes from the binary string
955 $tmp = substr ( pack ( 'u' , $&), 1 ); ## Convert the binary to uuencoded text
957 $tmp =~ tr
| ` -_|AA-Za-z0-9+/|; ## Translate from uuencode to base64
961 ################################
962 ## Print chunks to the server ##
963 ################################
964 while ( $base64 =~ s/(.{76})//s) {
965 print $SERVER " $1 $CRLF ";
970 ###################################
971 ## Encode and send the leftovers ##
972 ###################################
974 if ( ( $res ) and (length( $res ) >= 1) ) {
975 $padding = (3 - length( $res ) % 3) % 3; ## Set flag if binary data isn't divisible by 3
976 $res = substr(pack('u', $res ), 1); ## Convert the binary to uuencoded text
978 $res =~ tr|` - _
| AA
- Za
- z0
- 9 +/|; ## Translate from uuencode to base64
981 ############################
982 ## Fix padding at the end ##
983 ############################
984 $res = $base64 . $res ; ## Get left overs from above
985 $res =~ s/.{$padding}$/'=' x $padding/e if $padding ; ## Fix the end padding if flag (from above) is set
987 while ( $res =~ s/(.{1,76})//s ) { ## Send it to the email server.
988 print $SERVER " $1 $CRLF " ;
992 close ( FILETOATTACH
) || do {
993 printmsg
( "ERROR - Closing the filehandle for file [ $filename ] failed with the error: $!" , 0 );
1010 ###############################################################################################
1011 ## Function: printmsg (string $message, int $level)
1013 ## Description: Handles all messages - printing them to the screen only if the messages
1014 ## $level is >= the global debug level. If $conf{'logFile'} is defined it
1015 ## will also log the message to that file.
1017 ## Input: $message A message to be printed, logged, etc.
1018 ## $level The debug level of the message. If
1019 ## not defined 0 will be assumed. 0 is
1020 ## considered a normal message, 1 and
1021 ## higher is considered a debug message.
1023 ## Output: Prints to STDOUT
1025 ## Assumptions: $conf{'hostname'} should be the name of the computer we're running on.
1026 ## $conf{'stdout'} should be set to 1 if you want to print to stdout
1027 ## $conf{'logFile'} should be a full path to a log file if you want that
1028 ## $conf{'syslog'} should be 1 if you want to syslog, the syslog() function
1029 ## written by Brandon Zehm should be present.
1030 ## $conf{'debug'} should be an integer between 0 and 10.
1032 ## Example: printmsg("WARNING: We believe in generic error messages... NOT!", 0);
1033 ###############################################################################################
1035 ## Assign incoming parameters to variables
1036 my ( $message , $level ) = @_ ;
1038 ## Make sure input is sane
1039 $level = 0 if (! defined ( $level ));
1040 $message =~ s/\s+$//sgo ;
1041 $message =~ s/\r?\n/, /sgo ;
1043 ## Continue only if the debug level of the program is >= message debug level.
1044 if ( $conf { 'debug' } >= $level ) {
1046 ## Get the date in the format: Dec 3 11:14:04
1047 my ( $sec , $min , $hour , $mday , $mon ) = localtime ();
1048 $mon = ( 'Jan' , 'Feb' , 'Mar' , 'Apr' , 'May' , 'Jun' , 'Jul' , 'Aug' , 'Sep' , 'Oct' , 'Nov' , 'Dec' )[ $mon ];
1049 my $date = sprintf ( " %s %02d %02d : %02d : %02d " , $mon , $mday , $hour , $min , $sec );
1051 ## Print to STDOUT always if debugging is enabled, or if conf{stdout} is true.
1052 if ( ( $conf { 'debug' } >= 1 ) or ( $conf { 'stdout' } == 1 ) ) {
1053 print " $date $conf {'hostname'} $conf {'programName'}\[$$\]: $message \n " ;
1056 ## Print to the log file if $conf{'logging'} is true
1057 if ( $conf { 'logFile' }) {
1058 if ( openLogFile
( $conf { 'logFile' })) { $conf { 'logFile' } = "" ; printmsg
( "ERROR => Opening the file [ $conf {'logFile'}] for appending returned the error: $!" , 1 ); }
1059 print LOGFILE
" $date $conf {'hostname'} $conf {'programName'}\[$$\]: $message \n " ;
1079 ###############################################################################################
1081 ## openLogFile ( $filename )
1085 ## Opens the file $filename and attaches it to the filehandle "LOGFILE". Returns 0 on success
1086 ## and non-zero on failure. Error codes are listed below, and the error message gets set in
1087 ## global variable $!.
1091 ## openFile ("/var/log/sendEmail.log");
1093 ###############################################################################################
1095 ## Get the incoming filename
1096 my $filename = $_ [ 0 ];
1098 ## Make sure our file exists, and if the file doesn't exist then create it
1099 if ( ! - f
$filename ) {
1100 print STDERR
"NOTICE: The log file [ $filename ] does not exist. Creating it now with mode [0600]. \n " if ( $conf { 'stdout' });
1101 open ( LOGFILE
, ">> $filename " );
1103 chmod ( 0600 , $filename );
1106 ## Now open the file and attach it to a filehandle
1107 open ( LOGFILE
, ">> $filename " ) or return ( 1 );
1109 ## Put the file into non-buffering mode
1125 ###############################################################################################
1126 ## Function: read_file (string $filename)
1128 ## Description: Reads the contents of a file and returns a two part array:
1129 ## ($status, $file-contents)
1130 ## $status is 0 on success, non-zero on error.
1132 ## Example: ($status, $file) = read_file)("/etc/passwd");
1133 ###############################################################################################
1135 my ( $filename ) = @_ ;
1137 ## If the value specified is a file, load the file's contents
1138 if ( (- e
$filename and - r
$filename ) ) {
1140 if (! open ( $FILE , ' ' . $filename )) {
1147 ## Strip an ending \r\n
1148 $file =~ s/\r?\n$//os ;
1161 ###############################################################################################
1162 ## Function: quit (string $message, int $errorLevel)
1164 ## Description: Exits the program, optionally printing $message. It
1165 ## returns an exit error level of $errorLevel to the
1166 ## system (0 means no errors, and is assumed if empty.)
1168 ## Example: quit("Exiting program normally", 0);
1169 ###############################################################################################
1171 my ( $message , $errorLevel ) = @_ ;
1172 $errorLevel = 0 if (! defined ( $errorLevel ));
1174 ## Print exit message
1176 printmsg
( $message , 0 );
1194 ###############################################################################################
1195 ## Function: help ()
1197 ## Description: For all those newbies ;)
1198 ## Prints a help message and exits the program.
1200 ###############################################################################################
1202 exit ( 1 ) if (! $conf { 'stdout' });
1205 ${colorBold} $conf {'programName'}- $conf {'version'} by $conf {'authorName'} < $conf {'authorEmail'}>${colorNoBold}
1207 Synopsis: $conf {'programName'} -f ADDRESS [options]
1209 ${colorRed}Required:${colorNormal}
1210 -f ADDRESS from (sender) email address
1211 * At least one recipient required via -t, -cc, or -bcc
1212 * Message body required via -m, STDIN, or -o message-file=FILE
1214 ${colorGreen}Common:${colorNormal}
1215 -t ADDRESS [ADDR ...] to email address(es)
1216 -u SUBJECT message subject
1217 -m MESSAGE message body
1218 -s SERVER[:PORT] smtp mail relay, default is $conf {'server'}: $conf {'port'}
1220 ${colorGreen}Optional:${colorNormal}
1221 -a FILE [FILE ...] file attachment(s)
1222 -cc ADDRESS [ADDR ...] cc email address(es)
1223 -bcc ADDRESS [ADDR ...] bcc email address(es)
1225 ${colorGreen}Paranormal:${colorNormal}
1226 -xu USERNAME username for SMTP authentication
1227 -xp PASSWORD password for SMTP authentication
1228 -l LOGFILE log to the specified file
1229 -v verbosity, use multiple times for greater effect
1230 -q be quiet (i.e. no STDOUT output)
1231 -o NAME=VALUE advanced options, for details try --help TOPIC
1232 -o message-file=FILE -o message-format=raw
1233 -o message-header=HEADER -o message-charset=CHARSET
1234 -o reply-to=ADDRESS -o timeout=SECONDS
1235 -o username=USERNAME -o password=PASSWORD
1236 -o tls=<auto|yes|no>
1238 ${colorGreen}Help:${colorNormal}
1239 --help the helpful overview you're reading now
1240 --help addressing explain addressing and related options
1241 --help message explain message body input and related options
1242 --help networking explain -s, etc
1243 --help output explain logging and other output options
1244 --help misc explain -o options, TLS, SMTP auth, and more
1258 ###############################################################################################
1259 ## Function: helpTopic ($topic)
1261 ## Description: For all those newbies ;)
1262 ## Prints a help message and exits the program.
1264 ###############################################################################################
1266 exit ( 1 ) if (! $conf { 'stdout' });
1275 ( $topic eq 'addressing' ) && do {
1278 ${colorBold}ADDRESSING DOCUMENTATION${colorNormal}
1280 ${colorGreen}Addressing Options${colorNormal}
1281 Options related to addressing:
1283 -t ADDRESS [ADDRESS ...]
1284 -cc ADDRESS [ADDRESS ...]
1285 -bcc ADDRESS [ADDRESS ...]
1289 This required option specifies who the email is from, I.E. the sender's
1292 -t ADDRESS [ADDRESS ...]
1293 This option specifies the primary recipient(s). At least one recipient
1294 address must be specified via the -t, -cc. or -bcc options.
1296 -cc ADDRESS [ADDRESS ...]
1297 This option specifies the "carbon copy" recipient(s). At least one
1298 recipient address must be specified via the -t, -cc. or -bcc options.
1300 -bcc ADDRESS [ADDRESS ...]
1301 This option specifies the "blind carbon copy" recipient(s). At least
1302 one recipient address must be specified via the -t, -cc. or -bcc options.
1305 This option specifies that an optional "Reply-To" address should be
1306 written in the email's headers.
1309 ${colorGreen}Email Address Syntax${colorNormal}
1310 Email addresses may be specified in one of two ways:
1311 Full Name: "John Doe <john.doe\ @gmail .com>"
1312 Just Address: "john.doe\ @gmail .com"
1314 The "Full Name" method is useful if you want a name, rather than a plain
1315 email address, to be displayed in the recipient's From, To, or Cc fields
1316 when they view the message.
1319 ${colorGreen}Multiple Recipients${colorNormal}
1320 The -t, -cc, and -bcc options each accept multiple addresses. They may be
1321 specified by separating them by either a white space, comma, or semi-colon
1322 separated list. You may also specify the -t, -cc, and -bcc options multiple
1323 times, each occurance will append the new recipients to the respective list.
1326 (I used "-t" in these examples, but it can be "-cc" or "-bcc" as well)
1328 * Space separated list:
1329 -t jane.doe\ @yahoo .com "John Doe <john.doe\ @gmail .com>"
1331 * Semi-colon separated list:
1332 -t "jane.doe\ @yahoo .com; John Doe <john.doe\ @gmail .com>"
1334 * Comma separated list:
1335 -t "jane.doe\ @yahoo .com, John Doe <john.doe\ @gmail .com>"
1337 * Multiple -t, -cc, or -bcc options:
1338 -t "jane.doe\ @yahoo .com" -t "John Doe <john.doe\ @gmail .com>"
1351 ( $topic eq 'message' ) && do {
1354 ${colorBold}MESSAGE DOCUMENTATION${colorNormal}
1356 ${colorGreen}Message Options${colorNormal}
1357 Options related to the email message body:
1360 -o message-file=FILE
1361 -o message-header=EMAIL HEADER
1362 -o message-charset=CHARSET
1363 -o message-format=raw
1366 This option allows you to specify the subject for your email message.
1367 It is not required (anymore) that the subject be quoted, although it
1368 is recommended. The subject will be read until an argument starting
1369 with a hyphen (-) is found.
1371 -u "Contact information while on vacation"
1372 -u New Microsoft vulnerability discovered
1375 This option is one of three methods that allow you to specify the message
1376 body for your email. The message may be specified on the command line
1377 with this -m option, read from a file with the -o message-file=FILE
1378 option, or read from STDIN if neither of these options are present.
1380 It is not required (anymore) that the message be quoted, although it is
1381 recommended. The message will be read until an argument starting with a
1382 hyphen (-) is found.
1384 -m "See you in South Beach, Hawaii. -Todd"
1385 -m Please ensure that you upgrade your systems right away
1387 Multi-line message bodies may be specified with the -m option by putting
1388 a " \\ n" into the message. Example:
1389 -m "This is line 1. \\ nAnd this is line 2."
1391 HTML messages are supported, simply begin your message with "<html>" and
1392 sendEmail will properly label the mime header so MUAs properly render
1393 the message. It is currently not possible without "-o message-format=raw"
1394 to send a message with both text and html parts with sendEmail.
1396 -o message-file=FILE
1397 This option is one of three methods that allow you to specify the message
1398 body for your email. To use this option simply specify a text file
1399 containing the body of your email message. Examples:
1400 -o message-file=/root/message.txt
1401 -o message-file="C: \\ Program Files \\ output.txt"
1403 -o message-header=EMAIL HEADER
1404 This option allows you to specify additional email headers to be included.
1405 To add more than one message header simply use this option on the command
1406 line more than once. If you specify a message header that sendEmail would
1407 normally generate the one you specified will be used in it's place.
1408 Do not use this unless you know what you are doing!
1410 To scare a Microsoft Outlook user you may want to try this:
1411 -o message-header="X-Message-Flag: Message contains illegal content"
1413 To request a read-receipt try this:
1414 -o message-header="Disposition-Notification-To: <user\ @domain .com>"
1416 To set the message priority try this:
1417 -o message-header="X-Priority: 1"
1418 Priority reference: 1=highest, 2=high, 3=normal, 4=low, 5=lowest
1420 -o message-charset=CHARSET
1421 This option allows you to specify the character-set for the message body.
1422 The default is iso-8859-1.
1424 -o message-format=raw
1425 This option instructs sendEmail to assume the message (specified with -m,
1426 read from STDIN, or read from the file specified in -o message-file=FILE)
1427 is already a *complete* email message. SendEmail will not generate any
1428 headers and will transmit the message as-is to the remote SMTP server.
1429 Due to the nature of this option the following command line options will
1430 be ignored when this one is used:
1432 -o message-header=EMAIL HEADER
1433 -o message-charset=CHARSET
1437 ${colorGreen}The Message Body${colorNormal}
1438 The email message body may be specified in one of three ways:
1439 1) Via the -m MESSAGE command line option.
1441 -m "This is the message body"
1443 2) By putting the message body in a file and using the -o message-file=FILE
1444 command line option.
1446 -o message-file=/root/message.txt
1448 3) By piping the message body to sendEmail when nither of the above command
1449 line options were specified.
1451 grep "ERROR" /var/log/messages | sendEmail -t you\ @domain .com ...
1453 If the message body begins with "<html>" then the message will be treated as
1454 an HTML message and the MIME headers will be written so that a HTML capable
1455 email client will display the message in it's HTML form.
1456 Any of the above methods may be used with the -o message-format=raw option
1457 to deliver an already complete email message.
1470 ( $topic eq 'misc' ) && do {
1473 ${colorBold}MISC DOCUMENTATION${colorNormal}
1475 ${colorGreen}Misc Options${colorNormal}
1476 Options that don't fit anywhere else:
1477 -a ATTACHMENT [ATTACHMENT ...]
1480 -o username=USERNAME
1481 -o password=PASSWORD
1482 -o tls=<auto|yes|no>
1485 -a ATTACHMENT [ATTACHMENT ...]
1486 This option allows you to attach any number of files to your email message.
1487 To specify more than one attachment, simply separate each filename with a
1488 space. Example: -a file1.txt file2.txt file3.txt
1491 Alias for -o username=USERNAME
1494 Alias for -o password=PASSWORD
1496 -o username=USERNAME (synonym for -xu)
1497 These options allow specification of a username to be used with SMTP
1498 servers that require authentication. If a username is specified but a
1499 password is not, you will be prompted to enter one at runtime.
1501 -o password=PASSWORD (synonym for -xp)
1502 These options allow specification of a password to be used with SMTP
1503 servers that require authentication. If a username is specified but a
1504 password is not, you will be prompted to enter one at runtime.
1506 -o tls=<auto|yes|no>
1507 This option allows you to specify if TLS (SSL for SMTP) should be enabled
1508 or disabled. The default, auto, will use TLS automatically if your perl
1509 installation has the IO::Socket::SSL and Net::SSLeay modules available,
1510 and if the remote SMTP server supports TLS. To require TLS for message
1511 delivery set this to yes. To disable TLS support set this to no. A debug
1512 level of one or higher will reveal details about the status of TLS.
1515 This option sets the timeout value in seconds used for all network reads,
1516 writes, and a few other things.
1528 ( $topic eq 'networking' ) && do {
1531 ${colorBold}NETWORKING DOCUMENTATION${colorNormal}
1533 ${colorGreen}Networking Options${colorNormal}
1534 Options related to networking:
1536 -o tls=<auto|yes|no>
1540 This option allows you to specify the SMTP server sendEmail should
1541 connect to to deliver your email message to. If this option is not
1542 specified sendEmail will try to connect to localhost:25 to deliver
1543 the message. THIS IS MOST LIKELY NOT WHAT YOU WANT, AND WILL LIKELY
1544 FAIL unless you have a email server (commonly known as an MTA) running
1546 Typically you will need to specify your company or ISP's email server.
1547 For example, if you use CableOne you will need to specify:
1548 -s mail.cableone.net
1549 If you have your own email server running on port 300 you would
1550 probably use an option like this:
1551 -s myserver.mydomain.com:300
1553 -o tls=<auto|yes|no>
1554 This option allows you to specify if TLS (SSL for SMTP) should be enabled
1555 or disabled. The default, auto, will use TLS automatically if your perl
1556 installation has the IO::Socket::SSL and Net::SSLeay modules available,
1557 and if the remote SMTP server supports TLS. To require TLS for message
1558 delivery set this to yes. To disable TLS support set this to no. A debug
1559 level of one or higher will reveal details about the status of TLS.
1562 This option sets the timeout value in seconds used for all network reads,
1563 writes, and a few other things.
1576 ( $topic eq 'output' ) && do {
1579 ${colorBold}OUTPUT DOCUMENTATION${colorNormal}
1581 ${colorGreen}Output Options${colorNormal}
1582 Options related to output:
1588 This option allows you to specify a log file to append to. Every message
1589 that is displayed to STDOUT is also written to the log file. This may be
1590 used in conjunction with -q and -v.
1593 This option tells sendEmail to disable printing to STDOUT. In other
1594 words nothing will be printed to the console. This does not affect the
1595 behavior of the -l or -v options.
1598 This option allows you to increase the debug level of sendEmail. You may
1599 either use this option more than once, or specify more than one v at a
1600 time to obtain a debug level higher than one. Examples:
1601 Specifies a debug level of 1: -v
1602 Specifies a debug level of 2: -vv
1603 Specifies a debug level of 2: -v -v
1604 A debug level of one is recommended when doing any sort of debugging.
1605 At that level you will see the entire SMTP transaction (except the
1606 body of the email message), and hints will be displayed for most
1607 warnings and errors. The highest debug level is three.
1614 ## Unknown option selected!
1615 quit
( "ERROR => The help topic specified is not valid!" , 1 );
1642 #############################
1646 #############################
1652 ## Process Command Line
1653 processCommandLine
();
1654 $conf { 'alarm' } = $opt { 'timeout' };
1656 ## Abort program after $conf{'alarm'} seconds to avoid infinite hangs
1657 alarm ( $conf { 'alarm' }) if ($^ O
!~ /win/i ); ## alarm() doesn't work in win32
1662 ###################################################
1663 ## Read $message from STDIN if -m was not used ##
1664 ###################################################
1667 ## Read message body from a file specified with -o message-file=
1668 if ( $opt { 'message-file' }) {
1669 if (! - e
$opt { 'message-file' }) {
1670 printmsg
( "ERROR => Message body file specified [ $opt {'message-file'}] does not exist!" , 0 );
1671 printmsg
( "HINT => 1) check spelling of your file; 2) fully qualify the path; 3) doubble quote it" , 1 );
1674 if (! - r
$opt { 'message-file' }) {
1675 printmsg
( "ERROR => Message body file specified can not be read due to restricted permissions!" , 0 );
1676 printmsg
( "HINT => Check permissions on file specified to ensure it can be read" , 1 );
1679 if (! open ( MFILE
, "< " . $opt { 'message-file' })) {
1680 printmsg
( "ERROR => Error opening message body file [ $opt {'message-file'}]: $!" , 0 );
1689 ## Read message body from STDIN
1691 alarm ( $conf { 'alarm' }) if ($^ O
!~ /win/i ); ## alarm() doesn't work in win32
1692 if ( $conf { 'stdout' }) {
1693 print "Reading message body from STDIN because the '-m' option was not used. \n " ;
1694 print "If you are manually typing in a message: \n " ;
1695 print " - First line must be received within $conf {'alarm'} seconds. \n " if ($^ O
!~ /win/i );
1696 print " - End manual input with a CTRL-D on its own line. \n\n " if ($^ O
!~ /win/i );
1697 print " - End manual input with a CTRL-Z on its own line. \n\n " if ($^ O
=~ /win/i );
1699 while (< STDIN
>) { ## Read STDIN into $message
1701 alarm ( 0 ) if ($^ O
!~ /win/i ); ## Disable the alarm since at least one line was received
1703 printmsg
( "Message input complete." , 0 );
1707 ## Replace bare LF's with CRLF's (\012 should always have \015 with it)
1708 $message =~ s/(\015)?(\012|$)/\015\012/g ;
1710 ## Replace bare CR's with CRLF's (\015 should always have \012 with it)
1711 $message =~ s/(\015)(\012|$)?/\015\012/g ;
1713 ## Check message for bare periods and encode them
1714 $message =~ s/(^|$CRLF)(\.{1})($CRLF|$)/$1.$2$3/g ;
1716 ## Get the current date for the email header
1717 my ( $sec , $min , $hour , $mday , $mon , $year , $day ) = gmtime ();
1718 $year += 1900 ; $mon = return_month
( $mon ); $day = return_day
( $day );
1719 my $date = sprintf ( " %s , %s %s %d %.2d:%.2d:%.2d %s " , $day , $mday , $mon , $year , $hour , $min , $sec , $conf { 'timezone' });
1724 ##################################
1725 ## Connect to the SMTP server ##
1726 ##################################
1727 printmsg
( "DEBUG => Connecting to $conf {'server'}: $conf {'port'}" , 1 );
1728 $SIG { 'ALRM' } = sub {
1729 printmsg
( "ERROR => Timeout while connecting to $conf {'server'}: $conf {'port'} There was no response after $conf {'alarm'} seconds." , 0 );
1730 printmsg
( "HINT => Try specifying a different mail relay with the -s option." , 1 );
1733 alarm ( $conf { 'alarm' }) if ($^ O
!~ /win/i ); ## alarm() doesn't work in win32;
1734 $SERVER = IO
:: Socket
:: INET
-> new ( PeerAddr
=> $conf { 'server' },
1735 PeerPort
=> $conf { 'port' },
1738 timeout
=> $conf { 'alarm' },
1740 alarm ( 0 ) if ($^ O
!~ /win/i ); ## alarm() doesn't work in win32;
1742 ## Make sure we got connected
1743 if ( (! $SERVER ) or (! $SERVER -> opened ()) ) {
1744 printmsg
( "ERROR => Connection attempt to $conf {'server'}: $conf {'port'} failed: $@" , 0 );
1745 printmsg
( "HINT => Try specifying a different mail relay with the -s option." , 1 );
1754 #########################
1755 ## Do the SMTP Dance ##
1756 #########################
1758 ## Read initial greeting to make sure we're talking to a live SMTP server
1759 if ( SMTPchat
()) { quit
( $conf { 'error' }, 1 ); }
1762 if ( SMTPchat
( 'EHLO ' . $conf { 'hostname' })) {
1763 printmsg
( $conf { 'error' }, 0 );
1764 printmsg
( "NOTICE => EHLO command failed, attempting HELO instead" );
1765 if ( SMTPchat
( 'HELO ' . $conf { 'hostname' })) { quit
( $conf { 'error' }, 1 ); }
1766 if ( $opt { 'username' } and $opt { 'password' } ) {
1767 printmsg
( "WARNING => The mail server does not support SMTP authentication!" , 0 );
1772 ## Determin if the server supports TLS
1773 if ( $conf { 'SMTPchat_response' } =~ /STARTTLS/ ) {
1774 $conf { 'tls_server' } = 1 ;
1775 printmsg
( "DEBUG => The remote SMTP server supports TLS :)" , 2 );
1778 $conf { 'tls_server' } = 0 ;
1779 printmsg
( "DEBUG => The remote SMTP server does NOT support TLS :(" , 2 );
1782 ## Start TLS if possible
1783 if ( $conf { 'tls_server' } == 1 and $conf { 'tls_client' } == 1 and $opt { 'tls' } =~ /^(yes|auto)$/ ) {
1784 printmsg
( "DEBUG => Starting TLS" , 2 );
1785 if ( SMTPchat
( 'STARTTLS' )) { quit
( $conf { 'error' }, 1 ); }
1786 if (! IO
:: Socket
:: SSL
-> start_SSL ( $SERVER , SSL_version
=> 'SSLv3 TLSv1' )) {
1787 quit
( "ERROR => TLS setup failed: " . IO
:: Socket
:: SSL
:: errstr
(), 1 );
1789 printmsg
( "DEBUG => TLS: Using cipher: " . $SERVER -> get_cipher (), 3 );
1790 printmsg
( "DEBUG => TLS session initialized :)" , 1 );
1792 ## Restart our SMTP session
1793 if ( SMTPchat
( 'EHLO ' . $conf { 'hostname' })) { quit
( $conf { 'error' }, 1 ); }
1795 elsif ( $opt { 'tls' } eq 'yes' and $conf { 'tls_server' } == 0 ) {
1796 quit
( "ERROR => TLS not possible! Remote SMTP server, $conf {'server'}, does not support it." , 1 );
1800 ## Do SMTP Auth if required
1801 if ( $opt { 'username' } and $opt { 'password' } ) {
1802 if ( $conf { 'SMTPchat_response' } !~ /AUTH\s/ ) {
1803 printmsg
( "NOTICE => Authentication not supported by the remote SMTP server!" , 0 );
1806 # ## SASL CRAM-MD5 authentication method
1807 # if ($conf{'SMTPchat_response'} =~ /\bCRAM-MD5\b/i) {
1808 # printmsg("DEBUG => SMTP-AUTH: Using CRAM-MD5 authentication method", 1);
1809 # if (SMTPchat('AUTH CRAM-MD5')) { quit($conf{'error'}, 1); }
1813 # printmsg("DEBUG => User authentication was successful", 1);
1816 ## SASL PLAIN authentication method
1817 if ( $conf { 'SMTPchat_response' } =~ /\bPLAIN\b/i ) {
1818 printmsg
( "DEBUG => SMTP-AUTH: Using PLAIN authentication method" , 1 );
1819 if ( SMTPchat
( 'AUTH PLAIN ' . base64_encode
( " $opt {'username'}\0 $opt {'username'}\0 $opt {'password'}" ))) { quit
( $conf { 'error' }, 1 ); }
1820 printmsg
( "DEBUG => User authentication was successful" , 1 );
1823 ## SASL LOGIN authentication method
1824 elsif ( $conf { 'SMTPchat_response' } =~ /\bLOGIN\b/i ) {
1825 printmsg
( "DEBUG => SMTP-AUTH: Using LOGIN authentication method" , 1 );
1826 if ( SMTPchat
( 'AUTH LOGIN' )) { quit
( $conf { 'error' }, 1 ); }
1827 if ( SMTPchat
( base64_encode
( $opt { 'username' }))) { quit
( $conf { 'error' }, 1 ); }
1828 if ( SMTPchat
( base64_encode
( $opt { 'password' }))) { quit
( $conf { 'error' }, 1 ); }
1829 printmsg
( "DEBUG => User authentication was successful" , 1 );
1833 printmsg
( "WARNING => SMTP-AUTH: No mutually supported authentication methods available" , 0 );
1840 if ( SMTPchat
( 'MAIL FROM:<' .( returnAddressParts
( $from ))[ 1 ]. '>' )) { quit
( $conf { 'error' }, 1 ); }
1843 my $oneRcptAccepted = 0 ;
1844 foreach my $rcpt ( @to , @cc , @bcc ) {
1845 my ( $name , $address ) = returnAddressParts
( $rcpt );
1846 if ( SMTPchat
( 'RCPT TO:<' . $address . '>' )) {
1847 printmsg
( "WARNING => The recipient < $address > was rejected by the mail server, error follows:" , 0 );
1848 $conf { 'error' } =~ s/^ERROR/WARNING/o ;
1849 printmsg
( $conf { 'error' }, 0 );
1851 elsif ( $oneRcptAccepted == 0 ) {
1852 $oneRcptAccepted = 1 ;
1855 ## If no recipients were accepted we need to exit with an error.
1856 if ( $oneRcptAccepted == 0 ) {
1857 quit
( "ERROR => Exiting. No recipients were accepted for delivery by the mail server." , 1 );
1861 if ( SMTPchat
( 'DATA' )) { quit
( $conf { 'error' }, 1 ); }
1864 ###############################
1865 ## Build and send the body ##
1866 ###############################
1867 printmsg
( "INFO => Sending message body" , 1 );
1869 ## If the message-format is raw just send the message as-is.
1870 if ( $opt { 'message-format' } =~ /^raw$/i ) {
1871 print $SERVER $message ;
1874 ## If the message-format isn't raw, then build and send the message,
1877 ## Message-ID: <MessageID>
1878 if ( $opt { 'message-header' } !~ /^Message-ID:/iom ) {
1879 $header .= 'Message-ID: <' . $conf { 'Message-ID' } . '@' . $conf { 'hostname' } . '>' . $CRLF ;
1882 ## From: "Name" <address@domain.com> (the pointless test below is just to keep scoping correct)
1883 if ( $from and $opt { 'message-header' } !~ /^From:/iom ) {
1884 my ( $name , $address ) = returnAddressParts
( $from );
1885 $header .= 'From: "' . $name . '" <' . $address . '>' . $CRLF ;
1889 if ( $opt { 'reply-to' } and $opt { 'message-header' } !~ /^Reply-To:/iom ) {
1890 my ( $name , $address ) = returnAddressParts
( $opt { 'reply-to' });
1891 $header .= 'Reply-To: "' . $name . '" <' . $address . '>' . $CRLF ;
1894 ## To: "Name" <address@domain.com>
1895 if ( $opt { 'message-header' } =~ /^To:/iom ) {
1896 ## The user put the To: header in via -o message-header - dont do anything
1898 elsif ( scalar ( @to ) > 0 ) {
1900 for ( my $a = 0 ; $a < scalar ( @to ); $a ++) {
1903 my ( $name , $address ) = returnAddressParts
( $to [ $a ]);
1904 $msg = " \" $name \" < $address >" ;
1906 ## If we're not on the last address add a comma to the end of the line.
1907 if (( $a + 1 ) != scalar ( @to )) {
1911 $header .= $msg . $CRLF ;
1914 ## We always want a To: line so if the only recipients were bcc'd they don't see who it was sent to
1916 $header .= "To: \" Undisclosed Recipients \" <> $CRLF " ;
1919 if ( scalar ( @cc ) > 0 and $opt { 'message-header' } !~ /^Cc:/iom ) {
1921 for ( my $a = 0 ; $a < scalar ( @cc ); $a ++) {
1924 my ( $name , $address ) = returnAddressParts
( $cc [ $a ]);
1925 $msg = " \" $name \" < $address >" ;
1927 ## If we're not on the last address add a comma to the end of the line.
1928 if (( $a + 1 ) != scalar ( @cc )) {
1932 $header .= $msg . $CRLF ;
1936 if ( $opt { 'message-header' } !~ /^Subject:/iom ) {
1937 $header .= 'Subject: ' . $subject . $CRLF ; ## Subject
1939 if ( $opt { 'message-header' } !~ /^Date:/iom ) {
1940 $header .= 'Date: ' . $date . $CRLF ; ## Date
1942 if ( $opt { 'message-header' } !~ /^X-Mailer:/iom ) {
1943 $header .= 'X-Mailer: sendEmail-' . $conf { 'version' }. $CRLF ; ## X-Mailer
1946 ## Encode all messages with MIME.
1947 if ( $opt { 'message-header' } !~ /^MIME-Version:/iom ) {
1948 $header .= "MIME-Version: 1.0 $CRLF " ;
1950 if ( $opt { 'message-header' } !~ /^Content-Type:/iom ) {
1951 my $content_type = 'multipart/mixed' ;
1952 if ( scalar ( @attachments ) == 0 ) { $content_type = 'multipart/related' ; }
1953 $header .= "Content-Type: $content_type ; boundary= \" $conf {'delimiter'} \" $CRLF " ;
1956 ## Send additional message header line(s) if specified
1957 if ( $opt { 'message-header' }) {
1958 $header .= $opt { 'message-header' };
1961 ## Send the message header to the server
1962 print $SERVER $header . $CRLF ;
1964 ## Start sending the message body to the server
1965 print $SERVER "This is a multi-part message in MIME format. To properly display this message you need a MIME-Version 1.0 compliant Email program. $CRLF " ;
1966 print $SERVER " $CRLF " ;
1969 ## Send message body
1970 print $SERVER "-- $conf {'delimiter'} $CRLF " ;
1971 ## If the message contains HTML change the Content-Type
1972 if ( $message =~ /^\s*<html>/i ) {
1973 printmsg
( "Message is in HTML format" , 1 );
1974 print $SERVER "Content-Type: text/html; $CRLF " ;
1976 ## Otherwise it's a normal text email
1978 print $SERVER "Content-Type: text/plain; $CRLF " ;
1980 print $SERVER " charset= \" " . $opt { 'message-charset' } . " \" $CRLF " ;
1981 print $SERVER "Content-Transfer-Encoding: 7bit $CRLF " ;
1982 print $SERVER $CRLF . $message ;
1987 if ( scalar ( @attachments ) > 0 ) {
1988 ## Disable the alarm so people on modems can send big attachments
1989 alarm ( 0 ) if ($^ O
!~ /win/i ); ## alarm() doesn't work in win32
1991 ## Send the attachments
1992 foreach my $filename ( @attachments ) {
1993 ## This is check 2, we already checked this above, but just in case...
1994 if ( ! - f
$filename ) {
1995 printmsg
( "ERROR => The file [ $filename ] doesn't exist! Email will be sent, but without that attachment." , 0 );
1997 elsif ( ! - r
$filename ) {
1998 printmsg
( "ERROR => Couldn't open the file [ $filename ] for reading: $! Email will be sent, but without that attachment." , 0 );
2001 printmsg
( "DEBUG => Sending the attachment [ $filename ]" , 1 );
2002 send_attachment
( $filename );
2008 ## End the mime encoded message
2009 print $SERVER " $CRLF -- $conf {'delimiter'}-- $CRLF " ;
2013 ## Tell the server we are done sending the email
2014 print $SERVER " $CRLF . $CRLF " ;
2015 if ( SMTPchat
()) { quit
( $conf { 'error' }, 1 ); }
2019 ####################
2021 ####################
2023 ## Disconnect from the server (don't SMTPchat(), it breaks when using TLS)
2024 print $SERVER "QUIT $CRLF " ;
2032 #######################################
2033 ## Generate exit message/log entry ##
2034 #######################################
2036 if ( $conf { 'debug' } or $conf { 'logging' }) {
2037 printmsg
( "Generating a detailed exit message" , 3 );
2039 ## Put the message together
2040 my $output = "Email was sent successfully! From: <" . ( returnAddressParts
( $from ))[ 1 ] . "> " ;
2042 if ( scalar ( @to ) > 0 ) {
2044 for ( $a = 0 ; $a < scalar ( @to ); $a ++) {
2045 $output .= "<" . ( returnAddressParts
( $to [ $a ]))[ 1 ] . "> " ;
2048 if ( scalar ( @cc ) > 0 ) {
2050 for ( $a = 0 ; $a < scalar ( @cc ); $a ++) {
2051 $output .= "<" . ( returnAddressParts
( $cc [ $a ]))[ 1 ] . "> " ;
2054 if ( scalar ( @bcc ) > 0 ) {
2056 for ( $a = 0 ; $a < scalar ( @bcc ); $a ++) {
2057 $output .= "<" . ( returnAddressParts
( $bcc [ $a ]))[ 1 ] . "> " ;
2060 $output .= "Subject: [ $subject ] " if ( $subject );
2061 if ( scalar ( @attachments_names ) > 0 ) {
2062 $output .= "Attachment(s): " ;
2063 foreach ( @attachments_names ) {
2067 $output .= "Server: [ $conf {'server'}: $conf {'port'}]" ;
2070 ######################
2071 # Exit the program #
2072 ######################
2074 ## Print / Log the detailed message
2078 ## Or the standard message
2079 quit
( "Email was sent successfully!" , 0 );