]> git.ipfire.org Git - people/pmueller/ipfire-2.x.git/blob - config/nettraffic/sendEmail_nettraffic
3447a5568363fc5f5724b9d2e13b22e88602aff5
[people/pmueller/ipfire-2.x.git] / config / nettraffic / sendEmail_nettraffic
1 #!/usr/bin/perl -w
2 ##############################################################################
3 ## sendEmail
4 ## Written by: Brandon Zehm <caspian@dotconf.net>
5 ##
6 ## License:
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
13 ## modified code.
14 ##
15 ## Disclaimer:
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:
24 ##
25 ## NO WARRANTY
26 ##
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.
36 ##
37 ##############################################################################
38 use strict;
39 use IO::Socket;
40
41
42 ########################
43 ## Global Variables ##
44 ########################
45
46 my %conf = (
47 ## General
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
56
57 ## Logging
58 "stdout" => 1,
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.
61
62 ## Network
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
68
69 ## Email
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
73
74 );
75
76
77 ## This hash stores the options passed on the command line via the -o option.
78 my %opt = (
79 ## Addressing
80 "reply-to" => '', ## Reply-To field
81
82 ## Message
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
87
88 ## Network
89 "timeout" => 60, ## Default timeout for connects and reads, this is copied to $conf{'alarm'} later.
90
91 ## eSMTP
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
95
96 );
97
98 ## More variables used later in the program
99 my $SERVER;
100 my $CRLF = "\015\012";
101 my $subject = '';
102 my $header = '';
103 my $message = '';
104 my $from = '';
105 my @to = ();
106 my @cc = ();
107 my @bcc = ();
108 my @attachments = ();
109 my @attachments_names = ();
110
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";
119
120 ## Don't use shell escape codes on Windows systems
121 if ($^O =~ /win/i) {
122 ${colorRed} = ""; ${colorGreen} = ""; ${colorCyan} = "";
123 ${colorWhite} = ""; ${colorNormal} = ""; ${colorBold} = ""; ${colorNoBold} = "";
124 }
125
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; }
130
131
132
133
134
135
136
137
138
139
140
141 #############################
142 ## ##
143 ## FUNCTIONS ##
144 ## ##
145 #############################
146
147
148
149
150
151 ###############################################################################################
152 ## Function: initialize ()
153 ##
154 ## Does all the script startup jibberish.
155 ##
156 ###############################################################################################
157 sub initialize {
158
159 ## Set STDOUT to flush immediatly after each print
160 $| = 1;
161
162 ## Intercept signals
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); };
167
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); };
172 }
173
174 ## Fixup $conf{'programName'}
175 $conf{'programName'} =~ s/(.)*[\/,\\]//;
176 $0 = $conf{'programName'} . " " . join(" ", @ARGV);
177
178 ## Fixup $conf{'hostname'}
179 if ($conf{'hostname'} eq 'localhost') {
180 $conf{'hostname'} = "";
181
182 if ($ENV{'HOSTNAME'}) {
183 $conf{'hostname'} = lc($ENV{'HOSTNAME'});
184 }
185 elsif ($ENV{'COMPUTERNAME'}) {
186 $conf{'hostname'} = lc($ENV{'COMPUTERNAME'});
187 }
188 else {
189 ## Try the hostname module
190 use Sys::Hostname;
191 $conf{'hostname'} = lc(hostname());
192 }
193
194 ## Assign a name of "localhost" if it can't find anything else.
195 if (!$conf{'hostname'}) {
196 $conf{'hostname'} = 'localhost';
197 }
198
199 $conf{'hostname'} =~ s/\..*$//; ## Remove domain name if it's present
200 }
201
202 return(1);
203 }
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219 ###############################################################################################
220 ## Function: processCommandLine ()
221 ##
222 ## Processes command line storing important data in global vars (usually %conf)
223 ##
224 ###############################################################################################
225 sub processCommandLine {
226
227
228 ############################
229 ## Process command line ##
230 ############################
231
232 my @ARGS = @ARGV; ## This is so later we can re-parse the command line args later if we need to
233 my $numargv = @ARGS;
234 help() unless ($numargv);
235 my $counter = 0;
236
237 for ($counter = 0; $counter < $numargv; $counter++) {
238
239 if ($ARGS[$counter] =~ /^-h$/i) { ## Help ##
240 help();
241 }
242
243 elsif ($ARGS[$counter] eq "") { ## Ignore null arguments
244 ## Do nothing
245 }
246
247 elsif ($ARGS[$counter] =~ /^--help/) { ## Topical Help ##
248 $counter++;
249 if ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) {
250 helpTopic($ARGS[$counter]);
251 }
252 else {
253 help();
254 }
255 }
256
257 elsif ($ARGS[$counter] =~ /^-o$/i) { ## Options specified with -o ##
258 $counter++;
259 ## Loop through each option passed after the -o
260 while ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) {
261
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);
265 }
266 else {
267 if (exists($opt{$1})) {
268 if ($1 eq 'message-header') {
269 $opt{$1} .= $2 . $CRLF;
270 }
271 else {
272 $opt{$1} = $2;
273 }
274 printmsg("DEBUG => Assigned \$opt{} key/value: $1 => $2", 3);
275 }
276 else {
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);
279 }
280 }
281 $counter++;
282 } $counter--;
283 }
284
285 elsif ($ARGS[$counter] =~ /^-f$/) { ## From ##
286 $counter++;
287 if ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) { $from = $ARGS[$counter]; }
288 else { printmsg("WARNING => The argument after -f was not an email address!", 0); $counter--; }
289 }
290
291 elsif ($ARGS[$counter] =~ /^-t$/) { ## To ##
292 $counter++;
293 while ($ARGS[$counter] && ($ARGS[$counter] !~ /^-/)) {
294 if ($ARGS[$counter] =~ /[;,]/) {
295 push (@to, split(/[;,]/, $ARGS[$counter]));
296 }
297 else {
298 push (@to,$ARGS[$counter]);
299 }
300 $counter++;
301 } $counter--;
302 }
303
304 elsif ($ARGS[$counter] =~ /^-cc$/) { ## Cc ##
305 $counter++;
306 while ($ARGS[$counter] && ($ARGS[$counter] !~ /^-/)) {
307 if ($ARGS[$counter] =~ /[;,]/) {
308 push (@cc, split(/[;,]/, $ARGS[$counter]));
309 }
310 else {
311 push (@cc,$ARGS[$counter]);
312 }
313 $counter++;
314 } $counter--;
315 }
316
317 elsif ($ARGS[$counter] =~ /^-bcc$/) { ## Bcc ##
318 $counter++;
319 while ($ARGS[$counter] && ($ARGS[$counter] !~ /^-/)) {
320 if ($ARGS[$counter] =~ /[;,]/) {
321 push (@bcc, split(/[;,]/, $ARGS[$counter]));
322 }
323 else {
324 push (@bcc,$ARGS[$counter]);
325 }
326 $counter++;
327 } $counter--;
328 }
329
330 elsif ($ARGS[$counter] =~ /^-m$/) { ## Message ##
331 $counter++;
332 $message = "";
333 while ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) {
334 if ($message) { $message .= " "; }
335 $message .= $ARGS[$counter];
336 $counter++;
337 } $counter--;
338
339 ## Replace '\n' with $CRLF.
340 ## This allows newlines with messages sent on the command line
341 $message =~ s/\\n/$CRLF/g;
342 }
343
344 elsif ($ARGS[$counter] =~ /^-u$/) { ## Subject ##
345 $counter++;
346 $subject = "";
347 while ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) {
348 if ($subject) { $subject .= " "; }
349 $subject .= $ARGS[$counter];
350 $counter++;
351 } $counter--;
352 }
353
354 elsif ($ARGS[$counter] =~ /^-s$/) { ## Server ##
355 $counter++;
356 if ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) {
357 $conf{'server'} = $ARGS[$counter];
358 if ($conf{'server'} =~ /:/) { ## Port ##
359 ($conf{'server'},$conf{'port'}) = split(":",$conf{'server'});
360 }
361 }
362 else { printmsg("WARNING - The argument after -s was not the server!", 0); $counter--; }
363 }
364
365 elsif ($ARGS[$counter] =~ /^-a$/) { ## Attachments ##
366 $counter++;
367 while ($ARGS[$counter] && ($ARGS[$counter] !~ /^-/)) {
368 push (@attachments,$ARGS[$counter]);
369 $counter++;
370 } $counter--;
371 }
372
373 elsif ($ARGS[$counter] =~ /^-xu$/) { ## AuthSMTP Username ##
374 $counter++;
375 if ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) {
376 $opt{'username'} = $ARGS[$counter];
377 }
378 else {
379 printmsg("WARNING => The argument after -xu was not valid username!", 0);
380 $counter--;
381 }
382 }
383
384 elsif ($ARGS[$counter] =~ /^-xp$/) { ## AuthSMTP Password ##
385 $counter++;
386 if ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) {
387 $opt{'password'} = $ARGS[$counter];
388 }
389 else {
390 printmsg("WARNING => The argument after -xp was not valid password!", 0);
391 $counter--;
392 }
393 }
394
395 elsif ($ARGS[$counter] =~ /^-l$/) { ## Logging ##
396 $counter++;
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--; }
400 }
401
402 elsif ($ARGS[$counter] =~ s/^-v+//i) { ## Verbosity ##
403 my $tmp = (length($&) - 1);
404 $conf{'debug'} += $tmp;
405 }
406
407 elsif ($ARGS[$counter] =~ /^-q$/) { ## Quiet ##
408 $conf{'stdout'} = 0;
409 }
410
411 else {
412 printmsg("Error: \"$ARGS[$counter]\" is not a recognized option!", 0);
413 help();
414 }
415
416 }
417
418
419
420
421
422
423
424
425 ###################################################
426 ## Verify required variables are set correctly ##
427 ###################################################
428
429 if (!$conf{'server'}) {
430 $conf{'server'} = 'localhost';
431 }
432 if (!$conf{'port'}) {
433 $conf{'port'} = 25;
434 }
435 if (!$from) {
436 quit("ERROR => You must specify a 'from' field! Try --help.", 1);
437 }
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);
440 }
441
442 ## Make sure email addresses look OK.
443 foreach my $addr (@to, @cc, @bcc, $from, $opt{'reply-to'}) {
444 if ($addr) {
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);
448 quit("", 1);
449 }
450 }
451 }
452
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);
458 quit("", 1);
459 }
460 }
461
462 if ($conf{'logging'} and (!$conf{'logFile'})) {
463 quit("ERROR => You used -l to enable logging but didn't specify a log file!", 1);
464 }
465
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
471 print "Password: ";
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);
475 }
476 }
477 }
478
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);
483 }
484
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);
488 }
489
490 ## Return 0 errors
491 return(0);
492 }
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509 ## getline($socketRef)
510 sub getline {
511 my ($socketRef) = @_;
512 local ($/) = "\r\n";
513 return $$socketRef->getline;
514 }
515
516
517
518
519 ## Receive a (multiline?) SMTP response from ($socketRef)
520 sub getResponse {
521 my ($socketRef) = @_;
522 my ($tmp, $reply);
523 local ($/) = "\r\n";
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) {
528 $reply .= $tmp;
529 return undef unless defined($tmp = getline($socketRef));
530 }
531 $reply .= $tmp;
532 $reply =~ s/\r?\n$//o;
533 return $reply;
534 }
535
536
537
538
539 ###############################################################################################
540 ## Function: SMTPchat ( [string $command] )
541 ##
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.
547 ##
548 ## Input: [$command] A (optional) valid SMTP command (ex. "HELO")
549 ##
550 ##
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'}
555 ##
556 ##
557 ## Example: SMTPchat ("HELO mail.isp.net");
558 ###############################################################################################
559 sub SMTPchat {
560 my ($command) = @_;
561
562 printmsg("INFO => Sending: \t$command", 1) if ($command);
563
564 ## Send our command
565 print $SERVER "$command$CRLF" if ($command);
566
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;
572
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.";
576 return(1);
577 }
578
579 ## Make sure the server actually responded
580 if (!$result) {
581 $conf{'error'} = "ERROR => $conf{'server'}:$conf{'port'} returned a zero byte response to our query.";
582 return(2);
583 }
584
585 ## Validate the response
586 if (evalSMTPresponse($result)) {
587 ## conf{'error'} will already be set here
588 return(2);
589 }
590
591 ## Print the success messsage
592 printmsg($conf{'error'}, 1);
593
594 ## Return Success
595 return(0);
596 }
597
598
599
600
601
602
603
604
605
606
607
608
609 ###############################################################################################
610 ## Function: evalSMTPresponse (string $message )
611 ##
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.
614 ##
615 ##
616 ## Input: $message Data received from a SMTP server (ex. "220
617 ##
618 ##
619 ## Output: Returns zero on success, or non-zero on error.
620 ## Error messages will be stored in $conf{'error'}
621 ##
622 ##
623 ## Example: SMTPchat ("HELO mail.isp.net");
624 ###############################################################################################
625 sub evalSMTPresponse {
626 my ($message) = @_;
627
628 ## Validate input
629 if (!$message) {
630 $conf{'error'} = "ERROR => No message was passed to evalSMTPresponse(). What happened?";
631 return(1)
632 }
633
634 printmsg("DEBUG => evalSMTPresponse() - Checking for SMTP success or error status in the message: $message ", 3);
635
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";
640 return(0);
641 }
642
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";
647 return($1);
648 }
649
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";
652 return(2);
653
654 }
655
656
657
658
659
660
661
662
663
664
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 #########################################################
670 sub return_month {
671 my $x = $_[0];
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'; }
684 return (0);
685 }
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
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 #########################################################
707 sub return_day {
708 my $x = $_[0];
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'; }
716 return (0);
717 }
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734 ###############################################################################################
735 ## Function: returnAddressParts(string $address)
736 ##
737 ## Description: Returns a two element array containing the "Name" and "Address" parts of
738 ## an email address.
739 ##
740 ## Example: "Brandon Zehm <caspian@dotconf.net>"
741 ## would return: ("Brandon Zehm", "caspian@dotconf.net");
742 ##
743 ## "caspian@dotconf.net"
744 ## would return: ("caspian@dotconf.net", "caspian@dotconf.net")
745 ###############################################################################################
746 sub returnAddressParts {
747 my $input = $_[0];
748 my $name = "";
749 my $address = "";
750
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";
754 return(undef());
755 }
756
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);
760 }
761
762 ## Otherwise if that failed, just get the address: <caspian@dotconf.net>
763 elsif ($input =~ /<(\S+\@\S+)>/o) {
764 $name = $address = $1;
765 }
766
767 ## Or maybe it was formatted this way: caspian@dotconf.net
768 elsif ($input =~ /(\S+\@\S+)/o) {
769 $name = $address = $1;
770 }
771
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);
776 return(undef());
777 }
778
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);
784 }
785 return($name, $address);
786 }
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803 ###############################################################################################
804 ## Function: base64_encode(string $data)
805 ##
806 ## Description: Returns $data as a base64 encoded string
807 ## If the encoded data is returned in 76 character long lines with the final
808 ## CR\LF removed.
809 ###############################################################################################
810 sub base64_encode {
811 my $data = $_[0];
812 my $tmp = '';
813 my $base64 = '';
814 my $CRLF = "\r\n";
815
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
821 chop($tmp);
822 $tmp =~ tr|` -_|AA-Za-z0-9+/|; ## Translate from uuencode to base64
823 $base64 .= $tmp;
824 }
825
826 ###################################
827 ## Encode and send the leftovers ##
828 ###################################
829 my $padding = "";
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
833 chop($tmp);
834 $tmp =~ tr|` -_|AA-Za-z0-9+/|; ## Translate from uuencode to base64
835 $base64 .= $tmp;
836 }
837
838 ############################
839 ## Fix padding at the end ##
840 ############################
841 $data = '';
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
844 $data .= "$1$CRLF";
845 }
846 chomp $data;
847
848 return($data);
849 }
850
851
852
853
854
855
856
857
858
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);
868 my $bin = 1;
869
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
873
874 ##########################
875 ## Autodetect Mime Type ##
876 ##########################
877
878 @fields = split(/\./, $filename_name);
879 $encoding = $fields[$#fields];
880
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'; }
916
917
918 ############################
919 ## Process the attachment ##
920 ############################
921
922 #####################################
923 ## Generate and print MIME headers ##
924 #####################################
925
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";
931 $y .= "$CRLF";
932 print $SERVER $y;
933
934
935 ###########################################################
936 ## Convert the file to base64 and print it to the server ##
937 ###########################################################
938
939 open (FILETOATTACH, $filename) || do {
940 printmsg("ERROR => Opening the file [$filename] for attachment failed with the error: $!", 0);
941 return(1);
942 };
943 binmode(FILETOATTACH); ## Hack to make Win32 work
944
945 my $res = "";
946 my $tmp = "";
947 my $base64 = "";
948 while (<FILETOATTACH>) { ## Read a line from the (binary) file
949 $res .= $_;
950
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
956 chop($tmp);
957 $tmp =~ tr|` -_|AA-Za-z0-9+/|; ## Translate from uuencode to base64
958 $base64 .= $tmp;
959 }
960
961 ################################
962 ## Print chunks to the server ##
963 ################################
964 while ($base64 =~ s/(.{76})//s) {
965 print $SERVER "$1$CRLF";
966 }
967
968 }
969
970 ###################################
971 ## Encode and send the leftovers ##
972 ###################################
973 my $padding = "";
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
977 chop($res);
978 $res =~ tr|` -_|AA-Za-z0-9+/|; ## Translate from uuencode to base64
979 }
980
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
986 if ($res) {
987 while ($res =~ s/(.{1,76})//s) { ## Send it to the email server.
988 print $SERVER "$1$CRLF";
989 }
990 }
991
992 close (FILETOATTACH) || do {
993 printmsg("ERROR - Closing the filehandle for file [$filename] failed with the error: $!", 0);
994 return(2);
995 };
996
997 ## Return 0 errors
998 return(0);
999
1000 }
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010 ###############################################################################################
1011 ## Function: printmsg (string $message, int $level)
1012 ##
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.
1016 ##
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.
1022 ##
1023 ## Output: Prints to STDOUT
1024 ##
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.
1031 ##
1032 ## Example: printmsg("WARNING: We believe in generic error messages... NOT!", 0);
1033 ###############################################################################################
1034 sub printmsg {
1035 ## Assign incoming parameters to variables
1036 my ( $message, $level ) = @_;
1037
1038 ## Make sure input is sane
1039 $level = 0 if (!defined($level));
1040 $message =~ s/\s+$//sgo;
1041 $message =~ s/\r?\n/, /sgo;
1042
1043 ## Continue only if the debug level of the program is >= message debug level.
1044 if ($conf{'debug'} >= $level) {
1045
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);
1050
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";
1054 }
1055
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";
1060 }
1061
1062 }
1063
1064 ## Return 0 errors
1065 return(0);
1066 }
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079 ###############################################################################################
1080 ## FUNCTION:
1081 ## openLogFile ( $filename )
1082 ##
1083 ##
1084 ## DESCRIPTION:
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 $!.
1088 ##
1089 ##
1090 ## Example:
1091 ## openFile ("/var/log/sendEmail.log");
1092 ##
1093 ###############################################################################################
1094 sub openLogFile {
1095 ## Get the incoming filename
1096 my $filename = $_[0];
1097
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");
1102 close LOGFILE;
1103 chmod (0600, $filename);
1104 }
1105
1106 ## Now open the file and attach it to a filehandle
1107 open (LOGFILE,">>$filename") or return (1);
1108
1109 ## Put the file into non-buffering mode
1110 select LOGFILE;
1111 $| = 1;
1112 select STDOUT;
1113
1114 ## Return success
1115 return(0);
1116 }
1117
1118
1119
1120
1121
1122
1123
1124
1125 ###############################################################################################
1126 ## Function: read_file (string $filename)
1127 ##
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.
1131 ##
1132 ## Example: ($status, $file) = read_file)("/etc/passwd");
1133 ###############################################################################################
1134 sub read_file {
1135 my ( $filename ) = @_;
1136
1137 ## If the value specified is a file, load the file's contents
1138 if ( (-e $filename and -r $filename) ) {
1139 my $FILE;
1140 if(!open($FILE, ' ' . $filename)) {
1141 return((1, ""));
1142 }
1143 my $file = '';
1144 while (<$FILE>) {
1145 $file .= $_;
1146 }
1147 ## Strip an ending \r\n
1148 $file =~ s/\r?\n$//os;
1149 }
1150 return((1, ""));
1151 }
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161 ###############################################################################################
1162 ## Function: quit (string $message, int $errorLevel)
1163 ##
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.)
1167 ##
1168 ## Example: quit("Exiting program normally", 0);
1169 ###############################################################################################
1170 sub quit {
1171 my ( $message, $errorLevel ) = @_;
1172 $errorLevel = 0 if (!defined($errorLevel));
1173
1174 ## Print exit message
1175 if ($message) {
1176 printmsg($message, 0);
1177 }
1178
1179 ## Exit
1180 exit($errorLevel);
1181 }
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194 ###############################################################################################
1195 ## Function: help ()
1196 ##
1197 ## Description: For all those newbies ;)
1198 ## Prints a help message and exits the program.
1199 ##
1200 ###############################################################################################
1201 sub help {
1202 exit(1) if (!$conf{'stdout'});
1203 print <<EOM;
1204
1205 ${colorBold}$conf{'programName'}-$conf{'version'} by $conf{'authorName'} <$conf{'authorEmail'}>${colorNoBold}
1206
1207 Synopsis: $conf{'programName'} -f ADDRESS [options]
1208
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
1213
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'}
1219
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)
1224
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>
1237
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
1245
1246 EOM
1247 exit(1);
1248 }
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258 ###############################################################################################
1259 ## Function: helpTopic ($topic)
1260 ##
1261 ## Description: For all those newbies ;)
1262 ## Prints a help message and exits the program.
1263 ##
1264 ###############################################################################################
1265 sub helpTopic {
1266 exit(1) if (!$conf{'stdout'});
1267 my ($topic) = @_;
1268
1269 CASE: {
1270
1271
1272
1273
1274 ## ADDRESSING
1275 ($topic eq 'addressing') && do {
1276 print <<EOM;
1277
1278 ${colorBold}ADDRESSING DOCUMENTATION${colorNormal}
1279
1280 ${colorGreen}Addressing Options${colorNormal}
1281 Options related to addressing:
1282 -f ADDRESS
1283 -t ADDRESS [ADDRESS ...]
1284 -cc ADDRESS [ADDRESS ...]
1285 -bcc ADDRESS [ADDRESS ...]
1286 -o reply-to=ADDRESS
1287
1288 -f ADDRESS
1289 This required option specifies who the email is from, I.E. the sender's
1290 email address.
1291
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.
1295
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.
1299
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.
1303
1304 -o reply-to=ADDRESS
1305 This option specifies that an optional "Reply-To" address should be
1306 written in the email's headers.
1307
1308
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"
1313
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.
1317
1318
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.
1324
1325 Examples:
1326 (I used "-t" in these examples, but it can be "-cc" or "-bcc" as well)
1327
1328 * Space separated list:
1329 -t jane.doe\@yahoo.com "John Doe <john.doe\@gmail.com>"
1330
1331 * Semi-colon separated list:
1332 -t "jane.doe\@yahoo.com; John Doe <john.doe\@gmail.com>"
1333
1334 * Comma separated list:
1335 -t "jane.doe\@yahoo.com, John Doe <john.doe\@gmail.com>"
1336
1337 * Multiple -t, -cc, or -bcc options:
1338 -t "jane.doe\@yahoo.com" -t "John Doe <john.doe\@gmail.com>"
1339
1340
1341 EOM
1342 last CASE;
1343 };
1344
1345
1346
1347
1348
1349
1350 ## MESSAGE
1351 ($topic eq 'message') && do {
1352 print <<EOM;
1353
1354 ${colorBold}MESSAGE DOCUMENTATION${colorNormal}
1355
1356 ${colorGreen}Message Options${colorNormal}
1357 Options related to the email message body:
1358 -u SUBJECT
1359 -m MESSAGE
1360 -o message-file=FILE
1361 -o message-header=EMAIL HEADER
1362 -o message-charset=CHARSET
1363 -o message-format=raw
1364
1365 -u SUBJECT
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.
1370 Examples:
1371 -u "Contact information while on vacation"
1372 -u New Microsoft vulnerability discovered
1373
1374 -m MESSAGE
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.
1379
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.
1383 Examples:
1384 -m "See you in South Beach, Hawaii. -Todd"
1385 -m Please ensure that you upgrade your systems right away
1386
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."
1390
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.
1395
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"
1402
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!
1409 Example:
1410 To scare a Microsoft Outlook user you may want to try this:
1411 -o message-header="X-Message-Flag: Message contains illegal content"
1412 Example:
1413 To request a read-receipt try this:
1414 -o message-header="Disposition-Notification-To: <user\@domain.com>"
1415 Example:
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
1419
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.
1423
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:
1431 -u SUBJECT
1432 -o message-header=EMAIL HEADER
1433 -o message-charset=CHARSET
1434 -a ATTACHMENT
1435
1436
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.
1440 Example:
1441 -m "This is the message body"
1442
1443 2) By putting the message body in a file and using the -o message-file=FILE
1444 command line option.
1445 Example:
1446 -o message-file=/root/message.txt
1447
1448 3) By piping the message body to sendEmail when nither of the above command
1449 line options were specified.
1450 Example:
1451 grep "ERROR" /var/log/messages | sendEmail -t you\@domain.com ...
1452
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.
1458
1459
1460 EOM
1461 last CASE;
1462 };
1463
1464
1465
1466
1467
1468
1469 ## MISC
1470 ($topic eq 'misc') && do {
1471 print <<EOM;
1472
1473 ${colorBold}MISC DOCUMENTATION${colorNormal}
1474
1475 ${colorGreen}Misc Options${colorNormal}
1476 Options that don't fit anywhere else:
1477 -a ATTACHMENT [ATTACHMENT ...]
1478 -xu USERNAME
1479 -xp PASSWORD
1480 -o username=USERNAME
1481 -o password=PASSWORD
1482 -o tls=<auto|yes|no>
1483 -o timeout=SECONDS
1484
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
1489
1490 -xu USERNAME
1491 Alias for -o username=USERNAME
1492
1493 -xp PASSWORD
1494 Alias for -o password=PASSWORD
1495
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.
1500
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.
1505
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.
1513
1514 -o timeout=SECONDS
1515 This option sets the timeout value in seconds used for all network reads,
1516 writes, and a few other things.
1517
1518 EOM
1519 last CASE;
1520 };
1521
1522
1523
1524
1525
1526
1527 ## NETWORKING
1528 ($topic eq 'networking') && do {
1529 print <<EOM;
1530
1531 ${colorBold}NETWORKING DOCUMENTATION${colorNormal}
1532
1533 ${colorGreen}Networking Options${colorNormal}
1534 Options related to networking:
1535 -s SERVER[:PORT]
1536 -o tls=<auto|yes|no>
1537 -o timeout=SECONDS
1538
1539 -s SERVER[:PORT]
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
1545 on your computer!
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
1552
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.
1560
1561 -o timeout=SECONDS
1562 This option sets the timeout value in seconds used for all network reads,
1563 writes, and a few other things.
1564
1565
1566 EOM
1567 last CASE;
1568 };
1569
1570
1571
1572
1573
1574
1575 ## OUTPUTO
1576 ($topic eq 'output') && do {
1577 print <<EOM;
1578
1579 ${colorBold}OUTPUT DOCUMENTATION${colorNormal}
1580
1581 ${colorGreen}Output Options${colorNormal}
1582 Options related to output:
1583 -l LOGFILE
1584 -v
1585 -q
1586
1587 -l LOGFILE
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.
1591
1592 -q
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.
1596
1597 -v
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.
1608
1609
1610 EOM
1611 last CASE;
1612 };
1613
1614 ## Unknown option selected!
1615 quit("ERROR => The help topic specified is not valid!", 1);
1616 };
1617
1618 exit(1);
1619 }
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642 #############################
1643 ## ##
1644 ## MAIN PROGRAM ##
1645 ## ##
1646 #############################
1647
1648
1649 ## Initialize
1650 initialize();
1651
1652 ## Process Command Line
1653 processCommandLine();
1654 $conf{'alarm'} = $opt{'timeout'};
1655
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
1658
1659
1660
1661
1662 ###################################################
1663 ## Read $message from STDIN if -m was not used ##
1664 ###################################################
1665
1666 if (!($message)) {
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);
1672 quit("", 1);
1673 }
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);
1677 quit("", 1);
1678 }
1679 if (!open(MFILE, "< " . $opt{'message-file'})) {
1680 printmsg("ERROR => Error opening message body file [$opt{'message-file'}]: $!", 0);
1681 quit("", 1);
1682 }
1683 while (<MFILE>) {
1684 $message .= $_;
1685 }
1686 close(MFILE);
1687 }
1688
1689 ## Read message body from STDIN
1690 else {
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);
1698 }
1699 while (<STDIN>) { ## Read STDIN into $message
1700 $message .= $_;
1701 alarm(0) if ($^O !~ /win/i); ## Disable the alarm since at least one line was received
1702 }
1703 printmsg("Message input complete.", 0);
1704 }
1705 }
1706
1707 ## Replace bare LF's with CRLF's (\012 should always have \015 with it)
1708 $message =~ s/(\015)?(\012|$)/\015\012/g;
1709
1710 ## Replace bare CR's with CRLF's (\015 should always have \012 with it)
1711 $message =~ s/(\015)(\012|$)?/\015\012/g;
1712
1713 ## Check message for bare periods and encode them
1714 $message =~ s/(^|$CRLF)(\.{1})($CRLF|$)/$1.$2$3/g;
1715
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'});
1720
1721
1722
1723
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);
1731 quit("", 1);
1732 };
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'},
1736 Proto => 'tcp',
1737 Autoflush => 1,
1738 timeout => $conf{'alarm'},
1739 );
1740 alarm(0) if ($^O !~ /win/i); ## alarm() doesn't work in win32;
1741
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);
1746 quit("", 1);
1747 }
1748
1749
1750
1751
1752
1753
1754 #########################
1755 ## Do the SMTP Dance ##
1756 #########################
1757
1758 ## Read initial greeting to make sure we're talking to a live SMTP server
1759 if (SMTPchat()) { quit($conf{'error'}, 1); }
1760
1761 ## EHLO
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);
1768 }
1769 }
1770 else {
1771
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);
1776 }
1777 else {
1778 $conf{'tls_server'} = 0;
1779 printmsg("DEBUG => The remote SMTP server does NOT support TLS :(", 2);
1780 }
1781
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);
1788 }
1789 printmsg("DEBUG => TLS: Using cipher: ". $SERVER->get_cipher(), 3);
1790 printmsg("DEBUG => TLS session initialized :)", 1);
1791
1792 ## Restart our SMTP session
1793 if (SMTPchat('EHLO ' . $conf{'hostname'})) { quit($conf{'error'}, 1); }
1794 }
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);
1797 }
1798
1799
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);
1804 }
1805 else {
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); }
1810 #
1811 # ## FIXME!!
1812 #
1813 # printmsg("DEBUG => User authentication was successful", 1);
1814 # }
1815
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);
1821 }
1822
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);
1830 }
1831
1832 else {
1833 printmsg("WARNING => SMTP-AUTH: No mutually supported authentication methods available", 0);
1834 }
1835 }
1836 }
1837 }
1838
1839 ## MAIL FROM
1840 if (SMTPchat('MAIL FROM:<' .(returnAddressParts($from))[1]. '>')) { quit($conf{'error'}, 1); }
1841
1842 ## RCPT TO
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);
1850 }
1851 elsif ($oneRcptAccepted == 0) {
1852 $oneRcptAccepted = 1;
1853 }
1854 }
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);
1858 }
1859
1860 ## DATA
1861 if (SMTPchat('DATA')) { quit($conf{'error'}, 1); }
1862
1863
1864 ###############################
1865 ## Build and send the body ##
1866 ###############################
1867 printmsg("INFO => Sending message body",1);
1868
1869 ## If the message-format is raw just send the message as-is.
1870 if ($opt{'message-format'} =~ /^raw$/i) {
1871 print $SERVER $message;
1872 }
1873
1874 ## If the message-format isn't raw, then build and send the message,
1875 else {
1876
1877 ## Message-ID: <MessageID>
1878 if ($opt{'message-header'} !~ /^Message-ID:/iom) {
1879 $header .= 'Message-ID: <' . $conf{'Message-ID'} . '@' . $conf{'hostname'} . '>' . $CRLF;
1880 }
1881
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;
1886 }
1887
1888 ## Reply-To:
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;
1892 }
1893
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
1897 }
1898 elsif (scalar(@to) > 0) {
1899 $header .= "To:";
1900 for (my $a = 0; $a < scalar(@to); $a++) {
1901 my $msg = "";
1902
1903 my ($name, $address) = returnAddressParts($to[$a]);
1904 $msg = " \"$name\" <$address>";
1905
1906 ## If we're not on the last address add a comma to the end of the line.
1907 if (($a + 1) != scalar(@to)) {
1908 $msg .= ",";
1909 }
1910
1911 $header .= $msg . $CRLF;
1912 }
1913 }
1914 ## We always want a To: line so if the only recipients were bcc'd they don't see who it was sent to
1915 else {
1916 $header .= "To: \"Undisclosed Recipients\" <>$CRLF";
1917 }
1918
1919 if (scalar(@cc) > 0 and $opt{'message-header'} !~ /^Cc:/iom) {
1920 $header .= "Cc:";
1921 for (my $a = 0; $a < scalar(@cc); $a++) {
1922 my $msg = "";
1923
1924 my ($name, $address) = returnAddressParts($cc[$a]);
1925 $msg = " \"$name\" <$address>";
1926
1927 ## If we're not on the last address add a comma to the end of the line.
1928 if (($a + 1) != scalar(@cc)) {
1929 $msg .= ",";
1930 }
1931
1932 $header .= $msg . $CRLF;
1933 }
1934 }
1935
1936 if ($opt{'message-header'} !~ /^Subject:/iom) {
1937 $header .= 'Subject: ' . $subject . $CRLF; ## Subject
1938 }
1939 if ($opt{'message-header'} !~ /^Date:/iom) {
1940 $header .= 'Date: ' . $date . $CRLF; ## Date
1941 }
1942 if ($opt{'message-header'} !~ /^X-Mailer:/iom) {
1943 $header .= 'X-Mailer: sendEmail-'.$conf{'version'}.$CRLF; ## X-Mailer
1944 }
1945
1946 ## Encode all messages with MIME.
1947 if ($opt{'message-header'} !~ /^MIME-Version:/iom) {
1948 $header .= "MIME-Version: 1.0$CRLF";
1949 }
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";
1954 }
1955
1956 ## Send additional message header line(s) if specified
1957 if ($opt{'message-header'}) {
1958 $header .= $opt{'message-header'};
1959 }
1960
1961 ## Send the message header to the server
1962 print $SERVER $header . $CRLF;
1963
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";
1967
1968
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";
1975 }
1976 ## Otherwise it's a normal text email
1977 else {
1978 print $SERVER "Content-Type: text/plain;$CRLF";
1979 }
1980 print $SERVER " charset=\"" . $opt{'message-charset'} . "\"$CRLF";
1981 print $SERVER "Content-Transfer-Encoding: 7bit$CRLF";
1982 print $SERVER $CRLF . $message;
1983
1984
1985
1986 ## Send Attachemnts
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
1990
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);
1996 }
1997 elsif ( ! -r $filename ) {
1998 printmsg("ERROR => Couldn't open the file [$filename] for reading: $! Email will be sent, but without that attachment.", 0);
1999 }
2000 else {
2001 printmsg("DEBUG => Sending the attachment [$filename]", 1);
2002 send_attachment($filename);
2003 }
2004 }
2005 }
2006
2007
2008 ## End the mime encoded message
2009 print $SERVER "$CRLF--$conf{'delimiter'}--$CRLF";
2010 }
2011
2012
2013 ## Tell the server we are done sending the email
2014 print $SERVER "$CRLF.$CRLF";
2015 if (SMTPchat()) { quit($conf{'error'}, 1); }
2016
2017
2018
2019 ####################
2020 # We are done!!! #
2021 ####################
2022
2023 ## Disconnect from the server (don't SMTPchat(), it breaks when using TLS)
2024 print $SERVER "QUIT$CRLF";
2025 close $SERVER;
2026
2027
2028
2029
2030
2031
2032 #######################################
2033 ## Generate exit message/log entry ##
2034 #######################################
2035
2036 if ($conf{'debug'} or $conf{'logging'}) {
2037 printmsg("Generating a detailed exit message", 3);
2038
2039 ## Put the message together
2040 my $output = "Email was sent successfully! From: <" . (returnAddressParts($from))[1] . "> ";
2041
2042 if (scalar(@to) > 0) {
2043 $output .= "To: ";
2044 for ($a = 0; $a < scalar(@to); $a++) {
2045 $output .= "<" . (returnAddressParts($to[$a]))[1] . "> ";
2046 }
2047 }
2048 if (scalar(@cc) > 0) {
2049 $output .= "Cc: ";
2050 for ($a = 0; $a < scalar(@cc); $a++) {
2051 $output .= "<" . (returnAddressParts($cc[$a]))[1] . "> ";
2052 }
2053 }
2054 if (scalar(@bcc) > 0) {
2055 $output .= "Bcc: ";
2056 for ($a = 0; $a < scalar(@bcc); $a++) {
2057 $output .= "<" . (returnAddressParts($bcc[$a]))[1] . "> ";
2058 }
2059 }
2060 $output .= "Subject: [$subject] " if ($subject);
2061 if (scalar(@attachments_names) > 0) {
2062 $output .= "Attachment(s): ";
2063 foreach(@attachments_names) {
2064 $output .= "[$_] ";
2065 }
2066 }
2067 $output .= "Server: [$conf{'server'}:$conf{'port'}]";
2068
2069
2070 ######################
2071 # Exit the program #
2072 ######################
2073
2074 ## Print / Log the detailed message
2075 quit($output, 0);
2076 }
2077 else {
2078 ## Or the standard message
2079 quit("Email was sent successfully!", 0);
2080 }
2081
2082
2083