Merge branch 'tr/send-email-ssl'
[git/dscho.git] / git-send-email.perl
blobedb12c2aaaa64a13d0c59f8432d2ddd7d1cf75bd
1 #!/usr/bin/perl -w
3 # Copyright 2002,2005 Greg Kroah-Hartman <greg@kroah.com>
4 # Copyright 2005 Ryan Anderson <ryan@michonline.com>
6 # GPL v2 (See COPYING)
8 # Ported to support git "mbox" format files by Ryan Anderson <ryan@michonline.com>
10 # Sends a collection of emails to the given email addresses, disturbingly fast.
12 # Supports two formats:
13 # 1. mbox format files (ignoring most headers and MIME formatting - this is designed for sending patches)
14 # 2. The original format support by Greg's script:
15 # first line of the message is who to CC,
16 # and second line is the subject of the message.
19 use strict;
20 use warnings;
21 use Term::ReadLine;
22 use Getopt::Long;
23 use Data::Dumper;
24 use Term::ANSIColor;
25 use Git;
27 package FakeTerm;
28 sub new {
29 my ($class, $reason) = @_;
30 return bless \$reason, shift;
32 sub readline {
33 my $self = shift;
34 die "Cannot use readline on FakeTerm: $$self";
36 package main;
39 sub usage {
40 print <<EOT;
41 git-send-email [options] <file | directory>...
42 Options:
43 --from Specify the "From:" line of the email to be sent.
45 --to Specify the primary "To:" line of the email.
47 --cc Specify an initial "Cc:" list for the entire series
48 of emails.
50 --cc-cmd Specify a command to execute per file which adds
51 per file specific cc address entries
53 --bcc Specify a list of email addresses that should be Bcc:
54 on all the emails.
56 --compose Use \$GIT_EDITOR, core.editor, \$EDITOR, or \$VISUAL to edit
57 an introductory message for the patch series.
59 --subject Specify the initial "Subject:" line.
60 Only necessary if --compose is also set. If --compose
61 is not set, this will be prompted for.
63 --in-reply-to Specify the first "In-Reply-To:" header line.
64 Only used if --compose is also set. If --compose is not
65 set, this will be prompted for.
67 --chain-reply-to If set, the replies will all be to the previous
68 email sent, rather than to the first email sent.
69 Defaults to on.
71 --signed-off-cc Automatically add email addresses that appear in
72 Signed-off-by: or Cc: lines to the cc: list. Defaults to on.
74 --identity The configuration identity, a subsection to prioritise over
75 the default section.
77 --smtp-server If set, specifies the outgoing SMTP server to use.
78 Defaults to localhost. Port number can be specified here with
79 hostname:port format or by using --smtp-server-port option.
81 --smtp-server-port Specify a port on the outgoing SMTP server to connect to.
83 --smtp-user The username for SMTP-AUTH.
85 --smtp-pass The password for SMTP-AUTH.
87 --smtp-encryption Specify 'tls' for STARTTLS encryption, or 'ssl' for SSL.
88 Any other value disables the feature.
90 --smtp-ssl Synonym for '--smtp-encryption=ssl'. Deprecated.
92 --suppress-cc Suppress the specified category of auto-CC. The category
93 can be one of 'author' for the patch author, 'self' to
94 avoid copying yourself, 'sob' for Signed-off-by lines,
95 'cccmd' for the output of the cccmd, or 'all' to suppress
96 all of these.
98 --suppress-from Suppress sending emails to yourself. Defaults to off.
100 --thread Specify that the "In-Reply-To:" header should be set on all
101 emails. Defaults to on.
103 --quiet Make git-send-email less verbose. One line per email
104 should be all that is output.
106 --dry-run Do everything except actually send the emails.
108 --envelope-sender Specify the envelope sender used to send the emails.
110 --no-validate Don't perform any sanity checks on patches.
113 exit(1);
116 # most mail servers generate the Date: header, but not all...
117 sub format_2822_time {
118 my ($time) = @_;
119 my @localtm = localtime($time);
120 my @gmttm = gmtime($time);
121 my $localmin = $localtm[1] + $localtm[2] * 60;
122 my $gmtmin = $gmttm[1] + $gmttm[2] * 60;
123 if ($localtm[0] != $gmttm[0]) {
124 die "local zone differs from GMT by a non-minute interval\n";
126 if ((($gmttm[6] + 1) % 7) == $localtm[6]) {
127 $localmin += 1440;
128 } elsif ((($gmttm[6] - 1) % 7) == $localtm[6]) {
129 $localmin -= 1440;
130 } elsif ($gmttm[6] != $localtm[6]) {
131 die "local time offset greater than or equal to 24 hours\n";
133 my $offset = $localmin - $gmtmin;
134 my $offhour = $offset / 60;
135 my $offmin = abs($offset % 60);
136 if (abs($offhour) >= 24) {
137 die ("local time offset greater than or equal to 24 hours\n");
140 return sprintf("%s, %2d %s %d %02d:%02d:%02d %s%02d%02d",
141 qw(Sun Mon Tue Wed Thu Fri Sat)[$localtm[6]],
142 $localtm[3],
143 qw(Jan Feb Mar Apr May Jun
144 Jul Aug Sep Oct Nov Dec)[$localtm[4]],
145 $localtm[5]+1900,
146 $localtm[2],
147 $localtm[1],
148 $localtm[0],
149 ($offset >= 0) ? '+' : '-',
150 abs($offhour),
151 $offmin,
155 my $have_email_valid = eval { require Email::Valid; 1 };
156 my $smtp;
157 my $auth;
159 sub unique_email_list(@);
160 sub cleanup_compose_files();
162 # Constants (essentially)
163 my $compose_filename = ".msg.$$";
165 # Variables we fill in automatically, or via prompting:
166 my (@to,@cc,@initial_cc,@bcclist,@xh,
167 $initial_reply_to,$initial_subject,@files,$author,$sender,$smtp_authpass,$compose,$time);
169 my $envelope_sender;
171 # Example reply to:
172 #$initial_reply_to = ''; #<20050203173208.GA23964@foobar.com>';
174 my $repo = eval { Git->repository() };
175 my @repo = $repo ? ($repo) : ();
176 my $term = eval {
177 $ENV{"GIT_SEND_EMAIL_NOTTY"}
178 ? new Term::ReadLine 'git-send-email', \*STDIN, \*STDOUT
179 : new Term::ReadLine 'git-send-email';
181 if ($@) {
182 $term = new FakeTerm "$@: going non-interactive";
185 # Behavior modification variables
186 my ($quiet, $dry_run) = (0, 0);
188 # Variables with corresponding config settings
189 my ($thread, $chain_reply_to, $suppress_from, $signed_off_cc, $cc_cmd);
190 my ($smtp_server, $smtp_server_port, $smtp_authuser, $smtp_encryption);
191 my ($identity, $aliasfiletype, @alias_files, @smtp_host_parts);
192 my ($no_validate);
193 my (@suppress_cc);
195 my %config_bool_settings = (
196 "thread" => [\$thread, 1],
197 "chainreplyto" => [\$chain_reply_to, 1],
198 "suppressfrom" => [\$suppress_from, undef],
199 "signedoffcc" => [\$signed_off_cc, undef],
202 my %config_settings = (
203 "smtpserver" => \$smtp_server,
204 "smtpserverport" => \$smtp_server_port,
205 "smtpuser" => \$smtp_authuser,
206 "smtppass" => \$smtp_authpass,
207 "to" => \@to,
208 "cc" => \@initial_cc,
209 "cccmd" => \$cc_cmd,
210 "aliasfiletype" => \$aliasfiletype,
211 "bcc" => \@bcclist,
212 "aliasesfile" => \@alias_files,
213 "suppresscc" => \@suppress_cc,
214 "envelopesender" => \$envelope_sender,
217 # Handle Uncouth Termination
218 sub signal_handler {
220 # Make text normal
221 print color("reset"), "\n";
223 # SMTP password masked
224 system "stty echo";
226 # tmp files from --compose
227 if (-e $compose_filename) {
228 print "'$compose_filename' contains an intermediate version of the email you were composing.\n";
230 if (-e ($compose_filename . ".final")) {
231 print "'$compose_filename.final' contains the composed email.\n"
234 exit;
237 $SIG{TERM} = \&signal_handler;
238 $SIG{INT} = \&signal_handler;
240 # Begin by accumulating all the variables (defined above), that we will end up
241 # needing, first, from the command line:
243 my $rc = GetOptions("sender|from=s" => \$sender,
244 "in-reply-to=s" => \$initial_reply_to,
245 "subject=s" => \$initial_subject,
246 "to=s" => \@to,
247 "cc=s" => \@initial_cc,
248 "bcc=s" => \@bcclist,
249 "chain-reply-to!" => \$chain_reply_to,
250 "smtp-server=s" => \$smtp_server,
251 "smtp-server-port=s" => \$smtp_server_port,
252 "smtp-user=s" => \$smtp_authuser,
253 "smtp-pass:s" => \$smtp_authpass,
254 "smtp-ssl" => sub { $smtp_encryption = 'ssl' },
255 "smtp-encryption=s" => \$smtp_encryption,
256 "identity=s" => \$identity,
257 "compose" => \$compose,
258 "quiet" => \$quiet,
259 "cc-cmd=s" => \$cc_cmd,
260 "suppress-from!" => \$suppress_from,
261 "suppress-cc=s" => \@suppress_cc,
262 "signed-off-cc|signed-off-by-cc!" => \$signed_off_cc,
263 "dry-run" => \$dry_run,
264 "envelope-sender=s" => \$envelope_sender,
265 "thread!" => \$thread,
266 "no-validate" => \$no_validate,
269 unless ($rc) {
270 usage();
273 # Now, let's fill any that aren't set in with defaults:
275 sub read_config {
276 my ($prefix) = @_;
278 foreach my $setting (keys %config_bool_settings) {
279 my $target = $config_bool_settings{$setting}->[0];
280 $$target = Git::config_bool(@repo, "$prefix.$setting") unless (defined $$target);
283 foreach my $setting (keys %config_settings) {
284 my $target = $config_settings{$setting};
285 if (ref($target) eq "ARRAY") {
286 unless (@$target) {
287 my @values = Git::config(@repo, "$prefix.$setting");
288 @$target = @values if (@values && defined $values[0]);
291 else {
292 $$target = Git::config(@repo, "$prefix.$setting") unless (defined $$target);
296 if (!defined $smtp_encryption) {
297 my $enc = Git::config(@repo, "$prefix.smtpencryption");
298 if (defined $enc) {
299 $smtp_encryption = $enc;
300 } elsif (Git::config_bool(@repo, "$prefix.smtpssl")) {
301 $smtp_encryption = 'ssl';
306 # read configuration from [sendemail "$identity"], fall back on [sendemail]
307 $identity = Git::config(@repo, "sendemail.identity") unless (defined $identity);
308 read_config("sendemail.$identity") if (defined $identity);
309 read_config("sendemail");
311 # fall back on builtin bool defaults
312 foreach my $setting (values %config_bool_settings) {
313 ${$setting->[0]} = $setting->[1] unless (defined (${$setting->[0]}));
316 # 'default' encryption is none -- this only prevents a warning
317 $smtp_encryption = '' unless (defined $smtp_encryption);
319 # Set CC suppressions
320 my(%suppress_cc);
321 if (@suppress_cc) {
322 foreach my $entry (@suppress_cc) {
323 die "Unknown --suppress-cc field: '$entry'\n"
324 unless $entry =~ /^(all|cccmd|cc|author|self|sob)$/;
325 $suppress_cc{$entry} = 1;
329 if ($suppress_cc{'all'}) {
330 foreach my $entry (qw (ccmd cc author self sob)) {
331 $suppress_cc{$entry} = 1;
333 delete $suppress_cc{'all'};
336 # If explicit old-style ones are specified, they trump --suppress-cc.
337 $suppress_cc{'self'} = $suppress_from if defined $suppress_from;
338 $suppress_cc{'sob'} = !$signed_off_cc if defined $signed_off_cc;
340 # Debugging, print out the suppressions.
341 if (0) {
342 print "suppressions:\n";
343 foreach my $entry (keys %suppress_cc) {
344 printf " %-5s -> $suppress_cc{$entry}\n", $entry;
348 my ($repoauthor, $repocommitter);
349 ($repoauthor) = Git::ident_person(@repo, 'author');
350 ($repocommitter) = Git::ident_person(@repo, 'committer');
352 # Verify the user input
354 foreach my $entry (@to) {
355 die "Comma in --to entry: $entry'\n" unless $entry !~ m/,/;
358 foreach my $entry (@initial_cc) {
359 die "Comma in --cc entry: $entry'\n" unless $entry !~ m/,/;
362 foreach my $entry (@bcclist) {
363 die "Comma in --bcclist entry: $entry'\n" unless $entry !~ m/,/;
366 my %aliases;
367 my %parse_alias = (
368 # multiline formats can be supported in the future
369 mutt => sub { my $fh = shift; while (<$fh>) {
370 if (/^\s*alias\s+(\S+)\s+(.*)$/) {
371 my ($alias, $addr) = ($1, $2);
372 $addr =~ s/#.*$//; # mutt allows # comments
373 # commas delimit multiple addresses
374 $aliases{$alias} = [ split(/\s*,\s*/, $addr) ];
375 }}},
376 mailrc => sub { my $fh = shift; while (<$fh>) {
377 if (/^alias\s+(\S+)\s+(.*)$/) {
378 # spaces delimit multiple addresses
379 $aliases{$1} = [ split(/\s+/, $2) ];
380 }}},
381 pine => sub { my $fh = shift; while (<$fh>) {
382 if (/^(\S+)\t.*\t(.*)$/) {
383 $aliases{$1} = [ split(/\s*,\s*/, $2) ];
384 }}},
385 gnus => sub { my $fh = shift; while (<$fh>) {
386 if (/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) {
387 $aliases{$1} = [ $2 ];
391 if (@alias_files and $aliasfiletype and defined $parse_alias{$aliasfiletype}) {
392 foreach my $file (@alias_files) {
393 open my $fh, '<', $file or die "opening $file: $!\n";
394 $parse_alias{$aliasfiletype}->($fh);
395 close $fh;
399 ($sender) = expand_aliases($sender) if defined $sender;
401 # Now that all the defaults are set, process the rest of the command line
402 # arguments and collect up the files that need to be processed.
403 for my $f (@ARGV) {
404 if (-d $f) {
405 opendir(DH,$f)
406 or die "Failed to opendir $f: $!";
408 push @files, grep { -f $_ } map { +$f . "/" . $_ }
409 sort readdir(DH);
411 } elsif (-f $f) {
412 push @files, $f;
414 } else {
415 print STDERR "Skipping $f - not found.\n";
419 if (!$no_validate) {
420 foreach my $f (@files) {
421 my $error = validate_patch($f);
422 $error and die "fatal: $f: $error\nwarning: no patches were sent\n";
426 if (@files) {
427 unless ($quiet) {
428 print $_,"\n" for (@files);
430 } else {
431 print STDERR "\nNo patch files specified!\n\n";
432 usage();
435 my $prompting = 0;
436 if (!defined $sender) {
437 $sender = $repoauthor || $repocommitter || '';
439 while (1) {
440 $_ = $term->readline("Who should the emails appear to be from? [$sender] ");
441 last if defined $_;
442 print "\n";
445 $sender = $_ if ($_);
446 print "Emails will be sent from: ", $sender, "\n";
447 $prompting++;
450 if (!@to) {
453 while (1) {
454 $_ = $term->readline("Who should the emails be sent to? ", "");
455 last if defined $_;
456 print "\n";
459 my $to = $_;
460 push @to, split /,\s*/, $to;
461 $prompting++;
464 sub expand_aliases {
465 my @cur = @_;
466 my @last;
467 do {
468 @last = @cur;
469 @cur = map { $aliases{$_} ? @{$aliases{$_}} : $_ } @last;
470 } while (join(',',@cur) ne join(',',@last));
471 return @cur;
474 @to = expand_aliases(@to);
475 @to = (map { sanitize_address($_) } @to);
476 @initial_cc = expand_aliases(@initial_cc);
477 @bcclist = expand_aliases(@bcclist);
479 if (!defined $initial_subject && $compose) {
480 while (1) {
481 $_ = $term->readline("What subject should the initial email start with? ", $initial_subject);
482 last if defined $_;
483 print "\n";
486 $initial_subject = $_;
487 $prompting++;
490 if ($thread && !defined $initial_reply_to && $prompting) {
491 while (1) {
492 $_= $term->readline("Message-ID to be used as In-Reply-To for the first email? ", $initial_reply_to);
493 last if defined $_;
494 print "\n";
497 $initial_reply_to = $_;
499 if (defined $initial_reply_to) {
500 $initial_reply_to =~ s/^\s*<?//;
501 $initial_reply_to =~ s/>?\s*$//;
502 $initial_reply_to = "<$initial_reply_to>" if $initial_reply_to ne '';
505 if (!defined $smtp_server) {
506 foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
507 if (-x $_) {
508 $smtp_server = $_;
509 last;
512 $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
515 if ($compose) {
516 # Note that this does not need to be secure, but we will make a small
517 # effort to have it be unique
518 open(C,">",$compose_filename)
519 or die "Failed to open for writing $compose_filename: $!";
520 print C "From $sender # This line is ignored.\n";
521 printf C "Subject: %s\n\n", $initial_subject;
522 printf C <<EOT;
523 GIT: Please enter your email below.
524 GIT: Lines beginning in "GIT: " will be removed.
525 GIT: Consider including an overall diffstat or table of contents
526 GIT: for the patch you are writing.
529 close(C);
531 my $editor = $ENV{GIT_EDITOR} || Git::config(@repo, "core.editor") || $ENV{VISUAL} || $ENV{EDITOR} || "vi";
532 system('sh', '-c', $editor.' "$@"', $editor, $compose_filename);
534 open(C2,">",$compose_filename . ".final")
535 or die "Failed to open $compose_filename.final : " . $!;
537 open(C,"<",$compose_filename)
538 or die "Failed to open $compose_filename : " . $!;
540 my $need_8bit_cte = file_has_nonascii($compose_filename);
541 my $in_body = 0;
542 while(<C>) {
543 next if m/^GIT: /;
544 if (!$in_body && /^\n$/) {
545 $in_body = 1;
546 if ($need_8bit_cte) {
547 print C2 "MIME-Version: 1.0\n",
548 "Content-Type: text/plain; ",
549 "charset=utf-8\n",
550 "Content-Transfer-Encoding: 8bit\n";
553 if (!$in_body && /^MIME-Version:/i) {
554 $need_8bit_cte = 0;
556 if (!$in_body && /^Subject: ?(.*)/i) {
557 my $subject = $1;
558 $_ = "Subject: " .
559 ($subject =~ /[^[:ascii:]]/ ?
560 quote_rfc2047($subject) :
561 $subject) .
562 "\n";
564 print C2 $_;
566 close(C);
567 close(C2);
569 while (1) {
570 $_ = $term->readline("Send this email? (y|n) ");
571 last if defined $_;
572 print "\n";
575 if (uc substr($_,0,1) ne 'Y') {
576 cleanup_compose_files();
577 exit(0);
580 @files = ($compose_filename . ".final", @files);
583 # Variables we set as part of the loop over files
584 our ($message_id, %mail, $subject, $reply_to, $references, $message);
586 sub extract_valid_address {
587 my $address = shift;
588 my $local_part_regexp = '[^<>"\s@]+';
589 my $domain_regexp = '[^.<>"\s@]+(?:\.[^.<>"\s@]+)+';
591 # check for a local address:
592 return $address if ($address =~ /^($local_part_regexp)$/);
594 $address =~ s/^\s*<(.*)>\s*$/$1/;
595 if ($have_email_valid) {
596 return scalar Email::Valid->address($address);
597 } else {
598 # less robust/correct than the monster regexp in Email::Valid,
599 # but still does a 99% job, and one less dependency
600 $address =~ /($local_part_regexp\@$domain_regexp)/;
601 return $1;
605 # Usually don't need to change anything below here.
607 # we make a "fake" message id by taking the current number
608 # of seconds since the beginning of Unix time and tacking on
609 # a random number to the end, in case we are called quicker than
610 # 1 second since the last time we were called.
612 # We'll setup a template for the message id, using the "from" address:
614 my ($message_id_stamp, $message_id_serial);
615 sub make_message_id
617 my $uniq;
618 if (!defined $message_id_stamp) {
619 $message_id_stamp = sprintf("%s-%s", time, $$);
620 $message_id_serial = 0;
622 $message_id_serial++;
623 $uniq = "$message_id_stamp-$message_id_serial";
625 my $du_part;
626 for ($sender, $repocommitter, $repoauthor) {
627 $du_part = extract_valid_address(sanitize_address($_));
628 last if (defined $du_part and $du_part ne '');
630 if (not defined $du_part or $du_part eq '') {
631 use Sys::Hostname qw();
632 $du_part = 'user@' . Sys::Hostname::hostname();
634 my $message_id_template = "<%s-git-send-email-%s>";
635 $message_id = sprintf($message_id_template, $uniq, $du_part);
636 #print "new message id = $message_id\n"; # Was useful for debugging
641 $time = time - scalar $#files;
643 sub unquote_rfc2047 {
644 local ($_) = @_;
645 my $encoding;
646 if (s/=\?([^?]+)\?q\?(.*)\?=/$2/g) {
647 $encoding = $1;
648 s/_/ /g;
649 s/=([0-9A-F]{2})/chr(hex($1))/eg;
651 return wantarray ? ($_, $encoding) : $_;
654 sub quote_rfc2047 {
655 local $_ = shift;
656 my $encoding = shift || 'utf-8';
657 s/([^-a-zA-Z0-9!*+\/])/sprintf("=%02X", ord($1))/eg;
658 s/(.*)/=\?$encoding\?q\?$1\?=/;
659 return $_;
662 # use the simplest quoting being able to handle the recipient
663 sub sanitize_address
665 my ($recipient) = @_;
666 my ($recipient_name, $recipient_addr) = ($recipient =~ /^(.*?)\s*(<.*)/);
668 if (not $recipient_name) {
669 return "$recipient";
672 # if recipient_name is already quoted, do nothing
673 if ($recipient_name =~ /^(".*"|=\?utf-8\?q\?.*\?=)$/) {
674 return $recipient;
677 # rfc2047 is needed if a non-ascii char is included
678 if ($recipient_name =~ /[^[:ascii:]]/) {
679 $recipient_name = quote_rfc2047($recipient_name);
682 # double quotes are needed if specials or CTLs are included
683 elsif ($recipient_name =~ /[][()<>@,;:\\".\000-\037\177]/) {
684 $recipient_name =~ s/(["\\\r])/\\$1/g;
685 $recipient_name = "\"$recipient_name\"";
688 return "$recipient_name $recipient_addr";
692 sub send_message
694 my @recipients = unique_email_list(@to);
695 @cc = (grep { my $cc = extract_valid_address($_);
696 not grep { $cc eq $_ } @recipients
698 map { sanitize_address($_) }
699 @cc);
700 my $to = join (",\n\t", @recipients);
701 @recipients = unique_email_list(@recipients,@cc,@bcclist);
702 @recipients = (map { extract_valid_address($_) } @recipients);
703 my $date = format_2822_time($time++);
704 my $gitversion = '@@GIT_VERSION@@';
705 if ($gitversion =~ m/..GIT_VERSION../) {
706 $gitversion = Git::version();
709 my $cc = join(", ", unique_email_list(@cc));
710 my $ccline = "";
711 if ($cc ne '') {
712 $ccline = "\nCc: $cc";
714 my $sanitized_sender = sanitize_address($sender);
715 make_message_id() unless defined($message_id);
717 my $header = "From: $sanitized_sender
718 To: $to${ccline}
719 Subject: $subject
720 Date: $date
721 Message-Id: $message_id
722 X-Mailer: git-send-email $gitversion
724 if ($thread && $reply_to) {
726 $header .= "In-Reply-To: $reply_to\n";
727 $header .= "References: $references\n";
729 if (@xh) {
730 $header .= join("\n", @xh) . "\n";
733 my @sendmail_parameters = ('-i', @recipients);
734 my $raw_from = $sanitized_sender;
735 $raw_from = $envelope_sender if (defined $envelope_sender);
736 $raw_from = extract_valid_address($raw_from);
737 unshift (@sendmail_parameters,
738 '-f', $raw_from) if(defined $envelope_sender);
740 if ($dry_run) {
741 # We don't want to send the email.
742 } elsif ($smtp_server =~ m#^/#) {
743 my $pid = open my $sm, '|-';
744 defined $pid or die $!;
745 if (!$pid) {
746 exec($smtp_server, @sendmail_parameters) or die $!;
748 print $sm "$header\n$message";
749 close $sm or die $?;
750 } else {
752 if (!defined $smtp_server) {
753 die "The required SMTP server is not properly defined."
756 if ($smtp_encryption eq 'ssl') {
757 $smtp_server_port ||= 465; # ssmtp
758 require Net::SMTP::SSL;
759 $smtp ||= Net::SMTP::SSL->new($smtp_server, Port => $smtp_server_port);
761 else {
762 require Net::SMTP;
763 $smtp ||= Net::SMTP->new((defined $smtp_server_port)
764 ? "$smtp_server:$smtp_server_port"
765 : $smtp_server);
766 if ($smtp_encryption eq 'tls') {
767 require Net::SMTP::SSL;
768 $smtp->command('STARTTLS');
769 $smtp->response();
770 if ($smtp->code == 220) {
771 $smtp = Net::SMTP::SSL->start_SSL($smtp)
772 or die "STARTTLS failed! ".$smtp->message;
773 } else {
774 die "Server does not support STARTTLS! ".$smtp->message;
779 if (!$smtp) {
780 die "Unable to initialize SMTP properly. Is there something wrong with your config?";
783 if (defined $smtp_authuser) {
785 if (!defined $smtp_authpass) {
787 system "stty -echo";
789 do {
790 print "Password: ";
791 $_ = <STDIN>;
792 print "\n";
793 } while (!defined $_);
795 chomp($smtp_authpass = $_);
797 system "stty echo";
800 $auth ||= $smtp->auth( $smtp_authuser, $smtp_authpass ) or die $smtp->message;
803 $smtp->mail( $raw_from ) or die $smtp->message;
804 $smtp->to( @recipients ) or die $smtp->message;
805 $smtp->data or die $smtp->message;
806 $smtp->datasend("$header\n$message") or die $smtp->message;
807 $smtp->dataend() or die $smtp->message;
808 $smtp->ok or die "Failed to send $subject\n".$smtp->message;
810 if ($quiet) {
811 printf (($dry_run ? "Dry-" : "")."Sent %s\n", $subject);
812 } else {
813 print (($dry_run ? "Dry-" : "")."OK. Log says:\n");
814 if ($smtp_server !~ m#^/#) {
815 print "Server: $smtp_server\n";
816 print "MAIL FROM:<$raw_from>\n";
817 print "RCPT TO:".join(',',(map { "<$_>" } @recipients))."\n";
818 } else {
819 print "Sendmail: $smtp_server ".join(' ',@sendmail_parameters)."\n";
821 print $header, "\n";
822 if ($smtp) {
823 print "Result: ", $smtp->code, ' ',
824 ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
825 } else {
826 print "Result: OK\n";
831 $reply_to = $initial_reply_to;
832 $references = $initial_reply_to || '';
833 $subject = $initial_subject;
835 foreach my $t (@files) {
836 open(F,"<",$t) or die "can't open file $t";
838 my $author = undef;
839 my $author_encoding;
840 my $has_content_type;
841 my $body_encoding;
842 @cc = @initial_cc;
843 @xh = ();
844 my $input_format = undef;
845 my $header_done = 0;
846 $message = "";
847 while(<F>) {
848 if (!$header_done) {
849 if (/^From /) {
850 $input_format = 'mbox';
851 next;
853 chomp;
854 if (!defined $input_format && /^[-A-Za-z]+:\s/) {
855 $input_format = 'mbox';
858 if (defined $input_format && $input_format eq 'mbox') {
859 if (/^Subject:\s+(.*)$/) {
860 $subject = $1;
862 } elsif (/^(Cc|From):\s+(.*)$/) {
863 if (unquote_rfc2047($2) eq $sender) {
864 next if ($suppress_cc{'self'});
866 elsif ($1 eq 'From') {
867 ($author, $author_encoding)
868 = unquote_rfc2047($2);
869 next if ($suppress_cc{'author'});
870 } else {
871 next if ($suppress_cc{'cc'});
873 printf("(mbox) Adding cc: %s from line '%s'\n",
874 $2, $_) unless $quiet;
875 push @cc, $2;
877 elsif (/^Content-type:/i) {
878 $has_content_type = 1;
879 if (/charset="?[^ "]+/) {
880 $body_encoding = $1;
882 push @xh, $_;
884 elsif (/^Message-Id: (.*)/i) {
885 $message_id = $1;
887 elsif (!/^Date:\s/ && /^[-A-Za-z]+:\s+\S/) {
888 push @xh, $_;
891 } else {
892 # In the traditional
893 # "send lots of email" format,
894 # line 1 = cc
895 # line 2 = subject
896 # So let's support that, too.
897 $input_format = 'lots';
898 if (@cc == 0 && !$suppress_cc{'cc'}) {
899 printf("(non-mbox) Adding cc: %s from line '%s'\n",
900 $_, $_) unless $quiet;
902 push @cc, $_;
904 } elsif (!defined $subject) {
905 $subject = $_;
909 # A whitespace line will terminate the headers
910 if (m/^\s*$/) {
911 $header_done = 1;
913 } else {
914 $message .= $_;
915 if (/^(Signed-off-by|Cc): (.*)$/i) {
916 next if ($suppress_cc{'sob'});
917 chomp;
918 my $c = $2;
919 chomp $c;
920 next if ($c eq $sender and $suppress_cc{'self'});
921 push @cc, $c;
922 printf("(sob) Adding cc: %s from line '%s'\n",
923 $c, $_) unless $quiet;
927 close F;
929 if (defined $cc_cmd && !$suppress_cc{'cccmd'}) {
930 open(F, "$cc_cmd $t |")
931 or die "(cc-cmd) Could not execute '$cc_cmd'";
932 while(<F>) {
933 my $c = $_;
934 $c =~ s/^\s*//g;
935 $c =~ s/\n$//g;
936 next if ($c eq $sender and $suppress_from);
937 push @cc, $c;
938 printf("(cc-cmd) Adding cc: %s from: '%s'\n",
939 $c, $cc_cmd) unless $quiet;
941 close F
942 or die "(cc-cmd) failed to close pipe to '$cc_cmd'";
945 if (defined $author) {
946 $message = "From: $author\n\n$message";
947 if (defined $author_encoding) {
948 if ($has_content_type) {
949 if ($body_encoding eq $author_encoding) {
950 # ok, we already have the right encoding
952 else {
953 # uh oh, we should re-encode
956 else {
957 push @xh,
958 'MIME-Version: 1.0',
959 "Content-Type: text/plain; charset=$author_encoding",
960 'Content-Transfer-Encoding: 8bit';
965 send_message();
967 # set up for the next message
968 if ($chain_reply_to || !defined $reply_to || length($reply_to) == 0) {
969 $reply_to = $message_id;
970 if (length $references > 0) {
971 $references .= "\n $message_id";
972 } else {
973 $references = "$message_id";
976 $message_id = undef;
979 if ($compose) {
980 cleanup_compose_files();
983 sub cleanup_compose_files() {
984 unlink($compose_filename, $compose_filename . ".final");
988 $smtp->quit if $smtp;
990 sub unique_email_list(@) {
991 my %seen;
992 my @emails;
994 foreach my $entry (@_) {
995 if (my $clean = extract_valid_address($entry)) {
996 $seen{$clean} ||= 0;
997 next if $seen{$clean}++;
998 push @emails, $entry;
999 } else {
1000 print STDERR "W: unable to extract a valid address",
1001 " from: $entry\n";
1004 return @emails;
1007 sub validate_patch {
1008 my $fn = shift;
1009 open(my $fh, '<', $fn)
1010 or die "unable to open $fn: $!\n";
1011 while (my $line = <$fh>) {
1012 if (length($line) > 998) {
1013 return "$.: patch contains a line longer than 998 characters";
1016 return undef;
1019 sub file_has_nonascii {
1020 my $fn = shift;
1021 open(my $fh, '<', $fn)
1022 or die "unable to open $fn: $!\n";
1023 while (my $line = <$fh>) {
1024 return 1 if $line =~ /[^[:ascii:]]/;
1026 return 0;