Revert "git-gui: set GIT_DIR and GIT_WORK_TREE after setup"
[git/dscho.git] / git-send-email.perl
blob91607c5878953d69a8e32731023b2eb727bcc069
1 #!/usr/bin/perl
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 5.008;
20 use strict;
21 use warnings;
22 use Term::ReadLine;
23 use Getopt::Long;
24 use Text::ParseWords;
25 use Data::Dumper;
26 use Term::ANSIColor;
27 use File::Temp qw/ tempdir tempfile /;
28 use File::Spec::Functions qw(catfile);
29 use Error qw(:try);
30 use Git;
32 Getopt::Long::Configure qw/ pass_through /;
34 package FakeTerm;
35 sub new {
36 my ($class, $reason) = @_;
37 return bless \$reason, shift;
39 sub readline {
40 my $self = shift;
41 die "Cannot use readline on FakeTerm: $$self";
43 package main;
46 sub usage {
47 print <<EOT;
48 git send-email [options] <file | directory | rev-list options >
50 Composing:
51 --from <str> * Email From:
52 --[no-]to <str> * Email To:
53 --[no-]cc <str> * Email Cc:
54 --[no-]bcc <str> * Email Bcc:
55 --subject <str> * Email "Subject:"
56 --in-reply-to <str> * Email "In-Reply-To:"
57 --annotate * Review each patch that will be sent in an editor.
58 --compose * Open an editor for introduction.
59 --8bit-encoding <str> * Encoding to assume 8bit mails if undeclared
61 Sending:
62 --envelope-sender <str> * Email envelope sender.
63 --smtp-server <str:int> * Outgoing SMTP server to use. The port
64 is optional. Default 'localhost'.
65 --smtp-server-option <str> * Outgoing SMTP server option to use.
66 --smtp-server-port <int> * Outgoing SMTP server port.
67 --smtp-user <str> * Username for SMTP-AUTH.
68 --smtp-pass <str> * Password for SMTP-AUTH; not necessary.
69 --smtp-encryption <str> * tls or ssl; anything else disables.
70 --smtp-ssl * Deprecated. Use '--smtp-encryption ssl'.
71 --smtp-domain <str> * The domain name sent to HELO/EHLO handshake
72 --smtp-debug <0|1> * Disable, enable Net::SMTP debug.
74 Automating:
75 --identity <str> * Use the sendemail.<id> options.
76 --to-cmd <str> * Email To: via `<str> \$patch_path`
77 --cc-cmd <str> * Email Cc: via `<str> \$patch_path`
78 --suppress-cc <str> * author, self, sob, cc, cccmd, body, bodycc, all.
79 --[no-]signed-off-by-cc * Send to Signed-off-by: addresses. Default on.
80 --[no-]suppress-from * Send to self. Default off.
81 --[no-]chain-reply-to * Chain In-Reply-To: fields. Default off.
82 --[no-]thread * Use In-Reply-To: field. Default on.
84 Administering:
85 --confirm <str> * Confirm recipients before sending;
86 auto, cc, compose, always, or never.
87 --quiet * Output one line of info per email.
88 --dry-run * Don't actually send the emails.
89 --[no-]validate * Perform patch sanity checks. Default on.
90 --[no-]format-patch * understand any non optional arguments as
91 `git format-patch` ones.
92 --force * Send even if safety checks would prevent it.
94 EOT
95 exit(1);
98 # most mail servers generate the Date: header, but not all...
99 sub format_2822_time {
100 my ($time) = @_;
101 my @localtm = localtime($time);
102 my @gmttm = gmtime($time);
103 my $localmin = $localtm[1] + $localtm[2] * 60;
104 my $gmtmin = $gmttm[1] + $gmttm[2] * 60;
105 if ($localtm[0] != $gmttm[0]) {
106 die "local zone differs from GMT by a non-minute interval\n";
108 if ((($gmttm[6] + 1) % 7) == $localtm[6]) {
109 $localmin += 1440;
110 } elsif ((($gmttm[6] - 1) % 7) == $localtm[6]) {
111 $localmin -= 1440;
112 } elsif ($gmttm[6] != $localtm[6]) {
113 die "local time offset greater than or equal to 24 hours\n";
115 my $offset = $localmin - $gmtmin;
116 my $offhour = $offset / 60;
117 my $offmin = abs($offset % 60);
118 if (abs($offhour) >= 24) {
119 die ("local time offset greater than or equal to 24 hours\n");
122 return sprintf("%s, %2d %s %d %02d:%02d:%02d %s%02d%02d",
123 qw(Sun Mon Tue Wed Thu Fri Sat)[$localtm[6]],
124 $localtm[3],
125 qw(Jan Feb Mar Apr May Jun
126 Jul Aug Sep Oct Nov Dec)[$localtm[4]],
127 $localtm[5]+1900,
128 $localtm[2],
129 $localtm[1],
130 $localtm[0],
131 ($offset >= 0) ? '+' : '-',
132 abs($offhour),
133 $offmin,
137 my $have_email_valid = eval { require Email::Valid; 1 };
138 my $have_mail_address = eval { require Mail::Address; 1 };
139 my $smtp;
140 my $auth;
142 # Variables we fill in automatically, or via prompting:
143 my (@to,$no_to,@initial_to,@cc,$no_cc,@initial_cc,@bcclist,$no_bcc,@xh,
144 $initial_reply_to,$initial_subject,@files,
145 $author,$sender,$smtp_authpass,$annotate,$compose,$time);
147 my $envelope_sender;
149 # Example reply to:
150 #$initial_reply_to = ''; #<20050203173208.GA23964@foobar.com>';
152 my $repo = eval { Git->repository() };
153 my @repo = $repo ? ($repo) : ();
154 my $term = eval {
155 $ENV{"GIT_SEND_EMAIL_NOTTY"}
156 ? new Term::ReadLine 'git-send-email', \*STDIN, \*STDOUT
157 : new Term::ReadLine 'git-send-email';
159 if ($@) {
160 $term = new FakeTerm "$@: going non-interactive";
163 # Behavior modification variables
164 my ($quiet, $dry_run) = (0, 0);
165 my $format_patch;
166 my $compose_filename;
167 my $force = 0;
169 # Handle interactive edition of files.
170 my $multiedit;
171 my $editor;
173 sub do_edit {
174 if (!defined($editor)) {
175 $editor = Git::command_oneline('var', 'GIT_EDITOR');
177 if (defined($multiedit) && !$multiedit) {
178 map {
179 system('sh', '-c', $editor.' "$@"', $editor, $_);
180 if (($? & 127) || ($? >> 8)) {
181 die("the editor exited uncleanly, aborting everything");
183 } @_;
184 } else {
185 system('sh', '-c', $editor.' "$@"', $editor, @_);
186 if (($? & 127) || ($? >> 8)) {
187 die("the editor exited uncleanly, aborting everything");
192 # Variables with corresponding config settings
193 my ($thread, $chain_reply_to, $suppress_from, $signed_off_by_cc);
194 my ($to_cmd, $cc_cmd);
195 my ($smtp_server, $smtp_server_port, @smtp_server_options);
196 my ($smtp_authuser, $smtp_encryption);
197 my ($identity, $aliasfiletype, @alias_files, $smtp_domain);
198 my ($validate, $confirm);
199 my (@suppress_cc);
200 my ($auto_8bit_encoding);
202 my ($debug_net_smtp) = 0; # Net::SMTP, see send_message()
204 my $not_set_by_user = "true but not set by the user";
206 my %config_bool_settings = (
207 "thread" => [\$thread, 1],
208 "chainreplyto" => [\$chain_reply_to, $not_set_by_user],
209 "suppressfrom" => [\$suppress_from, undef],
210 "signedoffbycc" => [\$signed_off_by_cc, undef],
211 "signedoffcc" => [\$signed_off_by_cc, undef], # Deprecated
212 "validate" => [\$validate, 1],
215 my %config_settings = (
216 "smtpserver" => \$smtp_server,
217 "smtpserverport" => \$smtp_server_port,
218 "smtpserveroption" => \@smtp_server_options,
219 "smtpuser" => \$smtp_authuser,
220 "smtppass" => \$smtp_authpass,
221 "smtpdomain" => \$smtp_domain,
222 "to" => \@initial_to,
223 "tocmd" => \$to_cmd,
224 "cc" => \@initial_cc,
225 "cccmd" => \$cc_cmd,
226 "aliasfiletype" => \$aliasfiletype,
227 "bcc" => \@bcclist,
228 "suppresscc" => \@suppress_cc,
229 "envelopesender" => \$envelope_sender,
230 "multiedit" => \$multiedit,
231 "confirm" => \$confirm,
232 "from" => \$sender,
233 "assume8bitencoding" => \$auto_8bit_encoding,
236 my %config_path_settings = (
237 "aliasesfile" => \@alias_files,
240 # Help users prepare for 1.7.0
241 sub chain_reply_to {
242 if (defined $chain_reply_to &&
243 $chain_reply_to eq $not_set_by_user) {
244 print STDERR
245 "In git 1.7.0, the default has changed to --no-chain-reply-to\n" .
246 "Set sendemail.chainreplyto configuration variable to true if\n" .
247 "you want to keep --chain-reply-to as your default.\n";
248 $chain_reply_to = 0;
250 return $chain_reply_to;
253 # Handle Uncouth Termination
254 sub signal_handler {
256 # Make text normal
257 print color("reset"), "\n";
259 # SMTP password masked
260 system "stty echo";
262 # tmp files from --compose
263 if (defined $compose_filename) {
264 if (-e $compose_filename) {
265 print "'$compose_filename' contains an intermediate version of the email you were composing.\n";
267 if (-e ($compose_filename . ".final")) {
268 print "'$compose_filename.final' contains the composed email.\n"
272 exit;
275 $SIG{TERM} = \&signal_handler;
276 $SIG{INT} = \&signal_handler;
278 # Begin by accumulating all the variables (defined above), that we will end up
279 # needing, first, from the command line:
281 my $help;
282 my $rc = GetOptions("h" => \$help,
283 "sender|from=s" => \$sender,
284 "in-reply-to=s" => \$initial_reply_to,
285 "subject=s" => \$initial_subject,
286 "to=s" => \@initial_to,
287 "to-cmd=s" => \$to_cmd,
288 "no-to" => \$no_to,
289 "cc=s" => \@initial_cc,
290 "no-cc" => \$no_cc,
291 "bcc=s" => \@bcclist,
292 "no-bcc" => \$no_bcc,
293 "chain-reply-to!" => \$chain_reply_to,
294 "smtp-server=s" => \$smtp_server,
295 "smtp-server-option=s" => \@smtp_server_options,
296 "smtp-server-port=s" => \$smtp_server_port,
297 "smtp-user=s" => \$smtp_authuser,
298 "smtp-pass:s" => \$smtp_authpass,
299 "smtp-ssl" => sub { $smtp_encryption = 'ssl' },
300 "smtp-encryption=s" => \$smtp_encryption,
301 "smtp-debug:i" => \$debug_net_smtp,
302 "smtp-domain:s" => \$smtp_domain,
303 "identity=s" => \$identity,
304 "annotate" => \$annotate,
305 "compose" => \$compose,
306 "quiet" => \$quiet,
307 "cc-cmd=s" => \$cc_cmd,
308 "suppress-from!" => \$suppress_from,
309 "suppress-cc=s" => \@suppress_cc,
310 "signed-off-cc|signed-off-by-cc!" => \$signed_off_by_cc,
311 "confirm=s" => \$confirm,
312 "dry-run" => \$dry_run,
313 "envelope-sender=s" => \$envelope_sender,
314 "thread!" => \$thread,
315 "validate!" => \$validate,
316 "format-patch!" => \$format_patch,
317 "8bit-encoding=s" => \$auto_8bit_encoding,
318 "force" => \$force,
321 usage() if $help;
322 unless ($rc) {
323 usage();
326 die "Cannot run git format-patch from outside a repository\n"
327 if $format_patch and not $repo;
329 # Now, let's fill any that aren't set in with defaults:
331 sub read_config {
332 my ($prefix) = @_;
334 foreach my $setting (keys %config_bool_settings) {
335 my $target = $config_bool_settings{$setting}->[0];
336 $$target = Git::config_bool(@repo, "$prefix.$setting") unless (defined $$target);
339 foreach my $setting (keys %config_path_settings) {
340 my $target = $config_path_settings{$setting}->[0];
341 $$target = Git::config_path(@repo, "$prefix.$setting") unless (defined $$target);
344 foreach my $setting (keys %config_settings) {
345 my $target = $config_settings{$setting};
346 next if $setting eq "to" and defined $no_to;
347 next if $setting eq "cc" and defined $no_cc;
348 next if $setting eq "bcc" and defined $no_bcc;
349 if (ref($target) eq "ARRAY") {
350 unless (@$target) {
351 my @values = Git::config(@repo, "$prefix.$setting");
352 @$target = @values if (@values && defined $values[0]);
355 else {
356 $$target = Git::config(@repo, "$prefix.$setting") unless (defined $$target);
360 if (!defined $smtp_encryption) {
361 my $enc = Git::config(@repo, "$prefix.smtpencryption");
362 if (defined $enc) {
363 $smtp_encryption = $enc;
364 } elsif (Git::config_bool(@repo, "$prefix.smtpssl")) {
365 $smtp_encryption = 'ssl';
370 # read configuration from [sendemail "$identity"], fall back on [sendemail]
371 $identity = Git::config(@repo, "sendemail.identity") unless (defined $identity);
372 read_config("sendemail.$identity") if (defined $identity);
373 read_config("sendemail");
375 # fall back on builtin bool defaults
376 foreach my $setting (values %config_bool_settings) {
377 ${$setting->[0]} = $setting->[1] unless (defined (${$setting->[0]}));
380 # 'default' encryption is none -- this only prevents a warning
381 $smtp_encryption = '' unless (defined $smtp_encryption);
383 # Set CC suppressions
384 my(%suppress_cc);
385 if (@suppress_cc) {
386 foreach my $entry (@suppress_cc) {
387 die "Unknown --suppress-cc field: '$entry'\n"
388 unless $entry =~ /^(?:all|cccmd|cc|author|self|sob|body|bodycc)$/;
389 $suppress_cc{$entry} = 1;
393 if ($suppress_cc{'all'}) {
394 foreach my $entry (qw (cccmd cc author self sob body bodycc)) {
395 $suppress_cc{$entry} = 1;
397 delete $suppress_cc{'all'};
400 # If explicit old-style ones are specified, they trump --suppress-cc.
401 $suppress_cc{'self'} = $suppress_from if defined $suppress_from;
402 $suppress_cc{'sob'} = !$signed_off_by_cc if defined $signed_off_by_cc;
404 if ($suppress_cc{'body'}) {
405 foreach my $entry (qw (sob bodycc)) {
406 $suppress_cc{$entry} = 1;
408 delete $suppress_cc{'body'};
411 # Set confirm's default value
412 my $confirm_unconfigured = !defined $confirm;
413 if ($confirm_unconfigured) {
414 $confirm = scalar %suppress_cc ? 'compose' : 'auto';
416 die "Unknown --confirm setting: '$confirm'\n"
417 unless $confirm =~ /^(?:auto|cc|compose|always|never)/;
419 # Debugging, print out the suppressions.
420 if (0) {
421 print "suppressions:\n";
422 foreach my $entry (keys %suppress_cc) {
423 printf " %-5s -> $suppress_cc{$entry}\n", $entry;
427 my ($repoauthor, $repocommitter);
428 ($repoauthor) = Git::ident_person(@repo, 'author');
429 ($repocommitter) = Git::ident_person(@repo, 'committer');
431 # Verify the user input
433 foreach my $entry (@initial_to) {
434 die "Comma in --to entry: $entry'\n" unless $entry !~ m/,/;
437 foreach my $entry (@initial_cc) {
438 die "Comma in --cc entry: $entry'\n" unless $entry !~ m/,/;
441 foreach my $entry (@bcclist) {
442 die "Comma in --bcclist entry: $entry'\n" unless $entry !~ m/,/;
445 sub parse_address_line {
446 if ($have_mail_address) {
447 return map { $_->format } Mail::Address->parse($_[0]);
448 } else {
449 return split_addrs($_[0]);
453 sub split_addrs {
454 return quotewords('\s*,\s*', 1, @_);
457 my %aliases;
458 my %parse_alias = (
459 # multiline formats can be supported in the future
460 mutt => sub { my $fh = shift; while (<$fh>) {
461 if (/^\s*alias\s+(?:-group\s+\S+\s+)*(\S+)\s+(.*)$/) {
462 my ($alias, $addr) = ($1, $2);
463 $addr =~ s/#.*$//; # mutt allows # comments
464 # commas delimit multiple addresses
465 $aliases{$alias} = [ split_addrs($addr) ];
466 }}},
467 mailrc => sub { my $fh = shift; while (<$fh>) {
468 if (/^alias\s+(\S+)\s+(.*)$/) {
469 # spaces delimit multiple addresses
470 $aliases{$1} = [ quotewords('\s+', 0, $2) ];
471 }}},
472 pine => sub { my $fh = shift; my $f='\t[^\t]*';
473 for (my $x = ''; defined($x); $x = $_) {
474 chomp $x;
475 $x .= $1 while(defined($_ = <$fh>) && /^ +(.*)$/);
476 $x =~ /^(\S+)$f\t\(?([^\t]+?)\)?(:?$f){0,2}$/ or next;
477 $aliases{$1} = [ split_addrs($2) ];
479 elm => sub { my $fh = shift;
480 while (<$fh>) {
481 if (/^(\S+)\s+=\s+[^=]+=\s(\S+)/) {
482 my ($alias, $addr) = ($1, $2);
483 $aliases{$alias} = [ split_addrs($addr) ];
485 } },
487 gnus => sub { my $fh = shift; while (<$fh>) {
488 if (/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) {
489 $aliases{$1} = [ $2 ];
493 if (@alias_files and $aliasfiletype and defined $parse_alias{$aliasfiletype}) {
494 foreach my $file (@alias_files) {
495 open my $fh, '<', $file or die "opening $file: $!\n";
496 $parse_alias{$aliasfiletype}->($fh);
497 close $fh;
501 ($sender) = expand_aliases($sender) if defined $sender;
503 # returns 1 if the conflict must be solved using it as a format-patch argument
504 sub check_file_rev_conflict($) {
505 return unless $repo;
506 my $f = shift;
507 try {
508 $repo->command('rev-parse', '--verify', '--quiet', $f);
509 if (defined($format_patch)) {
510 return $format_patch;
512 die(<<EOF);
513 File '$f' exists but it could also be the range of commits
514 to produce patches for. Please disambiguate by...
516 * Saying "./$f" if you mean a file; or
517 * Giving --format-patch option if you mean a range.
519 } catch Git::Error::Command with {
520 return 0;
524 # Now that all the defaults are set, process the rest of the command line
525 # arguments and collect up the files that need to be processed.
526 my @rev_list_opts;
527 while (defined(my $f = shift @ARGV)) {
528 if ($f eq "--") {
529 push @rev_list_opts, "--", @ARGV;
530 @ARGV = ();
531 } elsif (-d $f and !check_file_rev_conflict($f)) {
532 opendir my $dh, $f
533 or die "Failed to opendir $f: $!";
535 push @files, grep { -f $_ } map { catfile($f, $_) }
536 sort readdir $dh;
537 closedir $dh;
538 } elsif ((-f $f or -p $f) and !check_file_rev_conflict($f)) {
539 push @files, $f;
540 } else {
541 push @rev_list_opts, $f;
545 if (@rev_list_opts) {
546 die "Cannot run git format-patch from outside a repository\n"
547 unless $repo;
548 push @files, $repo->command('format-patch', '-o', tempdir(CLEANUP => 1), @rev_list_opts);
551 if ($validate) {
552 foreach my $f (@files) {
553 unless (-p $f) {
554 my $error = validate_patch($f);
555 $error and die "fatal: $f: $error\nwarning: no patches were sent\n";
560 if (@files) {
561 unless ($quiet) {
562 print $_,"\n" for (@files);
564 } else {
565 print STDERR "\nNo patch files specified!\n\n";
566 usage();
569 sub get_patch_subject {
570 my $fn = shift;
571 open (my $fh, '<', $fn);
572 while (my $line = <$fh>) {
573 next unless ($line =~ /^Subject: (.*)$/);
574 close $fh;
575 return "GIT: $1\n";
577 close $fh;
578 die "No subject line in $fn ?";
581 if ($compose) {
582 # Note that this does not need to be secure, but we will make a small
583 # effort to have it be unique
584 $compose_filename = ($repo ?
585 tempfile(".gitsendemail.msg.XXXXXX", DIR => $repo->repo_path()) :
586 tempfile(".gitsendemail.msg.XXXXXX", DIR => "."))[1];
587 open my $c, ">", $compose_filename
588 or die "Failed to open for writing $compose_filename: $!";
591 my $tpl_sender = $sender || $repoauthor || $repocommitter || '';
592 my $tpl_subject = $initial_subject || '';
593 my $tpl_reply_to = $initial_reply_to || '';
595 print $c <<EOT;
596 From $tpl_sender # This line is ignored.
597 GIT: Lines beginning in "GIT:" will be removed.
598 GIT: Consider including an overall diffstat or table of contents
599 GIT: for the patch you are writing.
600 GIT:
601 GIT: Clear the body content if you don't wish to send a summary.
602 From: $tpl_sender
603 Subject: $tpl_subject
604 In-Reply-To: $tpl_reply_to
607 for my $f (@files) {
608 print $c get_patch_subject($f);
610 close $c;
612 if ($annotate) {
613 do_edit($compose_filename, @files);
614 } else {
615 do_edit($compose_filename);
618 open my $c2, ">", $compose_filename . ".final"
619 or die "Failed to open $compose_filename.final : " . $!;
621 open $c, "<", $compose_filename
622 or die "Failed to open $compose_filename : " . $!;
624 my $need_8bit_cte = file_has_nonascii($compose_filename);
625 my $in_body = 0;
626 my $summary_empty = 1;
627 while(<$c>) {
628 next if m/^GIT:/;
629 if ($in_body) {
630 $summary_empty = 0 unless (/^\n$/);
631 } elsif (/^\n$/) {
632 $in_body = 1;
633 if ($need_8bit_cte) {
634 print $c2 "MIME-Version: 1.0\n",
635 "Content-Type: text/plain; ",
636 "charset=UTF-8\n",
637 "Content-Transfer-Encoding: 8bit\n";
639 } elsif (/^MIME-Version:/i) {
640 $need_8bit_cte = 0;
641 } elsif (/^Subject:\s*(.+)\s*$/i) {
642 $initial_subject = $1;
643 my $subject = $initial_subject;
644 $_ = "Subject: " .
645 ($subject =~ /[^[:ascii:]]/ ?
646 quote_rfc2047($subject) :
647 $subject) .
648 "\n";
649 } elsif (/^In-Reply-To:\s*(.+)\s*$/i) {
650 $initial_reply_to = $1;
651 next;
652 } elsif (/^From:\s*(.+)\s*$/i) {
653 $sender = $1;
654 next;
655 } elsif (/^(?:To|Cc|Bcc):/i) {
656 print "To/Cc/Bcc fields are not interpreted yet, they have been ignored\n";
657 next;
659 print $c2 $_;
661 close $c;
662 close $c2;
664 if ($summary_empty) {
665 print "Summary email is empty, skipping it\n";
666 $compose = -1;
668 } elsif ($annotate) {
669 do_edit(@files);
672 sub ask {
673 my ($prompt, %arg) = @_;
674 my $valid_re = $arg{valid_re};
675 my $default = $arg{default};
676 my $resp;
677 my $i = 0;
678 return defined $default ? $default : undef
679 unless defined $term->IN and defined fileno($term->IN) and
680 defined $term->OUT and defined fileno($term->OUT);
681 while ($i++ < 10) {
682 $resp = $term->readline($prompt);
683 if (!defined $resp) { # EOF
684 print "\n";
685 return defined $default ? $default : undef;
687 if ($resp eq '' and defined $default) {
688 return $default;
690 if (!defined $valid_re or $resp =~ /$valid_re/) {
691 return $resp;
694 return undef;
697 my %broken_encoding;
699 sub file_declares_8bit_cte {
700 my $fn = shift;
701 open (my $fh, '<', $fn);
702 while (my $line = <$fh>) {
703 last if ($line =~ /^$/);
704 return 1 if ($line =~ /^Content-Transfer-Encoding: .*8bit.*$/);
706 close $fh;
707 return 0;
710 foreach my $f (@files) {
711 next unless (body_or_subject_has_nonascii($f)
712 && !file_declares_8bit_cte($f));
713 $broken_encoding{$f} = 1;
716 if (!defined $auto_8bit_encoding && scalar %broken_encoding) {
717 print "The following files are 8bit, but do not declare " .
718 "a Content-Transfer-Encoding.\n";
719 foreach my $f (sort keys %broken_encoding) {
720 print " $f\n";
722 $auto_8bit_encoding = ask("Which 8bit encoding should I declare [UTF-8]? ",
723 default => "UTF-8");
726 if (!$force) {
727 for my $f (@files) {
728 if (get_patch_subject($f) =~ /\Q*** SUBJECT HERE ***\E/) {
729 die "Refusing to send because the patch\n\t$f\n"
730 . "has the template subject '*** SUBJECT HERE ***'. "
731 . "Pass --force if you really want to send.\n";
736 my $prompting = 0;
737 if (!defined $sender) {
738 $sender = $repoauthor || $repocommitter || '';
739 $sender = ask("Who should the emails appear to be from? [$sender] ",
740 default => $sender);
741 print "Emails will be sent from: ", $sender, "\n";
742 $prompting++;
745 if (!@initial_to && !defined $to_cmd) {
746 my $to = ask("Who should the emails be sent to? ");
747 push @initial_to, parse_address_line($to) if defined $to; # sanitized/validated later
748 $prompting++;
751 sub expand_aliases {
752 return map { expand_one_alias($_) } @_;
755 my %EXPANDED_ALIASES;
756 sub expand_one_alias {
757 my $alias = shift;
758 if ($EXPANDED_ALIASES{$alias}) {
759 die "fatal: alias '$alias' expands to itself\n";
761 local $EXPANDED_ALIASES{$alias} = 1;
762 return $aliases{$alias} ? expand_aliases(@{$aliases{$alias}}) : $alias;
765 @initial_to = expand_aliases(@initial_to);
766 @initial_to = (map { sanitize_address($_) } @initial_to);
767 @initial_cc = expand_aliases(@initial_cc);
768 @bcclist = expand_aliases(@bcclist);
770 if ($thread && !defined $initial_reply_to && $prompting) {
771 $initial_reply_to = ask(
772 "Message-ID to be used as In-Reply-To for the first email? ");
774 if (defined $initial_reply_to) {
775 $initial_reply_to =~ s/^\s*<?//;
776 $initial_reply_to =~ s/>?\s*$//;
777 $initial_reply_to = "<$initial_reply_to>" if $initial_reply_to ne '';
780 if (!defined $smtp_server) {
781 foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
782 if (-x $_) {
783 $smtp_server = $_;
784 last;
787 $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
790 if ($compose && $compose > 0) {
791 @files = ($compose_filename . ".final", @files);
794 # Variables we set as part of the loop over files
795 our ($message_id, %mail, $subject, $reply_to, $references, $message,
796 $needs_confirm, $message_num, $ask_default);
798 sub extract_valid_address {
799 my $address = shift;
800 my $local_part_regexp = qr/[^<>"\s@]+/;
801 my $domain_regexp = qr/[^.<>"\s@]+(?:\.[^.<>"\s@]+)+/;
803 # check for a local address:
804 return $address if ($address =~ /^($local_part_regexp)$/);
806 $address =~ s/^\s*<(.*)>\s*$/$1/;
807 if ($have_email_valid) {
808 return scalar Email::Valid->address($address);
809 } else {
810 # less robust/correct than the monster regexp in Email::Valid,
811 # but still does a 99% job, and one less dependency
812 $address =~ /($local_part_regexp\@$domain_regexp)/;
813 return $1;
817 # Usually don't need to change anything below here.
819 # we make a "fake" message id by taking the current number
820 # of seconds since the beginning of Unix time and tacking on
821 # a random number to the end, in case we are called quicker than
822 # 1 second since the last time we were called.
824 # We'll setup a template for the message id, using the "from" address:
826 my ($message_id_stamp, $message_id_serial);
827 sub make_message_id {
828 my $uniq;
829 if (!defined $message_id_stamp) {
830 $message_id_stamp = sprintf("%s-%s", time, $$);
831 $message_id_serial = 0;
833 $message_id_serial++;
834 $uniq = "$message_id_stamp-$message_id_serial";
836 my $du_part;
837 for ($sender, $repocommitter, $repoauthor) {
838 $du_part = extract_valid_address(sanitize_address($_));
839 last if (defined $du_part and $du_part ne '');
841 if (not defined $du_part or $du_part eq '') {
842 require Sys::Hostname;
843 $du_part = 'user@' . Sys::Hostname::hostname();
845 my $message_id_template = "<%s-git-send-email-%s>";
846 $message_id = sprintf($message_id_template, $uniq, $du_part);
847 #print "new message id = $message_id\n"; # Was useful for debugging
852 $time = time - scalar $#files;
854 sub unquote_rfc2047 {
855 local ($_) = @_;
856 my $encoding;
857 if (s/=\?([^?]+)\?q\?(.*)\?=/$2/g) {
858 $encoding = $1;
859 s/_/ /g;
860 s/=([0-9A-F]{2})/chr(hex($1))/eg;
862 return wantarray ? ($_, $encoding) : $_;
865 sub quote_rfc2047 {
866 local $_ = shift;
867 my $encoding = shift || 'UTF-8';
868 s/([^-a-zA-Z0-9!*+\/])/sprintf("=%02X", ord($1))/eg;
869 s/(.*)/=\?$encoding\?q\?$1\?=/;
870 return $_;
873 sub is_rfc2047_quoted {
874 my $s = shift;
875 my $token = qr/[^][()<>@,;:"\/?.= \000-\037\177-\377]+/;
876 my $encoded_text = qr/[!->@-~]+/;
877 length($s) <= 75 &&
878 $s =~ m/^(?:"[[:ascii:]]*"|=\?$token\?$token\?$encoded_text\?=)$/o;
881 # use the simplest quoting being able to handle the recipient
882 sub sanitize_address {
883 my ($recipient) = @_;
884 my ($recipient_name, $recipient_addr) = ($recipient =~ /^(.*?)\s*(<.*)/);
886 if (not $recipient_name) {
887 return $recipient;
890 # if recipient_name is already quoted, do nothing
891 if (is_rfc2047_quoted($recipient_name)) {
892 return $recipient;
895 # rfc2047 is needed if a non-ascii char is included
896 if ($recipient_name =~ /[^[:ascii:]]/) {
897 $recipient_name =~ s/^"(.*)"$/$1/;
898 $recipient_name = quote_rfc2047($recipient_name);
901 # double quotes are needed if specials or CTLs are included
902 elsif ($recipient_name =~ /[][()<>@,;:\\".\000-\037\177]/) {
903 $recipient_name =~ s/(["\\\r])/\\$1/g;
904 $recipient_name = qq["$recipient_name"];
907 return "$recipient_name $recipient_addr";
911 # Returns the local Fully Qualified Domain Name (FQDN) if available.
913 # Tightly configured MTAa require that a caller sends a real DNS
914 # domain name that corresponds the IP address in the HELO/EHLO
915 # handshake. This is used to verify the connection and prevent
916 # spammers from trying to hide their identity. If the DNS and IP don't
917 # match, the receiveing MTA may deny the connection.
919 # Here is a deny example of Net::SMTP with the default "localhost.localdomain"
921 # Net::SMTP=GLOB(0x267ec28)>>> EHLO localhost.localdomain
922 # Net::SMTP=GLOB(0x267ec28)<<< 550 EHLO argument does not match calling host
924 # This maildomain*() code is based on ideas in Perl library Test::Reporter
925 # /usr/share/perl5/Test/Reporter/Mail/Util.pm ==> sub _maildomain ()
927 sub valid_fqdn {
928 my $domain = shift;
929 return defined $domain && !($^O eq 'darwin' && $domain =~ /\.local$/) && $domain =~ /\./;
932 sub maildomain_net {
933 my $maildomain;
935 if (eval { require Net::Domain; 1 }) {
936 my $domain = Net::Domain::domainname();
937 $maildomain = $domain if valid_fqdn($domain);
940 return $maildomain;
943 sub maildomain_mta {
944 my $maildomain;
946 if (eval { require Net::SMTP; 1 }) {
947 for my $host (qw(mailhost localhost)) {
948 my $smtp = Net::SMTP->new($host);
949 if (defined $smtp) {
950 my $domain = $smtp->domain;
951 $smtp->quit;
953 $maildomain = $domain if valid_fqdn($domain);
955 last if $maildomain;
960 return $maildomain;
963 sub maildomain {
964 return maildomain_net() || maildomain_mta() || 'localhost.localdomain';
967 # Returns 1 if the message was sent, and 0 otherwise.
968 # In actuality, the whole program dies when there
969 # is an error sending a message.
971 sub send_message {
972 my @recipients = unique_email_list(@to);
973 @cc = (grep { my $cc = extract_valid_address($_);
974 not grep { $cc eq $_ || $_ =~ /<\Q${cc}\E>$/ } @recipients
976 map { sanitize_address($_) }
977 @cc);
978 my $to = join (",\n\t", @recipients);
979 @recipients = unique_email_list(@recipients,@cc,@bcclist);
980 @recipients = (map { extract_valid_address($_) } @recipients);
981 my $date = format_2822_time($time++);
982 my $gitversion = '@@GIT_VERSION@@';
983 if ($gitversion =~ m/..GIT_VERSION../) {
984 $gitversion = Git::version();
987 my $cc = join(",\n\t", unique_email_list(@cc));
988 my $ccline = "";
989 if ($cc ne '') {
990 $ccline = "\nCc: $cc";
992 my $sanitized_sender = sanitize_address($sender);
993 make_message_id() unless defined($message_id);
995 my $header = "From: $sanitized_sender
996 To: $to${ccline}
997 Subject: $subject
998 Date: $date
999 Message-Id: $message_id
1000 X-Mailer: git-send-email $gitversion
1002 if ($reply_to) {
1004 $header .= "In-Reply-To: $reply_to\n";
1005 $header .= "References: $references\n";
1007 if (@xh) {
1008 $header .= join("\n", @xh) . "\n";
1011 my @sendmail_parameters = ('-i', @recipients);
1012 my $raw_from = $sanitized_sender;
1013 if (defined $envelope_sender && $envelope_sender ne "auto") {
1014 $raw_from = $envelope_sender;
1016 $raw_from = extract_valid_address($raw_from);
1017 unshift (@sendmail_parameters,
1018 '-f', $raw_from) if(defined $envelope_sender);
1020 if ($needs_confirm && !$dry_run) {
1021 print "\n$header\n";
1022 if ($needs_confirm eq "inform") {
1023 $confirm_unconfigured = 0; # squelch this message for the rest of this run
1024 $ask_default = "y"; # assume yes on EOF since user hasn't explicitly asked for confirmation
1025 print " The Cc list above has been expanded by additional\n";
1026 print " addresses found in the patch commit message. By default\n";
1027 print " send-email prompts before sending whenever this occurs.\n";
1028 print " This behavior is controlled by the sendemail.confirm\n";
1029 print " configuration setting.\n";
1030 print "\n";
1031 print " For additional information, run 'git send-email --help'.\n";
1032 print " To retain the current behavior, but squelch this message,\n";
1033 print " run 'git config --global sendemail.confirm auto'.\n\n";
1035 $_ = ask("Send this email? ([y]es|[n]o|[q]uit|[a]ll): ",
1036 valid_re => qr/^(?:yes|y|no|n|quit|q|all|a)/i,
1037 default => $ask_default);
1038 die "Send this email reply required" unless defined $_;
1039 if (/^n/i) {
1040 return 0;
1041 } elsif (/^q/i) {
1042 cleanup_compose_files();
1043 exit(0);
1044 } elsif (/^a/i) {
1045 $confirm = 'never';
1049 unshift (@sendmail_parameters, @smtp_server_options);
1051 if ($dry_run) {
1052 # We don't want to send the email.
1053 } elsif ($smtp_server =~ m#^/#) {
1054 my $pid = open my $sm, '|-';
1055 defined $pid or die $!;
1056 if (!$pid) {
1057 exec($smtp_server, @sendmail_parameters) or die $!;
1059 print $sm "$header\n$message";
1060 close $sm or die $!;
1061 } else {
1063 if (!defined $smtp_server) {
1064 die "The required SMTP server is not properly defined."
1067 if ($smtp_encryption eq 'ssl') {
1068 $smtp_server_port ||= 465; # ssmtp
1069 require Net::SMTP::SSL;
1070 $smtp_domain ||= maildomain();
1071 $smtp ||= Net::SMTP::SSL->new($smtp_server,
1072 Hello => $smtp_domain,
1073 Port => $smtp_server_port);
1075 else {
1076 require Net::SMTP;
1077 $smtp_domain ||= maildomain();
1078 $smtp ||= Net::SMTP->new((defined $smtp_server_port)
1079 ? "$smtp_server:$smtp_server_port"
1080 : $smtp_server,
1081 Hello => $smtp_domain,
1082 Debug => $debug_net_smtp);
1083 if ($smtp_encryption eq 'tls' && $smtp) {
1084 require Net::SMTP::SSL;
1085 $smtp->command('STARTTLS');
1086 $smtp->response();
1087 if ($smtp->code == 220) {
1088 $smtp = Net::SMTP::SSL->start_SSL($smtp)
1089 or die "STARTTLS failed! ".$smtp->message;
1090 $smtp_encryption = '';
1091 # Send EHLO again to receive fresh
1092 # supported commands
1093 $smtp->hello();
1094 } else {
1095 die "Server does not support STARTTLS! ".$smtp->message;
1100 if (!$smtp) {
1101 die "Unable to initialize SMTP properly. Check config and use --smtp-debug. ",
1102 "VALUES: server=$smtp_server ",
1103 "encryption=$smtp_encryption ",
1104 "hello=$smtp_domain",
1105 defined $smtp_server_port ? " port=$smtp_server_port" : "";
1108 if (defined $smtp_authuser) {
1109 # Workaround AUTH PLAIN/LOGIN interaction defect
1110 # with Authen::SASL::Cyrus
1111 eval {
1112 require Authen::SASL;
1113 Authen::SASL->import(qw(Perl));
1116 if (!defined $smtp_authpass) {
1118 system "stty -echo";
1120 do {
1121 print "Password: ";
1122 $_ = <STDIN>;
1123 print "\n";
1124 } while (!defined $_);
1126 chomp($smtp_authpass = $_);
1128 system "stty echo";
1131 $auth ||= $smtp->auth( $smtp_authuser, $smtp_authpass ) or die $smtp->message;
1134 $smtp->mail( $raw_from ) or die $smtp->message;
1135 $smtp->to( @recipients ) or die $smtp->message;
1136 $smtp->data or die $smtp->message;
1137 $smtp->datasend("$header\n$message") or die $smtp->message;
1138 $smtp->dataend() or die $smtp->message;
1139 $smtp->code =~ /250|200/ or die "Failed to send $subject\n".$smtp->message;
1141 if ($quiet) {
1142 printf (($dry_run ? "Dry-" : "")."Sent %s\n", $subject);
1143 } else {
1144 print (($dry_run ? "Dry-" : "")."OK. Log says:\n");
1145 if ($smtp_server !~ m#^/#) {
1146 print "Server: $smtp_server\n";
1147 print "MAIL FROM:<$raw_from>\n";
1148 foreach my $entry (@recipients) {
1149 print "RCPT TO:<$entry>\n";
1151 } else {
1152 print "Sendmail: $smtp_server ".join(' ',@sendmail_parameters)."\n";
1154 print $header, "\n";
1155 if ($smtp) {
1156 print "Result: ", $smtp->code, ' ',
1157 ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
1158 } else {
1159 print "Result: OK\n";
1163 return 1;
1166 $reply_to = $initial_reply_to;
1167 $references = $initial_reply_to || '';
1168 $subject = $initial_subject;
1169 $message_num = 0;
1171 foreach my $t (@files) {
1172 open my $fh, "<", $t or die "can't open file $t";
1174 my $author = undef;
1175 my $author_encoding;
1176 my $has_content_type;
1177 my $body_encoding;
1178 @to = ();
1179 @cc = ();
1180 @xh = ();
1181 my $input_format = undef;
1182 my @header = ();
1183 $message = "";
1184 $message_num++;
1185 # First unfold multiline header fields
1186 while(<$fh>) {
1187 last if /^\s*$/;
1188 if (/^\s+\S/ and @header) {
1189 chomp($header[$#header]);
1190 s/^\s+/ /;
1191 $header[$#header] .= $_;
1192 } else {
1193 push(@header, $_);
1196 # Now parse the header
1197 foreach(@header) {
1198 if (/^From /) {
1199 $input_format = 'mbox';
1200 next;
1202 chomp;
1203 if (!defined $input_format && /^[-A-Za-z]+:\s/) {
1204 $input_format = 'mbox';
1207 if (defined $input_format && $input_format eq 'mbox') {
1208 if (/^Subject:\s+(.*)$/) {
1209 $subject = $1;
1211 elsif (/^From:\s+(.*)$/) {
1212 ($author, $author_encoding) = unquote_rfc2047($1);
1213 next if $suppress_cc{'author'};
1214 next if $suppress_cc{'self'} and $author eq $sender;
1215 printf("(mbox) Adding cc: %s from line '%s'\n",
1216 $1, $_) unless $quiet;
1217 push @cc, $1;
1219 elsif (/^To:\s+(.*)$/) {
1220 foreach my $addr (parse_address_line($1)) {
1221 printf("(mbox) Adding to: %s from line '%s'\n",
1222 $addr, $_) unless $quiet;
1223 push @to, sanitize_address($addr);
1226 elsif (/^Cc:\s+(.*)$/) {
1227 foreach my $addr (parse_address_line($1)) {
1228 if (unquote_rfc2047($addr) eq $sender) {
1229 next if ($suppress_cc{'self'});
1230 } else {
1231 next if ($suppress_cc{'cc'});
1233 printf("(mbox) Adding cc: %s from line '%s'\n",
1234 $addr, $_) unless $quiet;
1235 push @cc, $addr;
1238 elsif (/^Content-type:/i) {
1239 $has_content_type = 1;
1240 if (/charset="?([^ "]+)/) {
1241 $body_encoding = $1;
1243 push @xh, $_;
1245 elsif (/^Message-Id: (.*)/i) {
1246 $message_id = $1;
1248 elsif (!/^Date:\s/ && /^[-A-Za-z]+:\s+\S/) {
1249 push @xh, $_;
1252 } else {
1253 # In the traditional
1254 # "send lots of email" format,
1255 # line 1 = cc
1256 # line 2 = subject
1257 # So let's support that, too.
1258 $input_format = 'lots';
1259 if (@cc == 0 && !$suppress_cc{'cc'}) {
1260 printf("(non-mbox) Adding cc: %s from line '%s'\n",
1261 $_, $_) unless $quiet;
1262 push @cc, $_;
1263 } elsif (!defined $subject) {
1264 $subject = $_;
1268 # Now parse the message body
1269 while(<$fh>) {
1270 $message .= $_;
1271 if (/^(Signed-off-by|Cc): (.*)$/i) {
1272 chomp;
1273 my ($what, $c) = ($1, $2);
1274 chomp $c;
1275 if ($c eq $sender) {
1276 next if ($suppress_cc{'self'});
1277 } else {
1278 next if $suppress_cc{'sob'} and $what =~ /Signed-off-by/i;
1279 next if $suppress_cc{'bodycc'} and $what =~ /Cc/i;
1281 push @cc, $c;
1282 printf("(body) Adding cc: %s from line '%s'\n",
1283 $c, $_) unless $quiet;
1286 close $fh;
1288 push @to, recipients_cmd("to-cmd", "to", $to_cmd, $t)
1289 if defined $to_cmd;
1290 push @cc, recipients_cmd("cc-cmd", "cc", $cc_cmd, $t)
1291 if defined $cc_cmd && !$suppress_cc{'cccmd'};
1293 if ($broken_encoding{$t} && !$has_content_type) {
1294 $has_content_type = 1;
1295 push @xh, "MIME-Version: 1.0",
1296 "Content-Type: text/plain; charset=$auto_8bit_encoding",
1297 "Content-Transfer-Encoding: 8bit";
1298 $body_encoding = $auto_8bit_encoding;
1301 if ($broken_encoding{$t} && !is_rfc2047_quoted($subject)) {
1302 $subject = quote_rfc2047($subject, $auto_8bit_encoding);
1305 if (defined $author and $author ne $sender) {
1306 $message = "From: $author\n\n$message";
1307 if (defined $author_encoding) {
1308 if ($has_content_type) {
1309 if ($body_encoding eq $author_encoding) {
1310 # ok, we already have the right encoding
1312 else {
1313 # uh oh, we should re-encode
1316 else {
1317 $has_content_type = 1;
1318 push @xh,
1319 'MIME-Version: 1.0',
1320 "Content-Type: text/plain; charset=$author_encoding",
1321 'Content-Transfer-Encoding: 8bit';
1326 $needs_confirm = (
1327 $confirm eq "always" or
1328 ($confirm =~ /^(?:auto|cc)$/ && @cc) or
1329 ($confirm =~ /^(?:auto|compose)$/ && $compose && $message_num == 1));
1330 $needs_confirm = "inform" if ($needs_confirm && $confirm_unconfigured && @cc);
1332 @to = (@initial_to, @to);
1333 @cc = (@initial_cc, @cc);
1335 my $message_was_sent = send_message();
1337 # set up for the next message
1338 if ($thread && $message_was_sent &&
1339 (chain_reply_to() || !defined $reply_to || length($reply_to) == 0 ||
1340 $message_num == 1)) {
1341 $reply_to = $message_id;
1342 if (length $references > 0) {
1343 $references .= "\n $message_id";
1344 } else {
1345 $references = "$message_id";
1348 $message_id = undef;
1351 # Execute a command (e.g. $to_cmd) to get a list of email addresses
1352 # and return a results array
1353 sub recipients_cmd {
1354 my ($prefix, $what, $cmd, $file) = @_;
1356 my $sanitized_sender = sanitize_address($sender);
1357 my @addresses = ();
1358 open my $fh, "$cmd \Q$file\E |"
1359 or die "($prefix) Could not execute '$cmd'";
1360 while (my $address = <$fh>) {
1361 $address =~ s/^\s*//g;
1362 $address =~ s/\s*$//g;
1363 $address = sanitize_address($address);
1364 next if ($address eq $sanitized_sender and $suppress_from);
1365 push @addresses, $address;
1366 printf("($prefix) Adding %s: %s from: '%s'\n",
1367 $what, $address, $cmd) unless $quiet;
1369 close $fh
1370 or die "($prefix) failed to close pipe to '$cmd'";
1371 return @addresses;
1374 cleanup_compose_files();
1376 sub cleanup_compose_files {
1377 unlink($compose_filename, $compose_filename . ".final") if $compose;
1380 $smtp->quit if $smtp;
1382 sub unique_email_list {
1383 my %seen;
1384 my @emails;
1386 foreach my $entry (@_) {
1387 if (my $clean = extract_valid_address($entry)) {
1388 $seen{$clean} ||= 0;
1389 next if $seen{$clean}++;
1390 push @emails, $entry;
1391 } else {
1392 print STDERR "W: unable to extract a valid address",
1393 " from: $entry\n";
1396 return @emails;
1399 sub validate_patch {
1400 my $fn = shift;
1401 open(my $fh, '<', $fn)
1402 or die "unable to open $fn: $!\n";
1403 while (my $line = <$fh>) {
1404 if (length($line) > 998) {
1405 return "$.: patch contains a line longer than 998 characters";
1408 return undef;
1411 sub file_has_nonascii {
1412 my $fn = shift;
1413 open(my $fh, '<', $fn)
1414 or die "unable to open $fn: $!\n";
1415 while (my $line = <$fh>) {
1416 return 1 if $line =~ /[^[:ascii:]]/;
1418 return 0;
1421 sub body_or_subject_has_nonascii {
1422 my $fn = shift;
1423 open(my $fh, '<', $fn)
1424 or die "unable to open $fn: $!\n";
1425 while (my $line = <$fh>) {
1426 last if $line =~ /^$/;
1427 return 1 if $line =~ /^Subject.*[^[:ascii:]]/;
1429 while (my $line = <$fh>) {
1430 return 1 if $line =~ /[^[:ascii:]]/;
1432 return 0;