git send-email: interpret unknown files as revision lists
[git/dscho.git] / git-send-email.perl
blob6f5a61389818635d2bd48c13df5e70329a00d0e3
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 File::Temp qw/ tempdir /;
26 use Error qw(:try);
27 use Git;
29 Getopt::Long::Configure qw/ pass_through /;
31 package FakeTerm;
32 sub new {
33 my ($class, $reason) = @_;
34 return bless \$reason, shift;
36 sub readline {
37 my $self = shift;
38 die "Cannot use readline on FakeTerm: $$self";
40 package main;
43 sub usage {
44 print <<EOT;
45 git send-email [options] <file | directory | rev-list options >
47 Composing:
48 --from <str> * Email From:
49 --to <str> * Email To:
50 --cc <str> * Email Cc:
51 --bcc <str> * Email Bcc:
52 --subject <str> * Email "Subject:"
53 --in-reply-to <str> * Email "In-Reply-To:"
54 --compose * Open an editor for introduction.
56 Sending:
57 --envelope-sender <str> * Email envelope sender.
58 --smtp-server <str:int> * Outgoing SMTP server to use. The port
59 is optional. Default 'localhost'.
60 --smtp-server-port <int> * Outgoing SMTP server port.
61 --smtp-user <str> * Username for SMTP-AUTH.
62 --smtp-pass <str> * Password for SMTP-AUTH; not necessary.
63 --smtp-encryption <str> * tls or ssl; anything else disables.
64 --smtp-ssl * Deprecated. Use '--smtp-encryption ssl'.
66 Automating:
67 --identity <str> * Use the sendemail.<id> options.
68 --cc-cmd <str> * Email Cc: via `<str> \$patch_path`
69 --suppress-cc <str> * author, self, sob, cccmd, all.
70 --[no-]signed-off-by-cc * Send to Cc: and Signed-off-by:
71 addresses. Default on.
72 --[no-]suppress-from * Send to self. Default off.
73 --[no-]chain-reply-to * Chain In-Reply-To: fields. Default on.
74 --[no-]thread * Use In-Reply-To: field. Default on.
76 Administering:
77 --quiet * Output one line of info per email.
78 --dry-run * Don't actually send the emails.
79 --[no-]validate * Perform patch sanity checks. Default on.
80 --[no-]format-patch * understand any non optional arguments as
81 `git format-patch` ones.
83 EOT
84 exit(1);
87 # most mail servers generate the Date: header, but not all...
88 sub format_2822_time {
89 my ($time) = @_;
90 my @localtm = localtime($time);
91 my @gmttm = gmtime($time);
92 my $localmin = $localtm[1] + $localtm[2] * 60;
93 my $gmtmin = $gmttm[1] + $gmttm[2] * 60;
94 if ($localtm[0] != $gmttm[0]) {
95 die "local zone differs from GMT by a non-minute interval\n";
97 if ((($gmttm[6] + 1) % 7) == $localtm[6]) {
98 $localmin += 1440;
99 } elsif ((($gmttm[6] - 1) % 7) == $localtm[6]) {
100 $localmin -= 1440;
101 } elsif ($gmttm[6] != $localtm[6]) {
102 die "local time offset greater than or equal to 24 hours\n";
104 my $offset = $localmin - $gmtmin;
105 my $offhour = $offset / 60;
106 my $offmin = abs($offset % 60);
107 if (abs($offhour) >= 24) {
108 die ("local time offset greater than or equal to 24 hours\n");
111 return sprintf("%s, %2d %s %d %02d:%02d:%02d %s%02d%02d",
112 qw(Sun Mon Tue Wed Thu Fri Sat)[$localtm[6]],
113 $localtm[3],
114 qw(Jan Feb Mar Apr May Jun
115 Jul Aug Sep Oct Nov Dec)[$localtm[4]],
116 $localtm[5]+1900,
117 $localtm[2],
118 $localtm[1],
119 $localtm[0],
120 ($offset >= 0) ? '+' : '-',
121 abs($offhour),
122 $offmin,
126 my $have_email_valid = eval { require Email::Valid; 1 };
127 my $smtp;
128 my $auth;
130 sub unique_email_list(@);
131 sub cleanup_compose_files();
133 # Variables we fill in automatically, or via prompting:
134 my (@to,@cc,@initial_cc,@bcclist,@xh,
135 $initial_reply_to,$initial_subject,@files,$author,$sender,$smtp_authpass,$compose,$time);
137 my $envelope_sender;
139 # Example reply to:
140 #$initial_reply_to = ''; #<20050203173208.GA23964@foobar.com>';
142 my $repo = eval { Git->repository() };
143 my @repo = $repo ? ($repo) : ();
144 my $term = eval {
145 $ENV{"GIT_SEND_EMAIL_NOTTY"}
146 ? new Term::ReadLine 'git-send-email', \*STDIN, \*STDOUT
147 : new Term::ReadLine 'git-send-email';
149 if ($@) {
150 $term = new FakeTerm "$@: going non-interactive";
153 # Behavior modification variables
154 my ($quiet, $dry_run) = (0, 0);
155 my $format_patch;
156 my $compose_filename = $repo->repo_path() . "/.gitsendemail.msg.$$";
158 # Variables with corresponding config settings
159 my ($thread, $chain_reply_to, $suppress_from, $signed_off_by_cc, $cc_cmd);
160 my ($smtp_server, $smtp_server_port, $smtp_authuser, $smtp_encryption);
161 my ($identity, $aliasfiletype, @alias_files, @smtp_host_parts);
162 my ($validate);
163 my (@suppress_cc);
165 my %config_bool_settings = (
166 "thread" => [\$thread, 1],
167 "chainreplyto" => [\$chain_reply_to, 1],
168 "suppressfrom" => [\$suppress_from, undef],
169 "signedoffbycc" => [\$signed_off_by_cc, undef],
170 "signedoffcc" => [\$signed_off_by_cc, undef], # Deprecated
171 "validate" => [\$validate, 1],
174 my %config_settings = (
175 "smtpserver" => \$smtp_server,
176 "smtpserverport" => \$smtp_server_port,
177 "smtpuser" => \$smtp_authuser,
178 "smtppass" => \$smtp_authpass,
179 "to" => \@to,
180 "cc" => \@initial_cc,
181 "cccmd" => \$cc_cmd,
182 "aliasfiletype" => \$aliasfiletype,
183 "bcc" => \@bcclist,
184 "aliasesfile" => \@alias_files,
185 "suppresscc" => \@suppress_cc,
186 "envelopesender" => \$envelope_sender,
189 # Handle Uncouth Termination
190 sub signal_handler {
192 # Make text normal
193 print color("reset"), "\n";
195 # SMTP password masked
196 system "stty echo";
198 # tmp files from --compose
199 if (-e $compose_filename) {
200 print "'$compose_filename' contains an intermediate version of the email you were composing.\n";
202 if (-e ($compose_filename . ".final")) {
203 print "'$compose_filename.final' contains the composed email.\n"
206 exit;
209 $SIG{TERM} = \&signal_handler;
210 $SIG{INT} = \&signal_handler;
212 # Begin by accumulating all the variables (defined above), that we will end up
213 # needing, first, from the command line:
215 my $rc = GetOptions("sender|from=s" => \$sender,
216 "in-reply-to=s" => \$initial_reply_to,
217 "subject=s" => \$initial_subject,
218 "to=s" => \@to,
219 "cc=s" => \@initial_cc,
220 "bcc=s" => \@bcclist,
221 "chain-reply-to!" => \$chain_reply_to,
222 "smtp-server=s" => \$smtp_server,
223 "smtp-server-port=s" => \$smtp_server_port,
224 "smtp-user=s" => \$smtp_authuser,
225 "smtp-pass:s" => \$smtp_authpass,
226 "smtp-ssl" => sub { $smtp_encryption = 'ssl' },
227 "smtp-encryption=s" => \$smtp_encryption,
228 "identity=s" => \$identity,
229 "compose" => \$compose,
230 "quiet" => \$quiet,
231 "cc-cmd=s" => \$cc_cmd,
232 "suppress-from!" => \$suppress_from,
233 "suppress-cc=s" => \@suppress_cc,
234 "signed-off-cc|signed-off-by-cc!" => \$signed_off_by_cc,
235 "dry-run" => \$dry_run,
236 "envelope-sender=s" => \$envelope_sender,
237 "thread!" => \$thread,
238 "validate!" => \$validate,
239 "format-patch!" => \$format_patch,
242 unless ($rc) {
243 usage();
246 # Now, let's fill any that aren't set in with defaults:
248 sub read_config {
249 my ($prefix) = @_;
251 foreach my $setting (keys %config_bool_settings) {
252 my $target = $config_bool_settings{$setting}->[0];
253 $$target = Git::config_bool(@repo, "$prefix.$setting") unless (defined $$target);
256 foreach my $setting (keys %config_settings) {
257 my $target = $config_settings{$setting};
258 if (ref($target) eq "ARRAY") {
259 unless (@$target) {
260 my @values = Git::config(@repo, "$prefix.$setting");
261 @$target = @values if (@values && defined $values[0]);
264 else {
265 $$target = Git::config(@repo, "$prefix.$setting") unless (defined $$target);
269 if (!defined $smtp_encryption) {
270 my $enc = Git::config(@repo, "$prefix.smtpencryption");
271 if (defined $enc) {
272 $smtp_encryption = $enc;
273 } elsif (Git::config_bool(@repo, "$prefix.smtpssl")) {
274 $smtp_encryption = 'ssl';
279 # read configuration from [sendemail "$identity"], fall back on [sendemail]
280 $identity = Git::config(@repo, "sendemail.identity") unless (defined $identity);
281 read_config("sendemail.$identity") if (defined $identity);
282 read_config("sendemail");
284 # fall back on builtin bool defaults
285 foreach my $setting (values %config_bool_settings) {
286 ${$setting->[0]} = $setting->[1] unless (defined (${$setting->[0]}));
289 # 'default' encryption is none -- this only prevents a warning
290 $smtp_encryption = '' unless (defined $smtp_encryption);
292 # Set CC suppressions
293 my(%suppress_cc);
294 if (@suppress_cc) {
295 foreach my $entry (@suppress_cc) {
296 die "Unknown --suppress-cc field: '$entry'\n"
297 unless $entry =~ /^(all|cccmd|cc|author|self|sob)$/;
298 $suppress_cc{$entry} = 1;
302 if ($suppress_cc{'all'}) {
303 foreach my $entry (qw (ccmd cc author self sob)) {
304 $suppress_cc{$entry} = 1;
306 delete $suppress_cc{'all'};
309 # If explicit old-style ones are specified, they trump --suppress-cc.
310 $suppress_cc{'self'} = $suppress_from if defined $suppress_from;
311 $suppress_cc{'sob'} = !$signed_off_by_cc if defined $signed_off_by_cc;
313 # Debugging, print out the suppressions.
314 if (0) {
315 print "suppressions:\n";
316 foreach my $entry (keys %suppress_cc) {
317 printf " %-5s -> $suppress_cc{$entry}\n", $entry;
321 my ($repoauthor, $repocommitter);
322 ($repoauthor) = Git::ident_person(@repo, 'author');
323 ($repocommitter) = Git::ident_person(@repo, 'committer');
325 # Verify the user input
327 foreach my $entry (@to) {
328 die "Comma in --to entry: $entry'\n" unless $entry !~ m/,/;
331 foreach my $entry (@initial_cc) {
332 die "Comma in --cc entry: $entry'\n" unless $entry !~ m/,/;
335 foreach my $entry (@bcclist) {
336 die "Comma in --bcclist entry: $entry'\n" unless $entry !~ m/,/;
339 my %aliases;
340 my %parse_alias = (
341 # multiline formats can be supported in the future
342 mutt => sub { my $fh = shift; while (<$fh>) {
343 if (/^\s*alias\s+(\S+)\s+(.*)$/) {
344 my ($alias, $addr) = ($1, $2);
345 $addr =~ s/#.*$//; # mutt allows # comments
346 # commas delimit multiple addresses
347 $aliases{$alias} = [ split(/\s*,\s*/, $addr) ];
348 }}},
349 mailrc => sub { my $fh = shift; while (<$fh>) {
350 if (/^alias\s+(\S+)\s+(.*)$/) {
351 # spaces delimit multiple addresses
352 $aliases{$1} = [ split(/\s+/, $2) ];
353 }}},
354 pine => sub { my $fh = shift; while (<$fh>) {
355 if (/^(\S+)\t.*\t(.*)$/) {
356 $aliases{$1} = [ split(/\s*,\s*/, $2) ];
357 }}},
358 gnus => sub { my $fh = shift; while (<$fh>) {
359 if (/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) {
360 $aliases{$1} = [ $2 ];
364 if (@alias_files and $aliasfiletype and defined $parse_alias{$aliasfiletype}) {
365 foreach my $file (@alias_files) {
366 open my $fh, '<', $file or die "opening $file: $!\n";
367 $parse_alias{$aliasfiletype}->($fh);
368 close $fh;
372 ($sender) = expand_aliases($sender) if defined $sender;
374 # returns 1 if the conflict must be solved using it as a format-patch argument
375 sub check_file_rev_conflict($) {
376 my $f = shift;
377 try {
378 $repo->command('rev-parse', '--verify', '--quiet', $f);
379 if (defined($format_patch)) {
380 print "foo\n";
381 return $format_patch;
383 die(<<EOF);
384 File '$f' exists but it could also be the range of commits
385 to produce patches for. Please disambiguate by...
387 * Saying "./$f" if you mean a file; or
388 * Giving --format-patch option if you mean a range.
390 } catch Git::Error::Command with {
391 return 0;
395 # Now that all the defaults are set, process the rest of the command line
396 # arguments and collect up the files that need to be processed.
397 my @rev_list_opts;
398 while (my $f = pop @ARGV) {
399 if ($f eq "--") {
400 push @rev_list_opts, "--", @ARGV;
401 @ARGV = ();
402 } elsif (-d $f and !check_file_rev_conflict($f)) {
403 opendir(DH,$f)
404 or die "Failed to opendir $f: $!";
406 push @files, grep { -f $_ } map { +$f . "/" . $_ }
407 sort readdir(DH);
408 closedir(DH);
409 } elsif ((-f $f or -p $f) and !check_file_rev_conflict($f)) {
410 push @files, $f;
411 } else {
412 push @rev_list_opts, $f;
416 if (@rev_list_opts) {
417 push @files, $repo->command('format-patch', '-o', tempdir(CLEANUP => 1), @rev_list_opts);
420 if ($validate) {
421 foreach my $f (@files) {
422 unless (-p $f) {
423 my $error = validate_patch($f);
424 $error and die "fatal: $f: $error\nwarning: no patches were sent\n";
429 if (@files) {
430 unless ($quiet) {
431 print $_,"\n" for (@files);
433 } else {
434 print STDERR "\nNo patch files specified!\n\n";
435 usage();
438 my $prompting = 0;
439 if (!defined $sender) {
440 $sender = $repoauthor || $repocommitter || '';
442 while (1) {
443 $_ = $term->readline("Who should the emails appear to be from? [$sender] ");
444 last if defined $_;
445 print "\n";
448 $sender = $_ if ($_);
449 print "Emails will be sent from: ", $sender, "\n";
450 $prompting++;
453 if (!@to) {
456 while (1) {
457 $_ = $term->readline("Who should the emails be sent to? ", "");
458 last if defined $_;
459 print "\n";
462 my $to = $_;
463 push @to, split /,\s*/, $to;
464 $prompting++;
467 sub expand_aliases {
468 my @cur = @_;
469 my @last;
470 do {
471 @last = @cur;
472 @cur = map { $aliases{$_} ? @{$aliases{$_}} : $_ } @last;
473 } while (join(',',@cur) ne join(',',@last));
474 return @cur;
477 @to = expand_aliases(@to);
478 @to = (map { sanitize_address($_) } @to);
479 @initial_cc = expand_aliases(@initial_cc);
480 @bcclist = expand_aliases(@bcclist);
482 if (!defined $initial_subject && $compose) {
483 while (1) {
484 $_ = $term->readline("What subject should the initial email start with? ", $initial_subject);
485 last if defined $_;
486 print "\n";
489 $initial_subject = $_;
490 $prompting++;
493 if ($thread && !defined $initial_reply_to && $prompting) {
494 while (1) {
495 $_= $term->readline("Message-ID to be used as In-Reply-To for the first email? ", $initial_reply_to);
496 last if defined $_;
497 print "\n";
500 $initial_reply_to = $_;
502 if (defined $initial_reply_to) {
503 $initial_reply_to =~ s/^\s*<?//;
504 $initial_reply_to =~ s/>?\s*$//;
505 $initial_reply_to = "<$initial_reply_to>" if $initial_reply_to ne '';
508 if (!defined $smtp_server) {
509 foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
510 if (-x $_) {
511 $smtp_server = $_;
512 last;
515 $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
518 if ($compose) {
519 # Note that this does not need to be secure, but we will make a small
520 # effort to have it be unique
521 open(C,">",$compose_filename)
522 or die "Failed to open for writing $compose_filename: $!";
523 print C "From $sender # This line is ignored.\n";
524 printf C "Subject: %s\n\n", $initial_subject;
525 printf C <<EOT;
526 GIT: Please enter your email below.
527 GIT: Lines beginning in "GIT: " will be removed.
528 GIT: Consider including an overall diffstat or table of contents
529 GIT: for the patch you are writing.
532 close(C);
534 my $editor = $ENV{GIT_EDITOR} || Git::config(@repo, "core.editor") || $ENV{VISUAL} || $ENV{EDITOR} || "vi";
535 system('sh', '-c', $editor.' "$@"', $editor, $compose_filename);
537 open(C2,">",$compose_filename . ".final")
538 or die "Failed to open $compose_filename.final : " . $!;
540 open(C,"<",$compose_filename)
541 or die "Failed to open $compose_filename : " . $!;
543 my $need_8bit_cte = file_has_nonascii($compose_filename);
544 my $in_body = 0;
545 while(<C>) {
546 next if m/^GIT: /;
547 if (!$in_body && /^\n$/) {
548 $in_body = 1;
549 if ($need_8bit_cte) {
550 print C2 "MIME-Version: 1.0\n",
551 "Content-Type: text/plain; ",
552 "charset=utf-8\n",
553 "Content-Transfer-Encoding: 8bit\n";
556 if (!$in_body && /^MIME-Version:/i) {
557 $need_8bit_cte = 0;
559 if (!$in_body && /^Subject: ?(.*)/i) {
560 my $subject = $1;
561 $_ = "Subject: " .
562 ($subject =~ /[^[:ascii:]]/ ?
563 quote_rfc2047($subject) :
564 $subject) .
565 "\n";
567 print C2 $_;
569 close(C);
570 close(C2);
572 while (1) {
573 $_ = $term->readline("Send this email? (y|n) ");
574 last if defined $_;
575 print "\n";
578 if (uc substr($_,0,1) ne 'Y') {
579 cleanup_compose_files();
580 exit(0);
583 @files = ($compose_filename . ".final", @files);
586 # Variables we set as part of the loop over files
587 our ($message_id, %mail, $subject, $reply_to, $references, $message);
589 sub extract_valid_address {
590 my $address = shift;
591 my $local_part_regexp = '[^<>"\s@]+';
592 my $domain_regexp = '[^.<>"\s@]+(?:\.[^.<>"\s@]+)+';
594 # check for a local address:
595 return $address if ($address =~ /^($local_part_regexp)$/);
597 $address =~ s/^\s*<(.*)>\s*$/$1/;
598 if ($have_email_valid) {
599 return scalar Email::Valid->address($address);
600 } else {
601 # less robust/correct than the monster regexp in Email::Valid,
602 # but still does a 99% job, and one less dependency
603 $address =~ /($local_part_regexp\@$domain_regexp)/;
604 return $1;
608 # Usually don't need to change anything below here.
610 # we make a "fake" message id by taking the current number
611 # of seconds since the beginning of Unix time and tacking on
612 # a random number to the end, in case we are called quicker than
613 # 1 second since the last time we were called.
615 # We'll setup a template for the message id, using the "from" address:
617 my ($message_id_stamp, $message_id_serial);
618 sub make_message_id
620 my $uniq;
621 if (!defined $message_id_stamp) {
622 $message_id_stamp = sprintf("%s-%s", time, $$);
623 $message_id_serial = 0;
625 $message_id_serial++;
626 $uniq = "$message_id_stamp-$message_id_serial";
628 my $du_part;
629 for ($sender, $repocommitter, $repoauthor) {
630 $du_part = extract_valid_address(sanitize_address($_));
631 last if (defined $du_part and $du_part ne '');
633 if (not defined $du_part or $du_part eq '') {
634 use Sys::Hostname qw();
635 $du_part = 'user@' . Sys::Hostname::hostname();
637 my $message_id_template = "<%s-git-send-email-%s>";
638 $message_id = sprintf($message_id_template, $uniq, $du_part);
639 #print "new message id = $message_id\n"; # Was useful for debugging
644 $time = time - scalar $#files;
646 sub unquote_rfc2047 {
647 local ($_) = @_;
648 my $encoding;
649 if (s/=\?([^?]+)\?q\?(.*)\?=/$2/g) {
650 $encoding = $1;
651 s/_/ /g;
652 s/=([0-9A-F]{2})/chr(hex($1))/eg;
654 return wantarray ? ($_, $encoding) : $_;
657 sub quote_rfc2047 {
658 local $_ = shift;
659 my $encoding = shift || 'utf-8';
660 s/([^-a-zA-Z0-9!*+\/])/sprintf("=%02X", ord($1))/eg;
661 s/(.*)/=\?$encoding\?q\?$1\?=/;
662 return $_;
665 # use the simplest quoting being able to handle the recipient
666 sub sanitize_address
668 my ($recipient) = @_;
669 my ($recipient_name, $recipient_addr) = ($recipient =~ /^(.*?)\s*(<.*)/);
671 if (not $recipient_name) {
672 return "$recipient";
675 # if recipient_name is already quoted, do nothing
676 if ($recipient_name =~ /^(".*"|=\?utf-8\?q\?.*\?=)$/) {
677 return $recipient;
680 # rfc2047 is needed if a non-ascii char is included
681 if ($recipient_name =~ /[^[:ascii:]]/) {
682 $recipient_name = quote_rfc2047($recipient_name);
685 # double quotes are needed if specials or CTLs are included
686 elsif ($recipient_name =~ /[][()<>@,;:\\".\000-\037\177]/) {
687 $recipient_name =~ s/(["\\\r])/\\$1/g;
688 $recipient_name = "\"$recipient_name\"";
691 return "$recipient_name $recipient_addr";
695 sub send_message
697 my @recipients = unique_email_list(@to);
698 @cc = (grep { my $cc = extract_valid_address($_);
699 not grep { $cc eq $_ } @recipients
701 map { sanitize_address($_) }
702 @cc);
703 my $to = join (",\n\t", @recipients);
704 @recipients = unique_email_list(@recipients,@cc,@bcclist);
705 @recipients = (map { extract_valid_address($_) } @recipients);
706 my $date = format_2822_time($time++);
707 my $gitversion = '@@GIT_VERSION@@';
708 if ($gitversion =~ m/..GIT_VERSION../) {
709 $gitversion = Git::version();
712 my $cc = join(", ", unique_email_list(@cc));
713 my $ccline = "";
714 if ($cc ne '') {
715 $ccline = "\nCc: $cc";
717 my $sanitized_sender = sanitize_address($sender);
718 make_message_id() unless defined($message_id);
720 my $header = "From: $sanitized_sender
721 To: $to${ccline}
722 Subject: $subject
723 Date: $date
724 Message-Id: $message_id
725 X-Mailer: git-send-email $gitversion
727 if ($thread && $reply_to) {
729 $header .= "In-Reply-To: $reply_to\n";
730 $header .= "References: $references\n";
732 if (@xh) {
733 $header .= join("\n", @xh) . "\n";
736 my @sendmail_parameters = ('-i', @recipients);
737 my $raw_from = $sanitized_sender;
738 $raw_from = $envelope_sender if (defined $envelope_sender);
739 $raw_from = extract_valid_address($raw_from);
740 unshift (@sendmail_parameters,
741 '-f', $raw_from) if(defined $envelope_sender);
743 if ($dry_run) {
744 # We don't want to send the email.
745 } elsif ($smtp_server =~ m#^/#) {
746 my $pid = open my $sm, '|-';
747 defined $pid or die $!;
748 if (!$pid) {
749 exec($smtp_server, @sendmail_parameters) or die $!;
751 print $sm "$header\n$message";
752 close $sm or die $?;
753 } else {
755 if (!defined $smtp_server) {
756 die "The required SMTP server is not properly defined."
759 if ($smtp_encryption eq 'ssl') {
760 $smtp_server_port ||= 465; # ssmtp
761 require Net::SMTP::SSL;
762 $smtp ||= Net::SMTP::SSL->new($smtp_server, Port => $smtp_server_port);
764 else {
765 require Net::SMTP;
766 $smtp ||= Net::SMTP->new((defined $smtp_server_port)
767 ? "$smtp_server:$smtp_server_port"
768 : $smtp_server);
769 if ($smtp_encryption eq 'tls') {
770 require Net::SMTP::SSL;
771 $smtp->command('STARTTLS');
772 $smtp->response();
773 if ($smtp->code == 220) {
774 $smtp = Net::SMTP::SSL->start_SSL($smtp)
775 or die "STARTTLS failed! ".$smtp->message;
776 $smtp_encryption = '';
777 # Send EHLO again to receive fresh
778 # supported commands
779 $smtp->hello();
780 } else {
781 die "Server does not support STARTTLS! ".$smtp->message;
786 if (!$smtp) {
787 die "Unable to initialize SMTP properly. Is there something wrong with your config?";
790 if (defined $smtp_authuser) {
792 if (!defined $smtp_authpass) {
794 system "stty -echo";
796 do {
797 print "Password: ";
798 $_ = <STDIN>;
799 print "\n";
800 } while (!defined $_);
802 chomp($smtp_authpass = $_);
804 system "stty echo";
807 $auth ||= $smtp->auth( $smtp_authuser, $smtp_authpass ) or die $smtp->message;
810 $smtp->mail( $raw_from ) or die $smtp->message;
811 $smtp->to( @recipients ) or die $smtp->message;
812 $smtp->data or die $smtp->message;
813 $smtp->datasend("$header\n$message") or die $smtp->message;
814 $smtp->dataend() or die $smtp->message;
815 $smtp->ok or die "Failed to send $subject\n".$smtp->message;
817 if ($quiet) {
818 printf (($dry_run ? "Dry-" : "")."Sent %s\n", $subject);
819 } else {
820 print (($dry_run ? "Dry-" : "")."OK. Log says:\n");
821 if ($smtp_server !~ m#^/#) {
822 print "Server: $smtp_server\n";
823 print "MAIL FROM:<$raw_from>\n";
824 print "RCPT TO:".join(',',(map { "<$_>" } @recipients))."\n";
825 } else {
826 print "Sendmail: $smtp_server ".join(' ',@sendmail_parameters)."\n";
828 print $header, "\n";
829 if ($smtp) {
830 print "Result: ", $smtp->code, ' ',
831 ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
832 } else {
833 print "Result: OK\n";
838 $reply_to = $initial_reply_to;
839 $references = $initial_reply_to || '';
840 $subject = $initial_subject;
842 foreach my $t (@files) {
843 open(F,"<",$t) or die "can't open file $t";
845 my $author = undef;
846 my $author_encoding;
847 my $has_content_type;
848 my $body_encoding;
849 @cc = @initial_cc;
850 @xh = ();
851 my $input_format = undef;
852 my $header_done = 0;
853 $message = "";
854 while(<F>) {
855 if (!$header_done) {
856 if (/^From /) {
857 $input_format = 'mbox';
858 next;
860 chomp;
861 if (!defined $input_format && /^[-A-Za-z]+:\s/) {
862 $input_format = 'mbox';
865 if (defined $input_format && $input_format eq 'mbox') {
866 if (/^Subject:\s+(.*)$/) {
867 $subject = $1;
869 } elsif (/^(Cc|From):\s+(.*)$/) {
870 if (unquote_rfc2047($2) eq $sender) {
871 next if ($suppress_cc{'self'});
873 elsif ($1 eq 'From') {
874 ($author, $author_encoding)
875 = unquote_rfc2047($2);
876 next if ($suppress_cc{'author'});
877 } else {
878 next if ($suppress_cc{'cc'});
880 printf("(mbox) Adding cc: %s from line '%s'\n",
881 $2, $_) unless $quiet;
882 push @cc, $2;
884 elsif (/^Content-type:/i) {
885 $has_content_type = 1;
886 if (/charset="?([^ "]+)/) {
887 $body_encoding = $1;
889 push @xh, $_;
891 elsif (/^Message-Id: (.*)/i) {
892 $message_id = $1;
894 elsif (!/^Date:\s/ && /^[-A-Za-z]+:\s+\S/) {
895 push @xh, $_;
898 } else {
899 # In the traditional
900 # "send lots of email" format,
901 # line 1 = cc
902 # line 2 = subject
903 # So let's support that, too.
904 $input_format = 'lots';
905 if (@cc == 0 && !$suppress_cc{'cc'}) {
906 printf("(non-mbox) Adding cc: %s from line '%s'\n",
907 $_, $_) unless $quiet;
909 push @cc, $_;
911 } elsif (!defined $subject) {
912 $subject = $_;
916 # A whitespace line will terminate the headers
917 if (m/^\s*$/) {
918 $header_done = 1;
920 } else {
921 $message .= $_;
922 if (/^(Signed-off-by|Cc): (.*)$/i) {
923 next if ($suppress_cc{'sob'});
924 chomp;
925 my $c = $2;
926 chomp $c;
927 next if ($c eq $sender and $suppress_cc{'self'});
928 push @cc, $c;
929 printf("(sob) Adding cc: %s from line '%s'\n",
930 $c, $_) unless $quiet;
934 close F;
936 if (defined $cc_cmd && !$suppress_cc{'cccmd'}) {
937 open(F, "$cc_cmd $t |")
938 or die "(cc-cmd) Could not execute '$cc_cmd'";
939 while(<F>) {
940 my $c = $_;
941 $c =~ s/^\s*//g;
942 $c =~ s/\n$//g;
943 next if ($c eq $sender and $suppress_from);
944 push @cc, $c;
945 printf("(cc-cmd) Adding cc: %s from: '%s'\n",
946 $c, $cc_cmd) unless $quiet;
948 close F
949 or die "(cc-cmd) failed to close pipe to '$cc_cmd'";
952 if (defined $author) {
953 $message = "From: $author\n\n$message";
954 if (defined $author_encoding) {
955 if ($has_content_type) {
956 if ($body_encoding eq $author_encoding) {
957 # ok, we already have the right encoding
959 else {
960 # uh oh, we should re-encode
963 else {
964 push @xh,
965 'MIME-Version: 1.0',
966 "Content-Type: text/plain; charset=$author_encoding",
967 'Content-Transfer-Encoding: 8bit';
972 send_message();
974 # set up for the next message
975 if ($chain_reply_to || !defined $reply_to || length($reply_to) == 0) {
976 $reply_to = $message_id;
977 if (length $references > 0) {
978 $references .= "\n $message_id";
979 } else {
980 $references = "$message_id";
983 $message_id = undef;
986 if ($compose) {
987 cleanup_compose_files();
990 sub cleanup_compose_files() {
991 unlink($compose_filename, $compose_filename . ".final");
995 $smtp->quit if $smtp;
997 sub unique_email_list(@) {
998 my %seen;
999 my @emails;
1001 foreach my $entry (@_) {
1002 if (my $clean = extract_valid_address($entry)) {
1003 $seen{$clean} ||= 0;
1004 next if $seen{$clean}++;
1005 push @emails, $entry;
1006 } else {
1007 print STDERR "W: unable to extract a valid address",
1008 " from: $entry\n";
1011 return @emails;
1014 sub validate_patch {
1015 my $fn = shift;
1016 open(my $fh, '<', $fn)
1017 or die "unable to open $fn: $!\n";
1018 while (my $line = <$fh>) {
1019 if (length($line) > 998) {
1020 return "$.: patch contains a line longer than 998 characters";
1023 return undef;
1026 sub file_has_nonascii {
1027 my $fn = shift;
1028 open(my $fh, '<', $fn)
1029 or die "unable to open $fn: $!\n";
1030 while (my $line = <$fh>) {
1031 return 1 if $line =~ /[^[:ascii:]]/;
1033 return 0;