Merge branch 'jn/t7006-fixup'
[git/kirr.git] / git-send-email.perl
blob111c981229bf2c0bc6afa4a22db011b68d93fdfa
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 Text::ParseWords;
24 use Data::Dumper;
25 use Term::ANSIColor;
26 use File::Temp qw/ tempdir tempfile /;
27 use Error qw(:try);
28 use Git;
30 Getopt::Long::Configure qw/ pass_through /;
32 package FakeTerm;
33 sub new {
34 my ($class, $reason) = @_;
35 return bless \$reason, shift;
37 sub readline {
38 my $self = shift;
39 die "Cannot use readline on FakeTerm: $$self";
41 package main;
44 sub usage {
45 print <<EOT;
46 git send-email [options] <file | directory | rev-list options >
48 Composing:
49 --from <str> * Email From:
50 --[no-]to <str> * Email To:
51 --[no-]cc <str> * Email Cc:
52 --[no-]bcc <str> * Email Bcc:
53 --subject <str> * Email "Subject:"
54 --in-reply-to <str> * Email "In-Reply-To:"
55 --annotate * Review each patch that will be sent in an editor.
56 --compose * Open an editor for introduction.
58 Sending:
59 --envelope-sender <str> * Email envelope sender.
60 --smtp-server <str:int> * Outgoing SMTP server to use. The port
61 is optional. Default 'localhost'.
62 --smtp-server-port <int> * Outgoing SMTP server port.
63 --smtp-user <str> * Username for SMTP-AUTH.
64 --smtp-pass <str> * Password for SMTP-AUTH; not necessary.
65 --smtp-encryption <str> * tls or ssl; anything else disables.
66 --smtp-ssl * Deprecated. Use '--smtp-encryption ssl'.
67 --smtp-domain <str> * The domain name sent to HELO/EHLO handshake
68 --smtp-debug <0|1> * Disable, enable Net::SMTP debug.
70 Automating:
71 --identity <str> * Use the sendemail.<id> options.
72 --cc-cmd <str> * Email Cc: via `<str> \$patch_path`
73 --suppress-cc <str> * author, self, sob, cc, cccmd, body, bodycc, all.
74 --[no-]signed-off-by-cc * Send to Signed-off-by: addresses. Default on.
75 --[no-]suppress-from * Send to self. Default off.
76 --[no-]chain-reply-to * Chain In-Reply-To: fields. Default off.
77 --[no-]thread * Use In-Reply-To: field. Default on.
79 Administering:
80 --confirm <str> * Confirm recipients before sending;
81 auto, cc, compose, always, or never.
82 --quiet * Output one line of info per email.
83 --dry-run * Don't actually send the emails.
84 --[no-]validate * Perform patch sanity checks. Default on.
85 --[no-]format-patch * understand any non optional arguments as
86 `git format-patch` ones.
88 EOT
89 exit(1);
92 # most mail servers generate the Date: header, but not all...
93 sub format_2822_time {
94 my ($time) = @_;
95 my @localtm = localtime($time);
96 my @gmttm = gmtime($time);
97 my $localmin = $localtm[1] + $localtm[2] * 60;
98 my $gmtmin = $gmttm[1] + $gmttm[2] * 60;
99 if ($localtm[0] != $gmttm[0]) {
100 die "local zone differs from GMT by a non-minute interval\n";
102 if ((($gmttm[6] + 1) % 7) == $localtm[6]) {
103 $localmin += 1440;
104 } elsif ((($gmttm[6] - 1) % 7) == $localtm[6]) {
105 $localmin -= 1440;
106 } elsif ($gmttm[6] != $localtm[6]) {
107 die "local time offset greater than or equal to 24 hours\n";
109 my $offset = $localmin - $gmtmin;
110 my $offhour = $offset / 60;
111 my $offmin = abs($offset % 60);
112 if (abs($offhour) >= 24) {
113 die ("local time offset greater than or equal to 24 hours\n");
116 return sprintf("%s, %2d %s %d %02d:%02d:%02d %s%02d%02d",
117 qw(Sun Mon Tue Wed Thu Fri Sat)[$localtm[6]],
118 $localtm[3],
119 qw(Jan Feb Mar Apr May Jun
120 Jul Aug Sep Oct Nov Dec)[$localtm[4]],
121 $localtm[5]+1900,
122 $localtm[2],
123 $localtm[1],
124 $localtm[0],
125 ($offset >= 0) ? '+' : '-',
126 abs($offhour),
127 $offmin,
131 my $have_email_valid = eval { require Email::Valid; 1 };
132 my $have_mail_address = eval { require Mail::Address; 1 };
133 my $smtp;
134 my $auth;
136 sub unique_email_list(@);
137 sub cleanup_compose_files();
139 # Variables we fill in automatically, or via prompting:
140 my (@to,$no_to,@cc,$no_cc,@initial_cc,@bcclist,$no_bcc,@xh,
141 $initial_reply_to,$initial_subject,@files,
142 $author,$sender,$smtp_authpass,$annotate,$compose,$time);
144 my $envelope_sender;
146 # Example reply to:
147 #$initial_reply_to = ''; #<20050203173208.GA23964@foobar.com>';
149 my $repo = eval { Git->repository() };
150 my @repo = $repo ? ($repo) : ();
151 my $term = eval {
152 $ENV{"GIT_SEND_EMAIL_NOTTY"}
153 ? new Term::ReadLine 'git-send-email', \*STDIN, \*STDOUT
154 : new Term::ReadLine 'git-send-email';
156 if ($@) {
157 $term = new FakeTerm "$@: going non-interactive";
160 # Behavior modification variables
161 my ($quiet, $dry_run) = (0, 0);
162 my $format_patch;
163 my $compose_filename;
165 # Handle interactive edition of files.
166 my $multiedit;
167 my $editor;
169 sub do_edit {
170 if (!defined($editor)) {
171 $editor = Git::command_oneline('var', 'GIT_EDITOR');
173 if (defined($multiedit) && !$multiedit) {
174 map {
175 system('sh', '-c', $editor.' "$@"', $editor, $_);
176 if (($? & 127) || ($? >> 8)) {
177 die("the editor exited uncleanly, aborting everything");
179 } @_;
180 } else {
181 system('sh', '-c', $editor.' "$@"', $editor, @_);
182 if (($? & 127) || ($? >> 8)) {
183 die("the editor exited uncleanly, aborting everything");
188 # Variables with corresponding config settings
189 my ($thread, $chain_reply_to, $suppress_from, $signed_off_by_cc, $cc_cmd);
190 my ($smtp_server, $smtp_server_port, $smtp_authuser, $smtp_encryption);
191 my ($identity, $aliasfiletype, @alias_files, @smtp_host_parts, $smtp_domain);
192 my ($validate, $confirm);
193 my (@suppress_cc);
195 my ($debug_net_smtp) = 0; # Net::SMTP, see send_message()
197 my $not_set_by_user = "true but not set by the user";
199 my %config_bool_settings = (
200 "thread" => [\$thread, 1],
201 "chainreplyto" => [\$chain_reply_to, $not_set_by_user],
202 "suppressfrom" => [\$suppress_from, undef],
203 "signedoffbycc" => [\$signed_off_by_cc, undef],
204 "signedoffcc" => [\$signed_off_by_cc, undef], # Deprecated
205 "validate" => [\$validate, 1],
208 my %config_settings = (
209 "smtpserver" => \$smtp_server,
210 "smtpserverport" => \$smtp_server_port,
211 "smtpuser" => \$smtp_authuser,
212 "smtppass" => \$smtp_authpass,
213 "smtpdomain" => \$smtp_domain,
214 "to" => \@to,
215 "cc" => \@initial_cc,
216 "cccmd" => \$cc_cmd,
217 "aliasfiletype" => \$aliasfiletype,
218 "bcc" => \@bcclist,
219 "aliasesfile" => \@alias_files,
220 "suppresscc" => \@suppress_cc,
221 "envelopesender" => \$envelope_sender,
222 "multiedit" => \$multiedit,
223 "confirm" => \$confirm,
224 "from" => \$sender,
227 # Help users prepare for 1.7.0
228 sub chain_reply_to {
229 if (defined $chain_reply_to &&
230 $chain_reply_to eq $not_set_by_user) {
231 print STDERR
232 "In git 1.7.0, the default has changed to --no-chain-reply-to\n" .
233 "Set sendemail.chainreplyto configuration variable to true if\n" .
234 "you want to keep --chain-reply-to as your default.\n";
235 $chain_reply_to = 0;
237 return $chain_reply_to;
240 # Handle Uncouth Termination
241 sub signal_handler {
243 # Make text normal
244 print color("reset"), "\n";
246 # SMTP password masked
247 system "stty echo";
249 # tmp files from --compose
250 if (defined $compose_filename) {
251 if (-e $compose_filename) {
252 print "'$compose_filename' contains an intermediate version of the email you were composing.\n";
254 if (-e ($compose_filename . ".final")) {
255 print "'$compose_filename.final' contains the composed email.\n"
259 exit;
262 $SIG{TERM} = \&signal_handler;
263 $SIG{INT} = \&signal_handler;
265 # Begin by accumulating all the variables (defined above), that we will end up
266 # needing, first, from the command line:
268 my $rc = GetOptions("sender|from=s" => \$sender,
269 "in-reply-to=s" => \$initial_reply_to,
270 "subject=s" => \$initial_subject,
271 "to=s" => \@to,
272 "no-to" => \$no_to,
273 "cc=s" => \@initial_cc,
274 "no-cc" => \$no_cc,
275 "bcc=s" => \@bcclist,
276 "no-bcc" => \$no_bcc,
277 "chain-reply-to!" => \$chain_reply_to,
278 "smtp-server=s" => \$smtp_server,
279 "smtp-server-port=s" => \$smtp_server_port,
280 "smtp-user=s" => \$smtp_authuser,
281 "smtp-pass:s" => \$smtp_authpass,
282 "smtp-ssl" => sub { $smtp_encryption = 'ssl' },
283 "smtp-encryption=s" => \$smtp_encryption,
284 "smtp-debug:i" => \$debug_net_smtp,
285 "smtp-domain:s" => \$smtp_domain,
286 "identity=s" => \$identity,
287 "annotate" => \$annotate,
288 "compose" => \$compose,
289 "quiet" => \$quiet,
290 "cc-cmd=s" => \$cc_cmd,
291 "suppress-from!" => \$suppress_from,
292 "suppress-cc=s" => \@suppress_cc,
293 "signed-off-cc|signed-off-by-cc!" => \$signed_off_by_cc,
294 "confirm=s" => \$confirm,
295 "dry-run" => \$dry_run,
296 "envelope-sender=s" => \$envelope_sender,
297 "thread!" => \$thread,
298 "validate!" => \$validate,
299 "format-patch!" => \$format_patch,
302 unless ($rc) {
303 usage();
306 die "Cannot run git format-patch from outside a repository\n"
307 if $format_patch and not $repo;
309 # Now, let's fill any that aren't set in with defaults:
311 sub read_config {
312 my ($prefix) = @_;
314 foreach my $setting (keys %config_bool_settings) {
315 my $target = $config_bool_settings{$setting}->[0];
316 $$target = Git::config_bool(@repo, "$prefix.$setting") unless (defined $$target);
319 foreach my $setting (keys %config_settings) {
320 my $target = $config_settings{$setting};
321 next if $setting eq "to" and defined $no_to;
322 next if $setting eq "cc" and defined $no_cc;
323 next if $setting eq "bcc" and defined $no_bcc;
324 if (ref($target) eq "ARRAY") {
325 unless (@$target) {
326 my @values = Git::config(@repo, "$prefix.$setting");
327 @$target = @values if (@values && defined $values[0]);
330 else {
331 $$target = Git::config(@repo, "$prefix.$setting") unless (defined $$target);
335 if (!defined $smtp_encryption) {
336 my $enc = Git::config(@repo, "$prefix.smtpencryption");
337 if (defined $enc) {
338 $smtp_encryption = $enc;
339 } elsif (Git::config_bool(@repo, "$prefix.smtpssl")) {
340 $smtp_encryption = 'ssl';
345 # read configuration from [sendemail "$identity"], fall back on [sendemail]
346 $identity = Git::config(@repo, "sendemail.identity") unless (defined $identity);
347 read_config("sendemail.$identity") if (defined $identity);
348 read_config("sendemail");
350 # fall back on builtin bool defaults
351 foreach my $setting (values %config_bool_settings) {
352 ${$setting->[0]} = $setting->[1] unless (defined (${$setting->[0]}));
355 # 'default' encryption is none -- this only prevents a warning
356 $smtp_encryption = '' unless (defined $smtp_encryption);
358 # Set CC suppressions
359 my(%suppress_cc);
360 if (@suppress_cc) {
361 foreach my $entry (@suppress_cc) {
362 die "Unknown --suppress-cc field: '$entry'\n"
363 unless $entry =~ /^(all|cccmd|cc|author|self|sob|body|bodycc)$/;
364 $suppress_cc{$entry} = 1;
368 if ($suppress_cc{'all'}) {
369 foreach my $entry (qw (cccmd cc author self sob body bodycc)) {
370 $suppress_cc{$entry} = 1;
372 delete $suppress_cc{'all'};
375 # If explicit old-style ones are specified, they trump --suppress-cc.
376 $suppress_cc{'self'} = $suppress_from if defined $suppress_from;
377 $suppress_cc{'sob'} = !$signed_off_by_cc if defined $signed_off_by_cc;
379 if ($suppress_cc{'body'}) {
380 foreach my $entry (qw (sob bodycc)) {
381 $suppress_cc{$entry} = 1;
383 delete $suppress_cc{'body'};
386 # Set confirm's default value
387 my $confirm_unconfigured = !defined $confirm;
388 if ($confirm_unconfigured) {
389 $confirm = scalar %suppress_cc ? 'compose' : 'auto';
391 die "Unknown --confirm setting: '$confirm'\n"
392 unless $confirm =~ /^(?:auto|cc|compose|always|never)/;
394 # Debugging, print out the suppressions.
395 if (0) {
396 print "suppressions:\n";
397 foreach my $entry (keys %suppress_cc) {
398 printf " %-5s -> $suppress_cc{$entry}\n", $entry;
402 my ($repoauthor, $repocommitter);
403 ($repoauthor) = Git::ident_person(@repo, 'author');
404 ($repocommitter) = Git::ident_person(@repo, 'committer');
406 # Verify the user input
408 foreach my $entry (@to) {
409 die "Comma in --to entry: $entry'\n" unless $entry !~ m/,/;
412 foreach my $entry (@initial_cc) {
413 die "Comma in --cc entry: $entry'\n" unless $entry !~ m/,/;
416 foreach my $entry (@bcclist) {
417 die "Comma in --bcclist entry: $entry'\n" unless $entry !~ m/,/;
420 sub parse_address_line {
421 if ($have_mail_address) {
422 return map { $_->format } Mail::Address->parse($_[0]);
423 } else {
424 return split_addrs($_[0]);
428 sub split_addrs {
429 return quotewords('\s*,\s*', 1, @_);
432 my %aliases;
433 my %parse_alias = (
434 # multiline formats can be supported in the future
435 mutt => sub { my $fh = shift; while (<$fh>) {
436 if (/^\s*alias\s+(?:-group\s+\S+\s+)*(\S+)\s+(.*)$/) {
437 my ($alias, $addr) = ($1, $2);
438 $addr =~ s/#.*$//; # mutt allows # comments
439 # commas delimit multiple addresses
440 $aliases{$alias} = [ split_addrs($addr) ];
441 }}},
442 mailrc => sub { my $fh = shift; while (<$fh>) {
443 if (/^alias\s+(\S+)\s+(.*)$/) {
444 # spaces delimit multiple addresses
445 $aliases{$1} = [ quotewords('\s+', 0, $2) ];
446 }}},
447 pine => sub { my $fh = shift; my $f='\t[^\t]*';
448 for (my $x = ''; defined($x); $x = $_) {
449 chomp $x;
450 $x .= $1 while(defined($_ = <$fh>) && /^ +(.*)$/);
451 $x =~ /^(\S+)$f\t\(?([^\t]+?)\)?(:?$f){0,2}$/ or next;
452 $aliases{$1} = [ split_addrs($2) ];
454 elm => sub { my $fh = shift;
455 while (<$fh>) {
456 if (/^(\S+)\s+=\s+[^=]+=\s(\S+)/) {
457 my ($alias, $addr) = ($1, $2);
458 $aliases{$alias} = [ split_addrs($addr) ];
460 } },
462 gnus => sub { my $fh = shift; while (<$fh>) {
463 if (/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) {
464 $aliases{$1} = [ $2 ];
468 if (@alias_files and $aliasfiletype and defined $parse_alias{$aliasfiletype}) {
469 foreach my $file (@alias_files) {
470 open my $fh, '<', $file or die "opening $file: $!\n";
471 $parse_alias{$aliasfiletype}->($fh);
472 close $fh;
476 ($sender) = expand_aliases($sender) if defined $sender;
478 # returns 1 if the conflict must be solved using it as a format-patch argument
479 sub check_file_rev_conflict($) {
480 return unless $repo;
481 my $f = shift;
482 try {
483 $repo->command('rev-parse', '--verify', '--quiet', $f);
484 if (defined($format_patch)) {
485 return $format_patch;
487 die(<<EOF);
488 File '$f' exists but it could also be the range of commits
489 to produce patches for. Please disambiguate by...
491 * Saying "./$f" if you mean a file; or
492 * Giving --format-patch option if you mean a range.
494 } catch Git::Error::Command with {
495 return 0;
499 # Now that all the defaults are set, process the rest of the command line
500 # arguments and collect up the files that need to be processed.
501 my @rev_list_opts;
502 while (defined(my $f = shift @ARGV)) {
503 if ($f eq "--") {
504 push @rev_list_opts, "--", @ARGV;
505 @ARGV = ();
506 } elsif (-d $f and !check_file_rev_conflict($f)) {
507 opendir(DH,$f)
508 or die "Failed to opendir $f: $!";
510 push @files, grep { -f $_ } map { +$f . "/" . $_ }
511 sort readdir(DH);
512 closedir(DH);
513 } elsif ((-f $f or -p $f) and !check_file_rev_conflict($f)) {
514 push @files, $f;
515 } else {
516 push @rev_list_opts, $f;
520 if (@rev_list_opts) {
521 die "Cannot run git format-patch from outside a repository\n"
522 unless $repo;
523 push @files, $repo->command('format-patch', '-o', tempdir(CLEANUP => 1), @rev_list_opts);
526 if ($validate) {
527 foreach my $f (@files) {
528 unless (-p $f) {
529 my $error = validate_patch($f);
530 $error and die "fatal: $f: $error\nwarning: no patches were sent\n";
535 if (@files) {
536 unless ($quiet) {
537 print $_,"\n" for (@files);
539 } else {
540 print STDERR "\nNo patch files specified!\n\n";
541 usage();
544 sub get_patch_subject($) {
545 my $fn = shift;
546 open (my $fh, '<', $fn);
547 while (my $line = <$fh>) {
548 next unless ($line =~ /^Subject: (.*)$/);
549 close $fh;
550 return "GIT: $1\n";
552 close $fh;
553 die "No subject line in $fn ?";
556 if ($compose) {
557 # Note that this does not need to be secure, but we will make a small
558 # effort to have it be unique
559 $compose_filename = ($repo ?
560 tempfile(".gitsendemail.msg.XXXXXX", DIR => $repo->repo_path()) :
561 tempfile(".gitsendemail.msg.XXXXXX", DIR => "."))[1];
562 open(C,">",$compose_filename)
563 or die "Failed to open for writing $compose_filename: $!";
566 my $tpl_sender = $sender || $repoauthor || $repocommitter || '';
567 my $tpl_subject = $initial_subject || '';
568 my $tpl_reply_to = $initial_reply_to || '';
570 print C <<EOT;
571 From $tpl_sender # This line is ignored.
572 GIT: Lines beginning in "GIT:" will be removed.
573 GIT: Consider including an overall diffstat or table of contents
574 GIT: for the patch you are writing.
575 GIT:
576 GIT: Clear the body content if you don't wish to send a summary.
577 From: $tpl_sender
578 Subject: $tpl_subject
579 In-Reply-To: $tpl_reply_to
582 for my $f (@files) {
583 print C get_patch_subject($f);
585 close(C);
587 if ($annotate) {
588 do_edit($compose_filename, @files);
589 } else {
590 do_edit($compose_filename);
593 open(C2,">",$compose_filename . ".final")
594 or die "Failed to open $compose_filename.final : " . $!;
596 open(C,"<",$compose_filename)
597 or die "Failed to open $compose_filename : " . $!;
599 my $need_8bit_cte = file_has_nonascii($compose_filename);
600 my $in_body = 0;
601 my $summary_empty = 1;
602 while(<C>) {
603 next if m/^GIT:/;
604 if ($in_body) {
605 $summary_empty = 0 unless (/^\n$/);
606 } elsif (/^\n$/) {
607 $in_body = 1;
608 if ($need_8bit_cte) {
609 print C2 "MIME-Version: 1.0\n",
610 "Content-Type: text/plain; ",
611 "charset=UTF-8\n",
612 "Content-Transfer-Encoding: 8bit\n";
614 } elsif (/^MIME-Version:/i) {
615 $need_8bit_cte = 0;
616 } elsif (/^Subject:\s*(.+)\s*$/i) {
617 $initial_subject = $1;
618 my $subject = $initial_subject;
619 $_ = "Subject: " .
620 ($subject =~ /[^[:ascii:]]/ ?
621 quote_rfc2047($subject) :
622 $subject) .
623 "\n";
624 } elsif (/^In-Reply-To:\s*(.+)\s*$/i) {
625 $initial_reply_to = $1;
626 next;
627 } elsif (/^From:\s*(.+)\s*$/i) {
628 $sender = $1;
629 next;
630 } elsif (/^(?:To|Cc|Bcc):/i) {
631 print "To/Cc/Bcc fields are not interpreted yet, they have been ignored\n";
632 next;
634 print C2 $_;
636 close(C);
637 close(C2);
639 if ($summary_empty) {
640 print "Summary email is empty, skipping it\n";
641 $compose = -1;
643 } elsif ($annotate) {
644 do_edit(@files);
647 sub ask {
648 my ($prompt, %arg) = @_;
649 my $valid_re = $arg{valid_re};
650 my $default = $arg{default};
651 my $resp;
652 my $i = 0;
653 return defined $default ? $default : undef
654 unless defined $term->IN and defined fileno($term->IN) and
655 defined $term->OUT and defined fileno($term->OUT);
656 while ($i++ < 10) {
657 $resp = $term->readline($prompt);
658 if (!defined $resp) { # EOF
659 print "\n";
660 return defined $default ? $default : undef;
662 if ($resp eq '' and defined $default) {
663 return $default;
665 if (!defined $valid_re or $resp =~ /$valid_re/) {
666 return $resp;
669 return undef;
672 my $prompting = 0;
673 if (!defined $sender) {
674 $sender = $repoauthor || $repocommitter || '';
675 $sender = ask("Who should the emails appear to be from? [$sender] ",
676 default => $sender);
677 print "Emails will be sent from: ", $sender, "\n";
678 $prompting++;
681 if (!@to) {
682 my $to = ask("Who should the emails be sent to? ");
683 push @to, parse_address_line($to) if defined $to; # sanitized/validated later
684 $prompting++;
687 sub expand_aliases {
688 return map { expand_one_alias($_) } @_;
691 my %EXPANDED_ALIASES;
692 sub expand_one_alias {
693 my $alias = shift;
694 if ($EXPANDED_ALIASES{$alias}) {
695 die "fatal: alias '$alias' expands to itself\n";
697 local $EXPANDED_ALIASES{$alias} = 1;
698 return $aliases{$alias} ? expand_aliases(@{$aliases{$alias}}) : $alias;
701 @to = expand_aliases(@to);
702 @to = (map { sanitize_address($_) } @to);
703 @initial_cc = expand_aliases(@initial_cc);
704 @bcclist = expand_aliases(@bcclist);
706 if ($thread && !defined $initial_reply_to && $prompting) {
707 $initial_reply_to = ask(
708 "Message-ID to be used as In-Reply-To for the first email? ");
710 if (defined $initial_reply_to) {
711 $initial_reply_to =~ s/^\s*<?//;
712 $initial_reply_to =~ s/>?\s*$//;
713 $initial_reply_to = "<$initial_reply_to>" if $initial_reply_to ne '';
716 if (!defined $smtp_server) {
717 foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
718 if (-x $_) {
719 $smtp_server = $_;
720 last;
723 $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
726 if ($compose && $compose > 0) {
727 @files = ($compose_filename . ".final", @files);
730 # Variables we set as part of the loop over files
731 our ($message_id, %mail, $subject, $reply_to, $references, $message,
732 $needs_confirm, $message_num, $ask_default);
734 sub extract_valid_address {
735 my $address = shift;
736 my $local_part_regexp = '[^<>"\s@]+';
737 my $domain_regexp = '[^.<>"\s@]+(?:\.[^.<>"\s@]+)+';
739 # check for a local address:
740 return $address if ($address =~ /^($local_part_regexp)$/);
742 $address =~ s/^\s*<(.*)>\s*$/$1/;
743 if ($have_email_valid) {
744 return scalar Email::Valid->address($address);
745 } else {
746 # less robust/correct than the monster regexp in Email::Valid,
747 # but still does a 99% job, and one less dependency
748 $address =~ /($local_part_regexp\@$domain_regexp)/;
749 return $1;
753 # Usually don't need to change anything below here.
755 # we make a "fake" message id by taking the current number
756 # of seconds since the beginning of Unix time and tacking on
757 # a random number to the end, in case we are called quicker than
758 # 1 second since the last time we were called.
760 # We'll setup a template for the message id, using the "from" address:
762 my ($message_id_stamp, $message_id_serial);
763 sub make_message_id {
764 my $uniq;
765 if (!defined $message_id_stamp) {
766 $message_id_stamp = sprintf("%s-%s", time, $$);
767 $message_id_serial = 0;
769 $message_id_serial++;
770 $uniq = "$message_id_stamp-$message_id_serial";
772 my $du_part;
773 for ($sender, $repocommitter, $repoauthor) {
774 $du_part = extract_valid_address(sanitize_address($_));
775 last if (defined $du_part and $du_part ne '');
777 if (not defined $du_part or $du_part eq '') {
778 use Sys::Hostname qw();
779 $du_part = 'user@' . Sys::Hostname::hostname();
781 my $message_id_template = "<%s-git-send-email-%s>";
782 $message_id = sprintf($message_id_template, $uniq, $du_part);
783 #print "new message id = $message_id\n"; # Was useful for debugging
788 $time = time - scalar $#files;
790 sub unquote_rfc2047 {
791 local ($_) = @_;
792 my $encoding;
793 if (s/=\?([^?]+)\?q\?(.*)\?=/$2/g) {
794 $encoding = $1;
795 s/_/ /g;
796 s/=([0-9A-F]{2})/chr(hex($1))/eg;
798 return wantarray ? ($_, $encoding) : $_;
801 sub quote_rfc2047 {
802 local $_ = shift;
803 my $encoding = shift || 'UTF-8';
804 s/([^-a-zA-Z0-9!*+\/])/sprintf("=%02X", ord($1))/eg;
805 s/(.*)/=\?$encoding\?q\?$1\?=/;
806 return $_;
809 sub is_rfc2047_quoted {
810 my $s = shift;
811 my $token = '[^][()<>@,;:"\/?.= \000-\037\177-\377]+';
812 my $encoded_text = '[!->@-~]+';
813 length($s) <= 75 &&
814 $s =~ m/^(?:"[[:ascii:]]*"|=\?$token\?$token\?$encoded_text\?=)$/o;
817 # use the simplest quoting being able to handle the recipient
818 sub sanitize_address {
819 my ($recipient) = @_;
820 my ($recipient_name, $recipient_addr) = ($recipient =~ /^(.*?)\s*(<.*)/);
822 if (not $recipient_name) {
823 return "$recipient";
826 # if recipient_name is already quoted, do nothing
827 if (is_rfc2047_quoted($recipient_name)) {
828 return $recipient;
831 # rfc2047 is needed if a non-ascii char is included
832 if ($recipient_name =~ /[^[:ascii:]]/) {
833 $recipient_name =~ s/^"(.*)"$/$1/;
834 $recipient_name = quote_rfc2047($recipient_name);
837 # double quotes are needed if specials or CTLs are included
838 elsif ($recipient_name =~ /[][()<>@,;:\\".\000-\037\177]/) {
839 $recipient_name =~ s/(["\\\r])/\\$1/g;
840 $recipient_name = "\"$recipient_name\"";
843 return "$recipient_name $recipient_addr";
847 # Returns the local Fully Qualified Domain Name (FQDN) if available.
849 # Tightly configured MTAa require that a caller sends a real DNS
850 # domain name that corresponds the IP address in the HELO/EHLO
851 # handshake. This is used to verify the connection and prevent
852 # spammers from trying to hide their identity. If the DNS and IP don't
853 # match, the receiveing MTA may deny the connection.
855 # Here is a deny example of Net::SMTP with the default "localhost.localdomain"
857 # Net::SMTP=GLOB(0x267ec28)>>> EHLO localhost.localdomain
858 # Net::SMTP=GLOB(0x267ec28)<<< 550 EHLO argument does not match calling host
860 # This maildomain*() code is based on ideas in Perl library Test::Reporter
861 # /usr/share/perl5/Test/Reporter/Mail/Util.pm ==> sub _maildomain ()
863 sub valid_fqdn {
864 my $domain = shift;
865 return !($^O eq 'darwin' && $domain =~ /\.local$/) && $domain =~ /\./;
868 sub maildomain_net {
869 my $maildomain;
871 if (eval { require Net::Domain; 1 }) {
872 my $domain = Net::Domain::domainname();
873 $maildomain = $domain if valid_fqdn($domain);
876 return $maildomain;
879 sub maildomain_mta {
880 my $maildomain;
882 if (eval { require Net::SMTP; 1 }) {
883 for my $host (qw(mailhost localhost)) {
884 my $smtp = Net::SMTP->new($host);
885 if (defined $smtp) {
886 my $domain = $smtp->domain;
887 $smtp->quit;
889 $maildomain = $domain if valid_fqdn($domain);
891 last if $maildomain;
896 return $maildomain;
899 sub maildomain {
900 return maildomain_net() || maildomain_mta() || 'localhost.localdomain';
903 # Returns 1 if the message was sent, and 0 otherwise.
904 # In actuality, the whole program dies when there
905 # is an error sending a message.
907 sub send_message {
908 my @recipients = unique_email_list(@to);
909 @cc = (grep { my $cc = extract_valid_address($_);
910 not grep { $cc eq $_ } @recipients
912 map { sanitize_address($_) }
913 @cc);
914 my $to = join (",\n\t", @recipients);
915 @recipients = unique_email_list(@recipients,@cc,@bcclist);
916 @recipients = (map { extract_valid_address($_) } @recipients);
917 my $date = format_2822_time($time++);
918 my $gitversion = '@@GIT_VERSION@@';
919 if ($gitversion =~ m/..GIT_VERSION../) {
920 $gitversion = Git::version();
923 my $cc = join(",\n\t", unique_email_list(@cc));
924 my $ccline = "";
925 if ($cc ne '') {
926 $ccline = "\nCc: $cc";
928 my $sanitized_sender = sanitize_address($sender);
929 make_message_id() unless defined($message_id);
931 my $header = "From: $sanitized_sender
932 To: $to${ccline}
933 Subject: $subject
934 Date: $date
935 Message-Id: $message_id
936 X-Mailer: git-send-email $gitversion
938 if ($reply_to) {
940 $header .= "In-Reply-To: $reply_to\n";
941 $header .= "References: $references\n";
943 if (@xh) {
944 $header .= join("\n", @xh) . "\n";
947 my @sendmail_parameters = ('-i', @recipients);
948 my $raw_from = $sanitized_sender;
949 if (defined $envelope_sender && $envelope_sender ne "auto") {
950 $raw_from = $envelope_sender;
952 $raw_from = extract_valid_address($raw_from);
953 unshift (@sendmail_parameters,
954 '-f', $raw_from) if(defined $envelope_sender);
956 if ($needs_confirm && !$dry_run) {
957 print "\n$header\n";
958 if ($needs_confirm eq "inform") {
959 $confirm_unconfigured = 0; # squelch this message for the rest of this run
960 $ask_default = "y"; # assume yes on EOF since user hasn't explicitly asked for confirmation
961 print " The Cc list above has been expanded by additional\n";
962 print " addresses found in the patch commit message. By default\n";
963 print " send-email prompts before sending whenever this occurs.\n";
964 print " This behavior is controlled by the sendemail.confirm\n";
965 print " configuration setting.\n";
966 print "\n";
967 print " For additional information, run 'git send-email --help'.\n";
968 print " To retain the current behavior, but squelch this message,\n";
969 print " run 'git config --global sendemail.confirm auto'.\n\n";
971 $_ = ask("Send this email? ([y]es|[n]o|[q]uit|[a]ll): ",
972 valid_re => qr/^(?:yes|y|no|n|quit|q|all|a)/i,
973 default => $ask_default);
974 die "Send this email reply required" unless defined $_;
975 if (/^n/i) {
976 return 0;
977 } elsif (/^q/i) {
978 cleanup_compose_files();
979 exit(0);
980 } elsif (/^a/i) {
981 $confirm = 'never';
985 if ($dry_run) {
986 # We don't want to send the email.
987 } elsif ($smtp_server =~ m#^/#) {
988 my $pid = open my $sm, '|-';
989 defined $pid or die $!;
990 if (!$pid) {
991 exec($smtp_server, @sendmail_parameters) or die $!;
993 print $sm "$header\n$message";
994 close $sm or die $?;
995 } else {
997 if (!defined $smtp_server) {
998 die "The required SMTP server is not properly defined."
1001 if ($smtp_encryption eq 'ssl') {
1002 $smtp_server_port ||= 465; # ssmtp
1003 require Net::SMTP::SSL;
1004 $smtp_domain ||= maildomain();
1005 $smtp ||= Net::SMTP::SSL->new($smtp_server,
1006 Hello => $smtp_domain,
1007 Port => $smtp_server_port);
1009 else {
1010 require Net::SMTP;
1011 $smtp_domain ||= maildomain();
1012 $smtp ||= Net::SMTP->new((defined $smtp_server_port)
1013 ? "$smtp_server:$smtp_server_port"
1014 : $smtp_server,
1015 Hello => $smtp_domain,
1016 Debug => $debug_net_smtp);
1017 if ($smtp_encryption eq 'tls' && $smtp) {
1018 require Net::SMTP::SSL;
1019 $smtp->command('STARTTLS');
1020 $smtp->response();
1021 if ($smtp->code == 220) {
1022 $smtp = Net::SMTP::SSL->start_SSL($smtp)
1023 or die "STARTTLS failed! ".$smtp->message;
1024 $smtp_encryption = '';
1025 # Send EHLO again to receive fresh
1026 # supported commands
1027 $smtp->hello();
1028 } else {
1029 die "Server does not support STARTTLS! ".$smtp->message;
1034 if (!$smtp) {
1035 die "Unable to initialize SMTP properly. Check config and use --smtp-debug. ",
1036 "VALUES: server=$smtp_server ",
1037 "encryption=$smtp_encryption ",
1038 "hello=$smtp_domain",
1039 defined $smtp_server_port ? "port=$smtp_server_port" : "";
1042 if (defined $smtp_authuser) {
1044 if (!defined $smtp_authpass) {
1046 system "stty -echo";
1048 do {
1049 print "Password: ";
1050 $_ = <STDIN>;
1051 print "\n";
1052 } while (!defined $_);
1054 chomp($smtp_authpass = $_);
1056 system "stty echo";
1059 $auth ||= $smtp->auth( $smtp_authuser, $smtp_authpass ) or die $smtp->message;
1062 $smtp->mail( $raw_from ) or die $smtp->message;
1063 $smtp->to( @recipients ) or die $smtp->message;
1064 $smtp->data or die $smtp->message;
1065 $smtp->datasend("$header\n$message") or die $smtp->message;
1066 $smtp->dataend() or die $smtp->message;
1067 $smtp->code =~ /250|200/ or die "Failed to send $subject\n".$smtp->message;
1069 if ($quiet) {
1070 printf (($dry_run ? "Dry-" : "")."Sent %s\n", $subject);
1071 } else {
1072 print (($dry_run ? "Dry-" : "")."OK. Log says:\n");
1073 if ($smtp_server !~ m#^/#) {
1074 print "Server: $smtp_server\n";
1075 print "MAIL FROM:<$raw_from>\n";
1076 foreach my $entry (@recipients) {
1077 print "RCPT TO:<$entry>\n";
1079 } else {
1080 print "Sendmail: $smtp_server ".join(' ',@sendmail_parameters)."\n";
1082 print $header, "\n";
1083 if ($smtp) {
1084 print "Result: ", $smtp->code, ' ',
1085 ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
1086 } else {
1087 print "Result: OK\n";
1091 return 1;
1094 $reply_to = $initial_reply_to;
1095 $references = $initial_reply_to || '';
1096 $subject = $initial_subject;
1097 $message_num = 0;
1099 foreach my $t (@files) {
1100 open(F,"<",$t) or die "can't open file $t";
1102 my $author = undef;
1103 my $author_encoding;
1104 my $has_content_type;
1105 my $body_encoding;
1106 @cc = ();
1107 @xh = ();
1108 my $input_format = undef;
1109 my @header = ();
1110 $message = "";
1111 $message_num++;
1112 # First unfold multiline header fields
1113 while(<F>) {
1114 last if /^\s*$/;
1115 if (/^\s+\S/ and @header) {
1116 chomp($header[$#header]);
1117 s/^\s+/ /;
1118 $header[$#header] .= $_;
1119 } else {
1120 push(@header, $_);
1123 # Now parse the header
1124 foreach(@header) {
1125 if (/^From /) {
1126 $input_format = 'mbox';
1127 next;
1129 chomp;
1130 if (!defined $input_format && /^[-A-Za-z]+:\s/) {
1131 $input_format = 'mbox';
1134 if (defined $input_format && $input_format eq 'mbox') {
1135 if (/^Subject:\s+(.*)$/) {
1136 $subject = $1;
1138 elsif (/^From:\s+(.*)$/) {
1139 ($author, $author_encoding) = unquote_rfc2047($1);
1140 next if $suppress_cc{'author'};
1141 next if $suppress_cc{'self'} and $author eq $sender;
1142 printf("(mbox) Adding cc: %s from line '%s'\n",
1143 $1, $_) unless $quiet;
1144 push @cc, $1;
1146 elsif (/^Cc:\s+(.*)$/) {
1147 foreach my $addr (parse_address_line($1)) {
1148 if (unquote_rfc2047($addr) eq $sender) {
1149 next if ($suppress_cc{'self'});
1150 } else {
1151 next if ($suppress_cc{'cc'});
1153 printf("(mbox) Adding cc: %s from line '%s'\n",
1154 $addr, $_) unless $quiet;
1155 push @cc, $addr;
1158 elsif (/^Content-type:/i) {
1159 $has_content_type = 1;
1160 if (/charset="?([^ "]+)/) {
1161 $body_encoding = $1;
1163 push @xh, $_;
1165 elsif (/^Message-Id: (.*)/i) {
1166 $message_id = $1;
1168 elsif (!/^Date:\s/ && /^[-A-Za-z]+:\s+\S/) {
1169 push @xh, $_;
1172 } else {
1173 # In the traditional
1174 # "send lots of email" format,
1175 # line 1 = cc
1176 # line 2 = subject
1177 # So let's support that, too.
1178 $input_format = 'lots';
1179 if (@cc == 0 && !$suppress_cc{'cc'}) {
1180 printf("(non-mbox) Adding cc: %s from line '%s'\n",
1181 $_, $_) unless $quiet;
1182 push @cc, $_;
1183 } elsif (!defined $subject) {
1184 $subject = $_;
1188 # Now parse the message body
1189 while(<F>) {
1190 $message .= $_;
1191 if (/^(Signed-off-by|Cc): (.*)$/i) {
1192 chomp;
1193 my ($what, $c) = ($1, $2);
1194 chomp $c;
1195 if ($c eq $sender) {
1196 next if ($suppress_cc{'self'});
1197 } else {
1198 next if $suppress_cc{'sob'} and $what =~ /Signed-off-by/i;
1199 next if $suppress_cc{'bodycc'} and $what =~ /Cc/i;
1201 push @cc, $c;
1202 printf("(body) Adding cc: %s from line '%s'\n",
1203 $c, $_) unless $quiet;
1206 close F;
1208 if (defined $cc_cmd && !$suppress_cc{'cccmd'}) {
1209 open(F, "$cc_cmd \Q$t\E |")
1210 or die "(cc-cmd) Could not execute '$cc_cmd'";
1211 while(<F>) {
1212 my $c = $_;
1213 $c =~ s/^\s*//g;
1214 $c =~ s/\n$//g;
1215 next if ($c eq $sender and $suppress_from);
1216 push @cc, $c;
1217 printf("(cc-cmd) Adding cc: %s from: '%s'\n",
1218 $c, $cc_cmd) unless $quiet;
1220 close F
1221 or die "(cc-cmd) failed to close pipe to '$cc_cmd'";
1224 if (defined $author and $author ne $sender) {
1225 $message = "From: $author\n\n$message";
1226 if (defined $author_encoding) {
1227 if ($has_content_type) {
1228 if ($body_encoding eq $author_encoding) {
1229 # ok, we already have the right encoding
1231 else {
1232 # uh oh, we should re-encode
1235 else {
1236 push @xh,
1237 'MIME-Version: 1.0',
1238 "Content-Type: text/plain; charset=$author_encoding",
1239 'Content-Transfer-Encoding: 8bit';
1244 $needs_confirm = (
1245 $confirm eq "always" or
1246 ($confirm =~ /^(?:auto|cc)$/ && @cc) or
1247 ($confirm =~ /^(?:auto|compose)$/ && $compose && $message_num == 1));
1248 $needs_confirm = "inform" if ($needs_confirm && $confirm_unconfigured && @cc);
1250 @cc = (@initial_cc, @cc);
1252 my $message_was_sent = send_message();
1254 # set up for the next message
1255 if ($thread && $message_was_sent &&
1256 (chain_reply_to() || !defined $reply_to || length($reply_to) == 0)) {
1257 $reply_to = $message_id;
1258 if (length $references > 0) {
1259 $references .= "\n $message_id";
1260 } else {
1261 $references = "$message_id";
1264 $message_id = undef;
1267 cleanup_compose_files();
1269 sub cleanup_compose_files() {
1270 unlink($compose_filename, $compose_filename . ".final") if $compose;
1273 $smtp->quit if $smtp;
1275 sub unique_email_list(@) {
1276 my %seen;
1277 my @emails;
1279 foreach my $entry (@_) {
1280 if (my $clean = extract_valid_address($entry)) {
1281 $seen{$clean} ||= 0;
1282 next if $seen{$clean}++;
1283 push @emails, $entry;
1284 } else {
1285 print STDERR "W: unable to extract a valid address",
1286 " from: $entry\n";
1289 return @emails;
1292 sub validate_patch {
1293 my $fn = shift;
1294 open(my $fh, '<', $fn)
1295 or die "unable to open $fn: $!\n";
1296 while (my $line = <$fh>) {
1297 if (length($line) > 998) {
1298 return "$.: patch contains a line longer than 998 characters";
1301 return undef;
1304 sub file_has_nonascii {
1305 my $fn = shift;
1306 open(my $fh, '<', $fn)
1307 or die "unable to open $fn: $!\n";
1308 while (my $line = <$fh>) {
1309 return 1 if $line =~ /[^[:ascii:]]/;
1311 return 0;