send-email: Cleanup smtp-domain and add config
[git/jnareb-git.git] / git-send-email.perl
blob0f23ed380f93383fd3e085149e482be54964f789
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 --to <str> * Email To:
51 --cc <str> * Email Cc:
52 --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,@cc,@initial_cc,@bcclist,@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 = Git::command_oneline('var', 'GIT_EDITOR');
169 sub do_edit {
170 if (defined($multiedit) && !$multiedit) {
171 map {
172 system('sh', '-c', $editor.' "$@"', $editor, $_);
173 if (($? & 127) || ($? >> 8)) {
174 die("the editor exited uncleanly, aborting everything");
176 } @_;
177 } else {
178 system('sh', '-c', $editor.' "$@"', $editor, @_);
179 if (($? & 127) || ($? >> 8)) {
180 die("the editor exited uncleanly, aborting everything");
185 # Variables with corresponding config settings
186 my ($thread, $chain_reply_to, $suppress_from, $signed_off_by_cc, $cc_cmd);
187 my ($smtp_server, $smtp_server_port, $smtp_authuser, $smtp_encryption);
188 my ($identity, $aliasfiletype, @alias_files, @smtp_host_parts, $smtp_domain);
189 my ($validate, $confirm);
190 my (@suppress_cc);
192 my ($debug_net_smtp) = 0; # Net::SMTP, see send_message()
194 my $not_set_by_user = "true but not set by the user";
196 my %config_bool_settings = (
197 "thread" => [\$thread, 1],
198 "chainreplyto" => [\$chain_reply_to, $not_set_by_user],
199 "suppressfrom" => [\$suppress_from, undef],
200 "signedoffbycc" => [\$signed_off_by_cc, undef],
201 "signedoffcc" => [\$signed_off_by_cc, undef], # Deprecated
202 "validate" => [\$validate, 1],
205 my %config_settings = (
206 "smtpserver" => \$smtp_server,
207 "smtpserverport" => \$smtp_server_port,
208 "smtpuser" => \$smtp_authuser,
209 "smtppass" => \$smtp_authpass,
210 "smtpdomain" => \$smtp_domain,
211 "to" => \@to,
212 "cc" => \@initial_cc,
213 "cccmd" => \$cc_cmd,
214 "aliasfiletype" => \$aliasfiletype,
215 "bcc" => \@bcclist,
216 "aliasesfile" => \@alias_files,
217 "suppresscc" => \@suppress_cc,
218 "envelopesender" => \$envelope_sender,
219 "multiedit" => \$multiedit,
220 "confirm" => \$confirm,
221 "from" => \$sender,
224 # Help users prepare for 1.7.0
225 sub chain_reply_to {
226 if (defined $chain_reply_to &&
227 $chain_reply_to eq $not_set_by_user) {
228 print STDERR
229 "In git 1.7.0, the default has changed to --no-chain-reply-to\n" .
230 "Set sendemail.chainreplyto configuration variable to true if\n" .
231 "you want to keep --chain-reply-to as your default.\n";
232 $chain_reply_to = 0;
234 return $chain_reply_to;
237 # Handle Uncouth Termination
238 sub signal_handler {
240 # Make text normal
241 print color("reset"), "\n";
243 # SMTP password masked
244 system "stty echo";
246 # tmp files from --compose
247 if (defined $compose_filename) {
248 if (-e $compose_filename) {
249 print "'$compose_filename' contains an intermediate version of the email you were composing.\n";
251 if (-e ($compose_filename . ".final")) {
252 print "'$compose_filename.final' contains the composed email.\n"
256 exit;
259 $SIG{TERM} = \&signal_handler;
260 $SIG{INT} = \&signal_handler;
262 # Begin by accumulating all the variables (defined above), that we will end up
263 # needing, first, from the command line:
265 my $rc = GetOptions("sender|from=s" => \$sender,
266 "in-reply-to=s" => \$initial_reply_to,
267 "subject=s" => \$initial_subject,
268 "to=s" => \@to,
269 "cc=s" => \@initial_cc,
270 "bcc=s" => \@bcclist,
271 "chain-reply-to!" => \$chain_reply_to,
272 "smtp-server=s" => \$smtp_server,
273 "smtp-server-port=s" => \$smtp_server_port,
274 "smtp-user=s" => \$smtp_authuser,
275 "smtp-pass:s" => \$smtp_authpass,
276 "smtp-ssl" => sub { $smtp_encryption = 'ssl' },
277 "smtp-encryption=s" => \$smtp_encryption,
278 "smtp-debug:i" => \$debug_net_smtp,
279 "smtp-domain:s" => \$smtp_domain,
280 "identity=s" => \$identity,
281 "annotate" => \$annotate,
282 "compose" => \$compose,
283 "quiet" => \$quiet,
284 "cc-cmd=s" => \$cc_cmd,
285 "suppress-from!" => \$suppress_from,
286 "suppress-cc=s" => \@suppress_cc,
287 "signed-off-cc|signed-off-by-cc!" => \$signed_off_by_cc,
288 "confirm=s" => \$confirm,
289 "dry-run" => \$dry_run,
290 "envelope-sender=s" => \$envelope_sender,
291 "thread!" => \$thread,
292 "validate!" => \$validate,
293 "format-patch!" => \$format_patch,
296 unless ($rc) {
297 usage();
300 die "Cannot run git format-patch from outside a repository\n"
301 if $format_patch and not $repo;
303 # Now, let's fill any that aren't set in with defaults:
305 sub read_config {
306 my ($prefix) = @_;
308 foreach my $setting (keys %config_bool_settings) {
309 my $target = $config_bool_settings{$setting}->[0];
310 $$target = Git::config_bool(@repo, "$prefix.$setting") unless (defined $$target);
313 foreach my $setting (keys %config_settings) {
314 my $target = $config_settings{$setting};
315 if (ref($target) eq "ARRAY") {
316 unless (@$target) {
317 my @values = Git::config(@repo, "$prefix.$setting");
318 @$target = @values if (@values && defined $values[0]);
321 else {
322 $$target = Git::config(@repo, "$prefix.$setting") unless (defined $$target);
326 if (!defined $smtp_encryption) {
327 my $enc = Git::config(@repo, "$prefix.smtpencryption");
328 if (defined $enc) {
329 $smtp_encryption = $enc;
330 } elsif (Git::config_bool(@repo, "$prefix.smtpssl")) {
331 $smtp_encryption = 'ssl';
336 # read configuration from [sendemail "$identity"], fall back on [sendemail]
337 $identity = Git::config(@repo, "sendemail.identity") unless (defined $identity);
338 read_config("sendemail.$identity") if (defined $identity);
339 read_config("sendemail");
341 # fall back on builtin bool defaults
342 foreach my $setting (values %config_bool_settings) {
343 ${$setting->[0]} = $setting->[1] unless (defined (${$setting->[0]}));
346 # 'default' encryption is none -- this only prevents a warning
347 $smtp_encryption = '' unless (defined $smtp_encryption);
349 # Set CC suppressions
350 my(%suppress_cc);
351 if (@suppress_cc) {
352 foreach my $entry (@suppress_cc) {
353 die "Unknown --suppress-cc field: '$entry'\n"
354 unless $entry =~ /^(all|cccmd|cc|author|self|sob|body|bodycc)$/;
355 $suppress_cc{$entry} = 1;
359 if ($suppress_cc{'all'}) {
360 foreach my $entry (qw (cccmd cc author self sob body bodycc)) {
361 $suppress_cc{$entry} = 1;
363 delete $suppress_cc{'all'};
366 # If explicit old-style ones are specified, they trump --suppress-cc.
367 $suppress_cc{'self'} = $suppress_from if defined $suppress_from;
368 $suppress_cc{'sob'} = !$signed_off_by_cc if defined $signed_off_by_cc;
370 if ($suppress_cc{'body'}) {
371 foreach my $entry (qw (sob bodycc)) {
372 $suppress_cc{$entry} = 1;
374 delete $suppress_cc{'body'};
377 # Set confirm's default value
378 my $confirm_unconfigured = !defined $confirm;
379 if ($confirm_unconfigured) {
380 $confirm = scalar %suppress_cc ? 'compose' : 'auto';
382 die "Unknown --confirm setting: '$confirm'\n"
383 unless $confirm =~ /^(?:auto|cc|compose|always|never)/;
385 # Debugging, print out the suppressions.
386 if (0) {
387 print "suppressions:\n";
388 foreach my $entry (keys %suppress_cc) {
389 printf " %-5s -> $suppress_cc{$entry}\n", $entry;
393 my ($repoauthor, $repocommitter);
394 ($repoauthor) = Git::ident_person(@repo, 'author');
395 ($repocommitter) = Git::ident_person(@repo, 'committer');
397 # Verify the user input
399 foreach my $entry (@to) {
400 die "Comma in --to entry: $entry'\n" unless $entry !~ m/,/;
403 foreach my $entry (@initial_cc) {
404 die "Comma in --cc entry: $entry'\n" unless $entry !~ m/,/;
407 foreach my $entry (@bcclist) {
408 die "Comma in --bcclist entry: $entry'\n" unless $entry !~ m/,/;
411 sub parse_address_line {
412 if ($have_mail_address) {
413 return map { $_->format } Mail::Address->parse($_[0]);
414 } else {
415 return split_addrs($_[0]);
419 sub split_addrs {
420 return quotewords('\s*,\s*', 1, @_);
423 my %aliases;
424 my %parse_alias = (
425 # multiline formats can be supported in the future
426 mutt => sub { my $fh = shift; while (<$fh>) {
427 if (/^\s*alias\s+(?:-group\s+\S+\s+)*(\S+)\s+(.*)$/) {
428 my ($alias, $addr) = ($1, $2);
429 $addr =~ s/#.*$//; # mutt allows # comments
430 # commas delimit multiple addresses
431 $aliases{$alias} = [ split_addrs($addr) ];
432 }}},
433 mailrc => sub { my $fh = shift; while (<$fh>) {
434 if (/^alias\s+(\S+)\s+(.*)$/) {
435 # spaces delimit multiple addresses
436 $aliases{$1} = [ quotewords('\s+', 0, $2) ];
437 }}},
438 pine => sub { my $fh = shift; my $f='\t[^\t]*';
439 for (my $x = ''; defined($x); $x = $_) {
440 chomp $x;
441 $x .= $1 while(defined($_ = <$fh>) && /^ +(.*)$/);
442 $x =~ /^(\S+)$f\t\(?([^\t]+?)\)?(:?$f){0,2}$/ or next;
443 $aliases{$1} = [ split_addrs($2) ];
445 elm => sub { my $fh = shift;
446 while (<$fh>) {
447 if (/^(\S+)\s+=\s+[^=]+=\s(\S+)/) {
448 my ($alias, $addr) = ($1, $2);
449 $aliases{$alias} = [ split_addrs($addr) ];
451 } },
453 gnus => sub { my $fh = shift; while (<$fh>) {
454 if (/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) {
455 $aliases{$1} = [ $2 ];
459 if (@alias_files and $aliasfiletype and defined $parse_alias{$aliasfiletype}) {
460 foreach my $file (@alias_files) {
461 open my $fh, '<', $file or die "opening $file: $!\n";
462 $parse_alias{$aliasfiletype}->($fh);
463 close $fh;
467 ($sender) = expand_aliases($sender) if defined $sender;
469 # returns 1 if the conflict must be solved using it as a format-patch argument
470 sub check_file_rev_conflict($) {
471 return unless $repo;
472 my $f = shift;
473 try {
474 $repo->command('rev-parse', '--verify', '--quiet', $f);
475 if (defined($format_patch)) {
476 return $format_patch;
478 die(<<EOF);
479 File '$f' exists but it could also be the range of commits
480 to produce patches for. Please disambiguate by...
482 * Saying "./$f" if you mean a file; or
483 * Giving --format-patch option if you mean a range.
485 } catch Git::Error::Command with {
486 return 0;
490 # Now that all the defaults are set, process the rest of the command line
491 # arguments and collect up the files that need to be processed.
492 my @rev_list_opts;
493 while (defined(my $f = shift @ARGV)) {
494 if ($f eq "--") {
495 push @rev_list_opts, "--", @ARGV;
496 @ARGV = ();
497 } elsif (-d $f and !check_file_rev_conflict($f)) {
498 opendir(DH,$f)
499 or die "Failed to opendir $f: $!";
501 push @files, grep { -f $_ } map { +$f . "/" . $_ }
502 sort readdir(DH);
503 closedir(DH);
504 } elsif ((-f $f or -p $f) and !check_file_rev_conflict($f)) {
505 push @files, $f;
506 } else {
507 push @rev_list_opts, $f;
511 if (@rev_list_opts) {
512 die "Cannot run git format-patch from outside a repository\n"
513 unless $repo;
514 push @files, $repo->command('format-patch', '-o', tempdir(CLEANUP => 1), @rev_list_opts);
517 if ($validate) {
518 foreach my $f (@files) {
519 unless (-p $f) {
520 my $error = validate_patch($f);
521 $error and die "fatal: $f: $error\nwarning: no patches were sent\n";
526 if (@files) {
527 unless ($quiet) {
528 print $_,"\n" for (@files);
530 } else {
531 print STDERR "\nNo patch files specified!\n\n";
532 usage();
535 sub get_patch_subject($) {
536 my $fn = shift;
537 open (my $fh, '<', $fn);
538 while (my $line = <$fh>) {
539 next unless ($line =~ /^Subject: (.*)$/);
540 close $fh;
541 return "GIT: $1\n";
543 close $fh;
544 die "No subject line in $fn ?";
547 if ($compose) {
548 # Note that this does not need to be secure, but we will make a small
549 # effort to have it be unique
550 $compose_filename = ($repo ?
551 tempfile(".gitsendemail.msg.XXXXXX", DIR => $repo->repo_path()) :
552 tempfile(".gitsendemail.msg.XXXXXX", DIR => "."))[1];
553 open(C,">",$compose_filename)
554 or die "Failed to open for writing $compose_filename: $!";
557 my $tpl_sender = $sender || $repoauthor || $repocommitter || '';
558 my $tpl_subject = $initial_subject || '';
559 my $tpl_reply_to = $initial_reply_to || '';
561 print C <<EOT;
562 From $tpl_sender # This line is ignored.
563 GIT: Lines beginning in "GIT:" will be removed.
564 GIT: Consider including an overall diffstat or table of contents
565 GIT: for the patch you are writing.
566 GIT:
567 GIT: Clear the body content if you don't wish to send a summary.
568 From: $tpl_sender
569 Subject: $tpl_subject
570 In-Reply-To: $tpl_reply_to
573 for my $f (@files) {
574 print C get_patch_subject($f);
576 close(C);
578 if ($annotate) {
579 do_edit($compose_filename, @files);
580 } else {
581 do_edit($compose_filename);
584 open(C2,">",$compose_filename . ".final")
585 or die "Failed to open $compose_filename.final : " . $!;
587 open(C,"<",$compose_filename)
588 or die "Failed to open $compose_filename : " . $!;
590 my $need_8bit_cte = file_has_nonascii($compose_filename);
591 my $in_body = 0;
592 my $summary_empty = 1;
593 while(<C>) {
594 next if m/^GIT:/;
595 if ($in_body) {
596 $summary_empty = 0 unless (/^\n$/);
597 } elsif (/^\n$/) {
598 $in_body = 1;
599 if ($need_8bit_cte) {
600 print C2 "MIME-Version: 1.0\n",
601 "Content-Type: text/plain; ",
602 "charset=UTF-8\n",
603 "Content-Transfer-Encoding: 8bit\n";
605 } elsif (/^MIME-Version:/i) {
606 $need_8bit_cte = 0;
607 } elsif (/^Subject:\s*(.+)\s*$/i) {
608 $initial_subject = $1;
609 my $subject = $initial_subject;
610 $_ = "Subject: " .
611 ($subject =~ /[^[:ascii:]]/ ?
612 quote_rfc2047($subject) :
613 $subject) .
614 "\n";
615 } elsif (/^In-Reply-To:\s*(.+)\s*$/i) {
616 $initial_reply_to = $1;
617 next;
618 } elsif (/^From:\s*(.+)\s*$/i) {
619 $sender = $1;
620 next;
621 } elsif (/^(?:To|Cc|Bcc):/i) {
622 print "To/Cc/Bcc fields are not interpreted yet, they have been ignored\n";
623 next;
625 print C2 $_;
627 close(C);
628 close(C2);
630 if ($summary_empty) {
631 print "Summary email is empty, skipping it\n";
632 $compose = -1;
634 } elsif ($annotate) {
635 do_edit(@files);
638 sub ask {
639 my ($prompt, %arg) = @_;
640 my $valid_re = $arg{valid_re};
641 my $default = $arg{default};
642 my $resp;
643 my $i = 0;
644 return defined $default ? $default : undef
645 unless defined $term->IN and defined fileno($term->IN) and
646 defined $term->OUT and defined fileno($term->OUT);
647 while ($i++ < 10) {
648 $resp = $term->readline($prompt);
649 if (!defined $resp) { # EOF
650 print "\n";
651 return defined $default ? $default : undef;
653 if ($resp eq '' and defined $default) {
654 return $default;
656 if (!defined $valid_re or $resp =~ /$valid_re/) {
657 return $resp;
660 return undef;
663 my $prompting = 0;
664 if (!defined $sender) {
665 $sender = $repoauthor || $repocommitter || '';
666 $sender = ask("Who should the emails appear to be from? [$sender] ",
667 default => $sender);
668 print "Emails will be sent from: ", $sender, "\n";
669 $prompting++;
672 if (!@to) {
673 my $to = ask("Who should the emails be sent to? ");
674 push @to, parse_address_line($to) if defined $to; # sanitized/validated later
675 $prompting++;
678 sub expand_aliases {
679 return map { expand_one_alias($_) } @_;
682 my %EXPANDED_ALIASES;
683 sub expand_one_alias {
684 my $alias = shift;
685 if ($EXPANDED_ALIASES{$alias}) {
686 die "fatal: alias '$alias' expands to itself\n";
688 local $EXPANDED_ALIASES{$alias} = 1;
689 return $aliases{$alias} ? expand_aliases(@{$aliases{$alias}}) : $alias;
692 @to = expand_aliases(@to);
693 @to = (map { sanitize_address($_) } @to);
694 @initial_cc = expand_aliases(@initial_cc);
695 @bcclist = expand_aliases(@bcclist);
697 if ($thread && !defined $initial_reply_to && $prompting) {
698 $initial_reply_to = ask(
699 "Message-ID to be used as In-Reply-To for the first email? ");
701 if (defined $initial_reply_to) {
702 $initial_reply_to =~ s/^\s*<?//;
703 $initial_reply_to =~ s/>?\s*$//;
704 $initial_reply_to = "<$initial_reply_to>" if $initial_reply_to ne '';
707 if (!defined $smtp_server) {
708 foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
709 if (-x $_) {
710 $smtp_server = $_;
711 last;
714 $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
717 if ($compose && $compose > 0) {
718 @files = ($compose_filename . ".final", @files);
721 # Variables we set as part of the loop over files
722 our ($message_id, %mail, $subject, $reply_to, $references, $message,
723 $needs_confirm, $message_num, $ask_default);
725 sub extract_valid_address {
726 my $address = shift;
727 my $local_part_regexp = '[^<>"\s@]+';
728 my $domain_regexp = '[^.<>"\s@]+(?:\.[^.<>"\s@]+)+';
730 # check for a local address:
731 return $address if ($address =~ /^($local_part_regexp)$/);
733 $address =~ s/^\s*<(.*)>\s*$/$1/;
734 if ($have_email_valid) {
735 return scalar Email::Valid->address($address);
736 } else {
737 # less robust/correct than the monster regexp in Email::Valid,
738 # but still does a 99% job, and one less dependency
739 $address =~ /($local_part_regexp\@$domain_regexp)/;
740 return $1;
744 # Usually don't need to change anything below here.
746 # we make a "fake" message id by taking the current number
747 # of seconds since the beginning of Unix time and tacking on
748 # a random number to the end, in case we are called quicker than
749 # 1 second since the last time we were called.
751 # We'll setup a template for the message id, using the "from" address:
753 my ($message_id_stamp, $message_id_serial);
754 sub make_message_id {
755 my $uniq;
756 if (!defined $message_id_stamp) {
757 $message_id_stamp = sprintf("%s-%s", time, $$);
758 $message_id_serial = 0;
760 $message_id_serial++;
761 $uniq = "$message_id_stamp-$message_id_serial";
763 my $du_part;
764 for ($sender, $repocommitter, $repoauthor) {
765 $du_part = extract_valid_address(sanitize_address($_));
766 last if (defined $du_part and $du_part ne '');
768 if (not defined $du_part or $du_part eq '') {
769 use Sys::Hostname qw();
770 $du_part = 'user@' . Sys::Hostname::hostname();
772 my $message_id_template = "<%s-git-send-email-%s>";
773 $message_id = sprintf($message_id_template, $uniq, $du_part);
774 #print "new message id = $message_id\n"; # Was useful for debugging
779 $time = time - scalar $#files;
781 sub unquote_rfc2047 {
782 local ($_) = @_;
783 my $encoding;
784 if (s/=\?([^?]+)\?q\?(.*)\?=/$2/g) {
785 $encoding = $1;
786 s/_/ /g;
787 s/=([0-9A-F]{2})/chr(hex($1))/eg;
789 return wantarray ? ($_, $encoding) : $_;
792 sub quote_rfc2047 {
793 local $_ = shift;
794 my $encoding = shift || 'UTF-8';
795 s/([^-a-zA-Z0-9!*+\/])/sprintf("=%02X", ord($1))/eg;
796 s/(.*)/=\?$encoding\?q\?$1\?=/;
797 return $_;
800 sub is_rfc2047_quoted {
801 my $s = shift;
802 my $token = '[^][()<>@,;:"\/?.= \000-\037\177-\377]+';
803 my $encoded_text = '[!->@-~]+';
804 length($s) <= 75 &&
805 $s =~ m/^(?:"[[:ascii:]]*"|=\?$token\?$token\?$encoded_text\?=)$/o;
808 # use the simplest quoting being able to handle the recipient
809 sub sanitize_address {
810 my ($recipient) = @_;
811 my ($recipient_name, $recipient_addr) = ($recipient =~ /^(.*?)\s*(<.*)/);
813 if (not $recipient_name) {
814 return "$recipient";
817 # if recipient_name is already quoted, do nothing
818 if (is_rfc2047_quoted($recipient_name)) {
819 return $recipient;
822 # rfc2047 is needed if a non-ascii char is included
823 if ($recipient_name =~ /[^[:ascii:]]/) {
824 $recipient_name =~ s/^"(.*)"$/$1/;
825 $recipient_name = quote_rfc2047($recipient_name);
828 # double quotes are needed if specials or CTLs are included
829 elsif ($recipient_name =~ /[][()<>@,;:\\".\000-\037\177]/) {
830 $recipient_name =~ s/(["\\\r])/\\$1/g;
831 $recipient_name = "\"$recipient_name\"";
834 return "$recipient_name $recipient_addr";
838 # Returns the local Fully Qualified Domain Name (FQDN) if available.
840 # Tightly configured MTAa require that a caller sends a real DNS
841 # domain name that corresponds the IP address in the HELO/EHLO
842 # handshake. This is used to verify the connection and prevent
843 # spammers from trying to hide their identity. If the DNS and IP don't
844 # match, the receiveing MTA may deny the connection.
846 # Here is a deny example of Net::SMTP with the default "localhost.localdomain"
848 # Net::SMTP=GLOB(0x267ec28)>>> EHLO localhost.localdomain
849 # Net::SMTP=GLOB(0x267ec28)<<< 550 EHLO argument does not match calling host
851 # This maildomain*() code is based on ideas in Perl library Test::Reporter
852 # /usr/share/perl5/Test/Reporter/Mail/Util.pm ==> sub _maildomain ()
854 sub valid_fqdn {
855 my $domain = shift;
856 return !($^O eq 'darwin' && $domain =~ /\.local$/) && $domain =~ /\./;
859 sub maildomain_net {
860 my $maildomain;
862 if (eval { require Net::Domain; 1 }) {
863 my $domain = Net::Domain::domainname();
864 $maildomain = $domain if valid_fqdn($domain);
867 return $maildomain;
870 sub maildomain_mta {
871 my $maildomain;
873 if (eval { require Net::SMTP; 1 }) {
874 for my $host (qw(mailhost localhost)) {
875 my $smtp = Net::SMTP->new($host);
876 if (defined $smtp) {
877 my $domain = $smtp->domain;
878 $smtp->quit;
880 $maildomain = $domain if valid_fqdn($domain);
882 last if $maildomain;
887 return $maildomain;
890 sub maildomain {
891 return maildomain_net() || maildomain_mta() || 'localhost.localdomain';
894 # Returns 1 if the message was sent, and 0 otherwise.
895 # In actuality, the whole program dies when there
896 # is an error sending a message.
898 sub send_message {
899 my @recipients = unique_email_list(@to);
900 @cc = (grep { my $cc = extract_valid_address($_);
901 not grep { $cc eq $_ } @recipients
903 map { sanitize_address($_) }
904 @cc);
905 my $to = join (",\n\t", @recipients);
906 @recipients = unique_email_list(@recipients,@cc,@bcclist);
907 @recipients = (map { extract_valid_address($_) } @recipients);
908 my $date = format_2822_time($time++);
909 my $gitversion = '@@GIT_VERSION@@';
910 if ($gitversion =~ m/..GIT_VERSION../) {
911 $gitversion = Git::version();
914 my $cc = join(",\n\t", unique_email_list(@cc));
915 my $ccline = "";
916 if ($cc ne '') {
917 $ccline = "\nCc: $cc";
919 my $sanitized_sender = sanitize_address($sender);
920 make_message_id() unless defined($message_id);
922 my $header = "From: $sanitized_sender
923 To: $to${ccline}
924 Subject: $subject
925 Date: $date
926 Message-Id: $message_id
927 X-Mailer: git-send-email $gitversion
929 if ($reply_to) {
931 $header .= "In-Reply-To: $reply_to\n";
932 $header .= "References: $references\n";
934 if (@xh) {
935 $header .= join("\n", @xh) . "\n";
938 my @sendmail_parameters = ('-i', @recipients);
939 my $raw_from = $sanitized_sender;
940 if (defined $envelope_sender && $envelope_sender ne "auto") {
941 $raw_from = $envelope_sender;
943 $raw_from = extract_valid_address($raw_from);
944 unshift (@sendmail_parameters,
945 '-f', $raw_from) if(defined $envelope_sender);
947 if ($needs_confirm && !$dry_run) {
948 print "\n$header\n";
949 if ($needs_confirm eq "inform") {
950 $confirm_unconfigured = 0; # squelch this message for the rest of this run
951 $ask_default = "y"; # assume yes on EOF since user hasn't explicitly asked for confirmation
952 print " The Cc list above has been expanded by additional\n";
953 print " addresses found in the patch commit message. By default\n";
954 print " send-email prompts before sending whenever this occurs.\n";
955 print " This behavior is controlled by the sendemail.confirm\n";
956 print " configuration setting.\n";
957 print "\n";
958 print " For additional information, run 'git send-email --help'.\n";
959 print " To retain the current behavior, but squelch this message,\n";
960 print " run 'git config --global sendemail.confirm auto'.\n\n";
962 $_ = ask("Send this email? ([y]es|[n]o|[q]uit|[a]ll): ",
963 valid_re => qr/^(?:yes|y|no|n|quit|q|all|a)/i,
964 default => $ask_default);
965 die "Send this email reply required" unless defined $_;
966 if (/^n/i) {
967 return 0;
968 } elsif (/^q/i) {
969 cleanup_compose_files();
970 exit(0);
971 } elsif (/^a/i) {
972 $confirm = 'never';
976 if ($dry_run) {
977 # We don't want to send the email.
978 } elsif ($smtp_server =~ m#^/#) {
979 my $pid = open my $sm, '|-';
980 defined $pid or die $!;
981 if (!$pid) {
982 exec($smtp_server, @sendmail_parameters) or die $!;
984 print $sm "$header\n$message";
985 close $sm or die $?;
986 } else {
988 if (!defined $smtp_server) {
989 die "The required SMTP server is not properly defined."
992 if ($smtp_encryption eq 'ssl') {
993 $smtp_server_port ||= 465; # ssmtp
994 require Net::SMTP::SSL;
995 $smtp_domain ||= maildomain();
996 $smtp ||= Net::SMTP::SSL->new($smtp_server,
997 Hello => $smtp_domain,
998 Port => $smtp_server_port);
1000 else {
1001 require Net::SMTP;
1002 $smtp_domain ||= maildomain();
1003 $smtp ||= Net::SMTP->new((defined $smtp_server_port)
1004 ? "$smtp_server:$smtp_server_port"
1005 : $smtp_server,
1006 Hello => $smtp_domain,
1007 Debug => $debug_net_smtp);
1008 if ($smtp_encryption eq 'tls' && $smtp) {
1009 require Net::SMTP::SSL;
1010 $smtp->command('STARTTLS');
1011 $smtp->response();
1012 if ($smtp->code == 220) {
1013 $smtp = Net::SMTP::SSL->start_SSL($smtp)
1014 or die "STARTTLS failed! ".$smtp->message;
1015 $smtp_encryption = '';
1016 # Send EHLO again to receive fresh
1017 # supported commands
1018 $smtp->hello();
1019 } else {
1020 die "Server does not support STARTTLS! ".$smtp->message;
1025 if (!$smtp) {
1026 die "Unable to initialize SMTP properly. Check config and use --smtp-debug. ",
1027 "VALUES: server=$smtp_server ",
1028 "encryption=$smtp_encryption ",
1029 "hello=$smtp_domain",
1030 defined $smtp_server_port ? "port=$smtp_server_port" : "";
1033 if (defined $smtp_authuser) {
1035 if (!defined $smtp_authpass) {
1037 system "stty -echo";
1039 do {
1040 print "Password: ";
1041 $_ = <STDIN>;
1042 print "\n";
1043 } while (!defined $_);
1045 chomp($smtp_authpass = $_);
1047 system "stty echo";
1050 $auth ||= $smtp->auth( $smtp_authuser, $smtp_authpass ) or die $smtp->message;
1053 $smtp->mail( $raw_from ) or die $smtp->message;
1054 $smtp->to( @recipients ) or die $smtp->message;
1055 $smtp->data or die $smtp->message;
1056 $smtp->datasend("$header\n$message") or die $smtp->message;
1057 $smtp->dataend() or die $smtp->message;
1058 $smtp->code =~ /250|200/ or die "Failed to send $subject\n".$smtp->message;
1060 if ($quiet) {
1061 printf (($dry_run ? "Dry-" : "")."Sent %s\n", $subject);
1062 } else {
1063 print (($dry_run ? "Dry-" : "")."OK. Log says:\n");
1064 if ($smtp_server !~ m#^/#) {
1065 print "Server: $smtp_server\n";
1066 print "MAIL FROM:<$raw_from>\n";
1067 foreach my $entry (@recipients) {
1068 print "RCPT TO:<$entry>\n";
1070 } else {
1071 print "Sendmail: $smtp_server ".join(' ',@sendmail_parameters)."\n";
1073 print $header, "\n";
1074 if ($smtp) {
1075 print "Result: ", $smtp->code, ' ',
1076 ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
1077 } else {
1078 print "Result: OK\n";
1082 return 1;
1085 $reply_to = $initial_reply_to;
1086 $references = $initial_reply_to || '';
1087 $subject = $initial_subject;
1088 $message_num = 0;
1090 foreach my $t (@files) {
1091 open(F,"<",$t) or die "can't open file $t";
1093 my $author = undef;
1094 my $author_encoding;
1095 my $has_content_type;
1096 my $body_encoding;
1097 @cc = ();
1098 @xh = ();
1099 my $input_format = undef;
1100 my @header = ();
1101 $message = "";
1102 $message_num++;
1103 # First unfold multiline header fields
1104 while(<F>) {
1105 last if /^\s*$/;
1106 if (/^\s+\S/ and @header) {
1107 chomp($header[$#header]);
1108 s/^\s+/ /;
1109 $header[$#header] .= $_;
1110 } else {
1111 push(@header, $_);
1114 # Now parse the header
1115 foreach(@header) {
1116 if (/^From /) {
1117 $input_format = 'mbox';
1118 next;
1120 chomp;
1121 if (!defined $input_format && /^[-A-Za-z]+:\s/) {
1122 $input_format = 'mbox';
1125 if (defined $input_format && $input_format eq 'mbox') {
1126 if (/^Subject:\s+(.*)$/) {
1127 $subject = $1;
1129 elsif (/^From:\s+(.*)$/) {
1130 ($author, $author_encoding) = unquote_rfc2047($1);
1131 next if $suppress_cc{'author'};
1132 next if $suppress_cc{'self'} and $author eq $sender;
1133 printf("(mbox) Adding cc: %s from line '%s'\n",
1134 $1, $_) unless $quiet;
1135 push @cc, $1;
1137 elsif (/^Cc:\s+(.*)$/) {
1138 foreach my $addr (parse_address_line($1)) {
1139 if (unquote_rfc2047($addr) eq $sender) {
1140 next if ($suppress_cc{'self'});
1141 } else {
1142 next if ($suppress_cc{'cc'});
1144 printf("(mbox) Adding cc: %s from line '%s'\n",
1145 $addr, $_) unless $quiet;
1146 push @cc, $addr;
1149 elsif (/^Content-type:/i) {
1150 $has_content_type = 1;
1151 if (/charset="?([^ "]+)/) {
1152 $body_encoding = $1;
1154 push @xh, $_;
1156 elsif (/^Message-Id: (.*)/i) {
1157 $message_id = $1;
1159 elsif (!/^Date:\s/ && /^[-A-Za-z]+:\s+\S/) {
1160 push @xh, $_;
1163 } else {
1164 # In the traditional
1165 # "send lots of email" format,
1166 # line 1 = cc
1167 # line 2 = subject
1168 # So let's support that, too.
1169 $input_format = 'lots';
1170 if (@cc == 0 && !$suppress_cc{'cc'}) {
1171 printf("(non-mbox) Adding cc: %s from line '%s'\n",
1172 $_, $_) unless $quiet;
1173 push @cc, $_;
1174 } elsif (!defined $subject) {
1175 $subject = $_;
1179 # Now parse the message body
1180 while(<F>) {
1181 $message .= $_;
1182 if (/^(Signed-off-by|Cc): (.*)$/i) {
1183 chomp;
1184 my ($what, $c) = ($1, $2);
1185 chomp $c;
1186 if ($c eq $sender) {
1187 next if ($suppress_cc{'self'});
1188 } else {
1189 next if $suppress_cc{'sob'} and $what =~ /Signed-off-by/i;
1190 next if $suppress_cc{'bodycc'} and $what =~ /Cc/i;
1192 push @cc, $c;
1193 printf("(body) Adding cc: %s from line '%s'\n",
1194 $c, $_) unless $quiet;
1197 close F;
1199 if (defined $cc_cmd && !$suppress_cc{'cccmd'}) {
1200 open(F, "$cc_cmd \Q$t\E |")
1201 or die "(cc-cmd) Could not execute '$cc_cmd'";
1202 while(<F>) {
1203 my $c = $_;
1204 $c =~ s/^\s*//g;
1205 $c =~ s/\n$//g;
1206 next if ($c eq $sender and $suppress_from);
1207 push @cc, $c;
1208 printf("(cc-cmd) Adding cc: %s from: '%s'\n",
1209 $c, $cc_cmd) unless $quiet;
1211 close F
1212 or die "(cc-cmd) failed to close pipe to '$cc_cmd'";
1215 if (defined $author and $author ne $sender) {
1216 $message = "From: $author\n\n$message";
1217 if (defined $author_encoding) {
1218 if ($has_content_type) {
1219 if ($body_encoding eq $author_encoding) {
1220 # ok, we already have the right encoding
1222 else {
1223 # uh oh, we should re-encode
1226 else {
1227 push @xh,
1228 'MIME-Version: 1.0',
1229 "Content-Type: text/plain; charset=$author_encoding",
1230 'Content-Transfer-Encoding: 8bit';
1235 $needs_confirm = (
1236 $confirm eq "always" or
1237 ($confirm =~ /^(?:auto|cc)$/ && @cc) or
1238 ($confirm =~ /^(?:auto|compose)$/ && $compose && $message_num == 1));
1239 $needs_confirm = "inform" if ($needs_confirm && $confirm_unconfigured && @cc);
1241 @cc = (@initial_cc, @cc);
1243 my $message_was_sent = send_message();
1245 # set up for the next message
1246 if ($thread && $message_was_sent &&
1247 (chain_reply_to() || !defined $reply_to || length($reply_to) == 0)) {
1248 $reply_to = $message_id;
1249 if (length $references > 0) {
1250 $references .= "\n $message_id";
1251 } else {
1252 $references = "$message_id";
1255 $message_id = undef;
1258 cleanup_compose_files();
1260 sub cleanup_compose_files() {
1261 unlink($compose_filename, $compose_filename . ".final") if $compose;
1264 $smtp->quit if $smtp;
1266 sub unique_email_list(@) {
1267 my %seen;
1268 my @emails;
1270 foreach my $entry (@_) {
1271 if (my $clean = extract_valid_address($entry)) {
1272 $seen{$clean} ||= 0;
1273 next if $seen{$clean}++;
1274 push @emails, $entry;
1275 } else {
1276 print STDERR "W: unable to extract a valid address",
1277 " from: $entry\n";
1280 return @emails;
1283 sub validate_patch {
1284 my $fn = shift;
1285 open(my $fh, '<', $fn)
1286 or die "unable to open $fn: $!\n";
1287 while (my $line = <$fh>) {
1288 if (length($line) > 998) {
1289 return "$.: patch contains a line longer than 998 characters";
1292 return undef;
1295 sub file_has_nonascii {
1296 my $fn = shift;
1297 open(my $fh, '<', $fn)
1298 or die "unable to open $fn: $!\n";
1299 while (my $line = <$fh>) {
1300 return 1 if $line =~ /[^[:ascii:]]/;
1302 return 0;