3 # Copyright 2002,2005 Greg Kroah-Hartman <greg@kroah.com>
4 # Copyright 2005 Ryan Anderson <ryan@michonline.com>
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.
27 use File
::Temp qw
/ tempdir tempfile /;
28 use File
::Spec
::Functions
qw(catfile);
32 Getopt
::Long
::Configure qw
/ pass_through /;
36 my ($class, $reason) = @_;
37 return bless \
$reason, shift;
41 die "Cannot use readline on FakeTerm: $$self";
48 git send-email [options] <file | directory | rev-list options >
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 --[no-]annotate * Review each patch that will be sent in an editor.
58 --compose * Open an editor for introduction.
59 --compose-encoding <str> * Encoding to assume for introduction.
60 --8bit-encoding <str> * Encoding to assume 8bit mails if undeclared
63 --envelope-sender <str> * Email envelope sender.
64 --smtp-server <str:int> * Outgoing SMTP server to use. The port
65 is optional. Default 'localhost'.
66 --smtp-server-option <str> * Outgoing SMTP server option to use.
67 --smtp-server-port <int> * Outgoing SMTP server port.
68 --smtp-user <str> * Username for SMTP-AUTH.
69 --smtp-pass <str> * Password for SMTP-AUTH; not necessary.
70 --smtp-encryption <str> * tls or ssl; anything else disables.
71 --smtp-ssl * Deprecated. Use '--smtp-encryption ssl'.
72 --smtp-ssl-cert-path <str> * Path to ca-certificates (either directory or file).
73 Pass an empty string to disable certificate
75 --smtp-domain <str> * The domain name sent to HELO/EHLO handshake
76 --smtp-debug <0|1> * Disable, enable Net::SMTP debug.
79 --identity <str> * Use the sendemail.<id> options.
80 --to-cmd <str> * Email To: via `<str> \$patch_path`
81 --cc-cmd <str> * Email Cc: via `<str> \$patch_path`
82 --suppress-cc <str> * author, self, sob, cc, cccmd, body, bodycc, all.
83 --[no-]signed-off-by-cc * Send to Signed-off-by: addresses. Default on.
84 --[no-]suppress-from * Send to self. Default off.
85 --[no-]chain-reply-to * Chain In-Reply-To: fields. Default off.
86 --[no-]thread * Use In-Reply-To: field. Default on.
89 --confirm <str> * Confirm recipients before sending;
90 auto, cc, compose, always, or never.
91 --quiet * Output one line of info per email.
92 --dry-run * Don't actually send the emails.
93 --[no-]validate * Perform patch sanity checks. Default on.
94 --[no-]format-patch * understand any non optional arguments as
95 `git format-patch` ones.
96 --force * Send even if safety checks would prevent it.
102 # most mail servers generate the Date: header, but not all...
103 sub format_2822_time
{
105 my @localtm = localtime($time);
106 my @gmttm = gmtime($time);
107 my $localmin = $localtm[1] + $localtm[2] * 60;
108 my $gmtmin = $gmttm[1] + $gmttm[2] * 60;
109 if ($localtm[0] != $gmttm[0]) {
110 die "local zone differs from GMT by a non-minute interval\n";
112 if ((($gmttm[6] + 1) % 7) == $localtm[6]) {
114 } elsif ((($gmttm[6] - 1) % 7) == $localtm[6]) {
116 } elsif ($gmttm[6] != $localtm[6]) {
117 die "local time offset greater than or equal to 24 hours\n";
119 my $offset = $localmin - $gmtmin;
120 my $offhour = $offset / 60;
121 my $offmin = abs($offset % 60);
122 if (abs($offhour) >= 24) {
123 die ("local time offset greater than or equal to 24 hours\n");
126 return sprintf("%s, %2d %s %d %02d:%02d:%02d %s%02d%02d",
127 qw(Sun Mon Tue Wed Thu Fri Sat)[$localtm[6]],
129 qw(Jan Feb Mar Apr May Jun
130 Jul Aug Sep Oct Nov Dec)[$localtm[4]],
135 ($offset >= 0) ?
'+' : '-',
141 my $have_email_valid = eval { require Email
::Valid
; 1 };
142 my $have_mail_address = eval { require Mail
::Address
; 1 };
146 # Variables we fill in automatically, or via prompting:
147 my (@to,$no_to,@initial_to,@cc,$no_cc,@initial_cc,@bcclist,$no_bcc,@xh,
148 $initial_reply_to,$initial_subject,@files,
149 $author,$sender,$smtp_authpass,$annotate,$compose,$time);
154 #$initial_reply_to = ''; #<20050203173208.GA23964@foobar.com>';
156 my $repo = eval { Git
->repository() };
157 my @repo = $repo ?
($repo) : ();
159 $ENV{"GIT_SEND_EMAIL_NOTTY"}
160 ? new Term
::ReadLine
'git-send-email', \
*STDIN
, \
*STDOUT
161 : new Term
::ReadLine
'git-send-email';
164 $term = new FakeTerm
"$@: going non-interactive";
167 # Behavior modification variables
168 my ($quiet, $dry_run) = (0, 0);
170 my $compose_filename;
173 # Handle interactive edition of files.
178 if (!defined($editor)) {
179 $editor = Git
::command_oneline
('var', 'GIT_EDITOR');
181 if (defined($multiedit) && !$multiedit) {
183 system('sh', '-c', $editor.' "$@"', $editor, $_);
184 if (($?
& 127) || ($?
>> 8)) {
185 die("the editor exited uncleanly, aborting everything");
189 system('sh', '-c', $editor.' "$@"', $editor, @_);
190 if (($?
& 127) || ($?
>> 8)) {
191 die("the editor exited uncleanly, aborting everything");
196 # Variables with corresponding config settings
197 my ($thread, $chain_reply_to, $suppress_from, $signed_off_by_cc);
198 my ($to_cmd, $cc_cmd);
199 my ($smtp_server, $smtp_server_port, @smtp_server_options);
200 my ($smtp_authuser, $smtp_encryption, $smtp_ssl_cert_path);
201 my ($identity, $aliasfiletype, @alias_files, $smtp_domain);
202 my ($validate, $confirm);
204 my ($auto_8bit_encoding);
205 my ($compose_encoding);
207 my ($debug_net_smtp) = 0; # Net::SMTP, see send_message()
209 my %config_bool_settings = (
210 "thread" => [\
$thread, 1],
211 "chainreplyto" => [\
$chain_reply_to, 0],
212 "suppressfrom" => [\
$suppress_from, undef],
213 "signedoffbycc" => [\
$signed_off_by_cc, undef],
214 "signedoffcc" => [\
$signed_off_by_cc, undef], # Deprecated
215 "validate" => [\
$validate, 1],
216 "multiedit" => [\
$multiedit, undef],
217 "annotate" => [\
$annotate, undef]
220 my %config_settings = (
221 "smtpserver" => \
$smtp_server,
222 "smtpserverport" => \
$smtp_server_port,
223 "smtpserveroption" => \
@smtp_server_options,
224 "smtpuser" => \
$smtp_authuser,
225 "smtppass" => \
$smtp_authpass,
226 "smtpsslcertpath" => \
$smtp_ssl_cert_path,
227 "smtpdomain" => \
$smtp_domain,
228 "to" => \
@initial_to,
230 "cc" => \
@initial_cc,
232 "aliasfiletype" => \
$aliasfiletype,
234 "suppresscc" => \
@suppress_cc,
235 "envelopesender" => \
$envelope_sender,
236 "confirm" => \
$confirm,
238 "assume8bitencoding" => \
$auto_8bit_encoding,
239 "composeencoding" => \
$compose_encoding,
242 my %config_path_settings = (
243 "aliasesfile" => \
@alias_files,
246 # Handle Uncouth Termination
250 print color
("reset"), "\n";
252 # SMTP password masked
255 # tmp files from --compose
256 if (defined $compose_filename) {
257 if (-e
$compose_filename) {
258 print "'$compose_filename' contains an intermediate version of the email you were composing.\n";
260 if (-e
($compose_filename . ".final")) {
261 print "'$compose_filename.final' contains the composed email.\n"
268 $SIG{TERM
} = \
&signal_handler
;
269 $SIG{INT
} = \
&signal_handler
;
271 # Begin by accumulating all the variables (defined above), that we will end up
272 # needing, first, from the command line:
275 my $rc = GetOptions
("h" => \
$help,
276 "sender|from=s" => \
$sender,
277 "in-reply-to=s" => \
$initial_reply_to,
278 "subject=s" => \
$initial_subject,
279 "to=s" => \
@initial_to,
280 "to-cmd=s" => \
$to_cmd,
282 "cc=s" => \
@initial_cc,
284 "bcc=s" => \
@bcclist,
285 "no-bcc" => \
$no_bcc,
286 "chain-reply-to!" => \
$chain_reply_to,
287 "smtp-server=s" => \
$smtp_server,
288 "smtp-server-option=s" => \
@smtp_server_options,
289 "smtp-server-port=s" => \
$smtp_server_port,
290 "smtp-user=s" => \
$smtp_authuser,
291 "smtp-pass:s" => \
$smtp_authpass,
292 "smtp-ssl" => sub { $smtp_encryption = 'ssl' },
293 "smtp-encryption=s" => \
$smtp_encryption,
294 "smtp-ssl-cert-path=s" => \
$smtp_ssl_cert_path,
295 "smtp-debug:i" => \
$debug_net_smtp,
296 "smtp-domain:s" => \
$smtp_domain,
297 "identity=s" => \
$identity,
298 "annotate!" => \
$annotate,
299 "compose" => \
$compose,
301 "cc-cmd=s" => \
$cc_cmd,
302 "suppress-from!" => \
$suppress_from,
303 "suppress-cc=s" => \
@suppress_cc,
304 "signed-off-cc|signed-off-by-cc!" => \
$signed_off_by_cc,
305 "confirm=s" => \
$confirm,
306 "dry-run" => \
$dry_run,
307 "envelope-sender=s" => \
$envelope_sender,
308 "thread!" => \
$thread,
309 "validate!" => \
$validate,
310 "format-patch!" => \
$format_patch,
311 "8bit-encoding=s" => \
$auto_8bit_encoding,
312 "compose-encoding=s" => \
$compose_encoding,
321 die "Cannot run git format-patch from outside a repository\n"
322 if $format_patch and not $repo;
324 # Now, let's fill any that aren't set in with defaults:
329 foreach my $setting (keys %config_bool_settings) {
330 my $target = $config_bool_settings{$setting}->[0];
331 $$target = Git
::config_bool
(@repo, "$prefix.$setting") unless (defined $$target);
334 foreach my $setting (keys %config_path_settings) {
335 my $target = $config_path_settings{$setting};
336 if (ref($target) eq "ARRAY") {
338 my @values = Git
::config_path
(@repo, "$prefix.$setting");
339 @
$target = @values if (@values && defined $values[0]);
343 $$target = Git
::config_path
(@repo, "$prefix.$setting") unless (defined $$target);
347 foreach my $setting (keys %config_settings) {
348 my $target = $config_settings{$setting};
349 next if $setting eq "to" and defined $no_to;
350 next if $setting eq "cc" and defined $no_cc;
351 next if $setting eq "bcc" and defined $no_bcc;
352 if (ref($target) eq "ARRAY") {
354 my @values = Git
::config
(@repo, "$prefix.$setting");
355 @
$target = @values if (@values && defined $values[0]);
359 $$target = Git
::config
(@repo, "$prefix.$setting") unless (defined $$target);
363 if (!defined $smtp_encryption) {
364 my $enc = Git
::config
(@repo, "$prefix.smtpencryption");
366 $smtp_encryption = $enc;
367 } elsif (Git
::config_bool
(@repo, "$prefix.smtpssl")) {
368 $smtp_encryption = 'ssl';
373 # read configuration from [sendemail "$identity"], fall back on [sendemail]
374 $identity = Git
::config
(@repo, "sendemail.identity") unless (defined $identity);
375 read_config
("sendemail.$identity") if (defined $identity);
376 read_config
("sendemail");
378 # fall back on builtin bool defaults
379 foreach my $setting (values %config_bool_settings) {
380 ${$setting->[0]} = $setting->[1] unless (defined (${$setting->[0]}));
383 # 'default' encryption is none -- this only prevents a warning
384 $smtp_encryption = '' unless (defined $smtp_encryption);
386 # Set CC suppressions
389 foreach my $entry (@suppress_cc) {
390 die "Unknown --suppress-cc field: '$entry'\n"
391 unless $entry =~ /^(?:all|cccmd|cc|author|self|sob|body|bodycc)$/;
392 $suppress_cc{$entry} = 1;
396 if ($suppress_cc{'all'}) {
397 foreach my $entry (qw
(cccmd cc author self sob body bodycc
)) {
398 $suppress_cc{$entry} = 1;
400 delete $suppress_cc{'all'};
403 # If explicit old-style ones are specified, they trump --suppress-cc.
404 $suppress_cc{'self'} = $suppress_from if defined $suppress_from;
405 $suppress_cc{'sob'} = !$signed_off_by_cc if defined $signed_off_by_cc;
407 if ($suppress_cc{'body'}) {
408 foreach my $entry (qw
(sob bodycc
)) {
409 $suppress_cc{$entry} = 1;
411 delete $suppress_cc{'body'};
414 # Set confirm's default value
415 my $confirm_unconfigured = !defined $confirm;
416 if ($confirm_unconfigured) {
417 $confirm = scalar %suppress_cc ?
'compose' : 'auto';
419 die "Unknown --confirm setting: '$confirm'\n"
420 unless $confirm =~ /^(?:auto|cc|compose|always|never)/;
422 # Debugging, print out the suppressions.
424 print "suppressions:\n";
425 foreach my $entry (keys %suppress_cc) {
426 printf " %-5s -> $suppress_cc{$entry}\n", $entry;
430 my ($repoauthor, $repocommitter);
431 ($repoauthor) = Git
::ident_person
(@repo, 'author');
432 ($repocommitter) = Git
::ident_person
(@repo, 'committer');
434 # Verify the user input
436 foreach my $entry (@initial_to) {
437 die "Comma in --to entry: $entry'\n" unless $entry !~ m/,/;
440 foreach my $entry (@initial_cc) {
441 die "Comma in --cc entry: $entry'\n" unless $entry !~ m/,/;
444 foreach my $entry (@bcclist) {
445 die "Comma in --bcclist entry: $entry'\n" unless $entry !~ m/,/;
448 sub parse_address_line
{
449 if ($have_mail_address) {
450 return map { $_->format } Mail
::Address
->parse($_[0]);
452 return split_addrs
($_[0]);
457 return quotewords
('\s*,\s*', 1, @_);
462 # multiline formats can be supported in the future
463 mutt
=> sub { my $fh = shift; while (<$fh>) {
464 if (/^\s*alias\s+(?:-group\s+\S+\s+)*(\S+)\s+(.*)$/) {
465 my ($alias, $addr) = ($1, $2);
466 $addr =~ s/#.*$//; # mutt allows # comments
467 # commas delimit multiple addresses
468 $aliases{$alias} = [ split_addrs
($addr) ];
470 mailrc
=> sub { my $fh = shift; while (<$fh>) {
471 if (/^alias\s+(\S+)\s+(.*)$/) {
472 # spaces delimit multiple addresses
473 $aliases{$1} = [ quotewords
('\s+', 0, $2) ];
475 pine
=> sub { my $fh = shift; my $f='\t[^\t]*';
476 for (my $x = ''; defined($x); $x = $_) {
478 $x .= $1 while(defined($_ = <$fh>) && /^ +(.*)$/);
479 $x =~ /^(\S+)$f\t\(?([^\t]+?)\)?(:?$f){0,2}$/ or next;
480 $aliases{$1} = [ split_addrs
($2) ];
482 elm
=> sub { my $fh = shift;
484 if (/^(\S+)\s+=\s+[^=]+=\s(\S+)/) {
485 my ($alias, $addr) = ($1, $2);
486 $aliases{$alias} = [ split_addrs
($addr) ];
490 gnus
=> sub { my $fh = shift; while (<$fh>) {
491 if (/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) {
492 $aliases{$1} = [ $2 ];
496 if (@alias_files and $aliasfiletype and defined $parse_alias{$aliasfiletype}) {
497 foreach my $file (@alias_files) {
498 open my $fh, '<', $file or die "opening $file: $!\n";
499 $parse_alias{$aliasfiletype}->($fh);
504 ($sender) = expand_aliases
($sender) if defined $sender;
506 # is_format_patch_arg($f) returns 0 if $f names a patch, or 1 if
507 # $f is a revision list specification to be passed to format-patch.
508 sub is_format_patch_arg
{
512 $repo->command('rev-parse', '--verify', '--quiet', $f);
513 if (defined($format_patch)) {
514 return $format_patch;
517 File '$f' exists but it could also be the range of commits
518 to produce patches for. Please disambiguate by...
520 * Saying "./$f" if you mean a file; or
521 * Giving --format-patch option if you mean a range.
523 } catch Git
::Error
::Command with
{
524 # Not a valid revision. Treat it as a filename.
529 # Now that all the defaults are set, process the rest of the command line
530 # arguments and collect up the files that need to be processed.
532 while (defined(my $f = shift @ARGV)) {
534 push @rev_list_opts, "--", @ARGV;
536 } elsif (-d
$f and !is_format_patch_arg
($f)) {
538 or die "Failed to opendir $f: $!";
540 push @files, grep { -f
$_ } map { catfile
($f, $_) }
543 } elsif ((-f
$f or -p
$f) and !is_format_patch_arg
($f)) {
546 push @rev_list_opts, $f;
550 if (@rev_list_opts) {
551 die "Cannot run git format-patch from outside a repository\n"
553 push @files, $repo->command('format-patch', '-o', tempdir
(CLEANUP
=> 1), @rev_list_opts);
557 foreach my $f (@files) {
559 my $error = validate_patch
($f);
560 $error and die "fatal: $f: $error\nwarning: no patches were sent\n";
567 print $_,"\n" for (@files);
570 print STDERR
"\nNo patch files specified!\n\n";
574 sub get_patch_subject
{
576 open (my $fh, '<', $fn);
577 while (my $line = <$fh>) {
578 next unless ($line =~ /^Subject: (.*)$/);
583 die "No subject line in $fn ?";
587 # Note that this does not need to be secure, but we will make a small
588 # effort to have it be unique
589 $compose_filename = ($repo ?
590 tempfile
(".gitsendemail.msg.XXXXXX", DIR
=> $repo->repo_path()) :
591 tempfile
(".gitsendemail.msg.XXXXXX", DIR
=> "."))[1];
592 open my $c, ">", $compose_filename
593 or die "Failed to open for writing $compose_filename: $!";
596 my $tpl_sender = $sender || $repoauthor || $repocommitter || '';
597 my $tpl_subject = $initial_subject || '';
598 my $tpl_reply_to = $initial_reply_to || '';
601 From $tpl_sender # This line is ignored.
602 GIT: Lines beginning in "GIT:" will be removed.
603 GIT: Consider including an overall diffstat or table of contents
604 GIT: for the patch you are writing.
606 GIT: Clear the body content if you don't wish to send a summary.
608 Subject: $tpl_subject
609 In-Reply-To: $tpl_reply_to
613 print $c get_patch_subject
($f);
618 do_edit
($compose_filename, @files);
620 do_edit
($compose_filename);
623 open my $c2, ">", $compose_filename . ".final"
624 or die "Failed to open $compose_filename.final : " . $!;
626 open $c, "<", $compose_filename
627 or die "Failed to open $compose_filename : " . $!;
629 my $need_8bit_cte = file_has_nonascii
($compose_filename);
631 my $summary_empty = 1;
632 if (!defined $compose_encoding) {
633 $compose_encoding = "UTF-8";
638 $summary_empty = 0 unless (/^\n$/);
641 if ($need_8bit_cte) {
642 print $c2 "MIME-Version: 1.0\n",
643 "Content-Type: text/plain; ",
644 "charset=$compose_encoding\n",
645 "Content-Transfer-Encoding: 8bit\n";
647 } elsif (/^MIME-Version:/i) {
649 } elsif (/^Subject:\s*(.+)\s*$/i) {
650 $initial_subject = $1;
651 my $subject = $initial_subject;
653 quote_subject
($subject, $compose_encoding) .
655 } elsif (/^In-Reply-To:\s*(.+)\s*$/i) {
656 $initial_reply_to = $1;
658 } elsif (/^From:\s*(.+)\s*$/i) {
661 } elsif (/^(?:To|Cc|Bcc):/i) {
662 print "To/Cc/Bcc fields are not interpreted yet, they have been ignored\n";
670 if ($summary_empty) {
671 print "Summary email is empty, skipping it\n";
674 } elsif ($annotate) {
679 my ($prompt, %arg) = @_;
680 my $valid_re = $arg{valid_re
};
681 my $default = $arg{default};
682 my $confirm_only = $arg{confirm_only
};
685 return defined $default ?
$default : undef
686 unless defined $term->IN and defined fileno($term->IN) and
687 defined $term->OUT and defined fileno($term->OUT);
689 $resp = $term->readline($prompt);
690 if (!defined $resp) { # EOF
692 return defined $default ?
$default : undef;
694 if ($resp eq '' and defined $default) {
697 if (!defined $valid_re or $resp =~ /$valid_re/) {
701 my $yesno = $term->readline("Are you sure you want to use <$resp> [y/N]? ");
702 if (defined $yesno && $yesno =~ /y/i) {
712 sub file_declares_8bit_cte
{
714 open (my $fh, '<', $fn);
715 while (my $line = <$fh>) {
716 last if ($line =~ /^$/);
717 return 1 if ($line =~ /^Content-Transfer-Encoding: .*8bit.*$/);
723 foreach my $f (@files) {
724 next unless (body_or_subject_has_nonascii
($f)
725 && !file_declares_8bit_cte
($f));
726 $broken_encoding{$f} = 1;
729 if (!defined $auto_8bit_encoding && scalar %broken_encoding) {
730 print "The following files are 8bit, but do not declare " .
731 "a Content-Transfer-Encoding.\n";
732 foreach my $f (sort keys %broken_encoding) {
735 $auto_8bit_encoding = ask
("Which 8bit encoding should I declare [UTF-8]? ",
741 if (get_patch_subject
($f) =~ /\Q*** SUBJECT HERE ***\E/) {
742 die "Refusing to send because the patch\n\t$f\n"
743 . "has the template subject '*** SUBJECT HERE ***'. "
744 . "Pass --force if you really want to send.\n";
749 if (!defined $sender) {
750 $sender = $repoauthor || $repocommitter || '';
753 # $sender could be an already sanitized address
754 # (e.g. sendemail.from could be manually sanitized by user).
755 # But it's a no-op to run sanitize_address on an already sanitized address.
756 $sender = sanitize_address
($sender);
759 if (!@initial_to && !defined $to_cmd) {
760 my $to = ask
("Who should the emails be sent to (if any)? ",
762 valid_re
=> qr/\@.*\./, confirm_only
=> 1);
763 push @initial_to, parse_address_line
($to) if defined $to; # sanitized/validated later
768 return map { expand_one_alias
($_) } @_;
771 my %EXPANDED_ALIASES;
772 sub expand_one_alias
{
774 if ($EXPANDED_ALIASES{$alias}) {
775 die "fatal: alias '$alias' expands to itself\n";
777 local $EXPANDED_ALIASES{$alias} = 1;
778 return $aliases{$alias} ? expand_aliases
(@
{$aliases{$alias}}) : $alias;
781 @initial_to = expand_aliases
(@initial_to);
782 @initial_to = validate_address_list
(sanitize_address_list
(@initial_to));
783 @initial_cc = expand_aliases
(@initial_cc);
784 @initial_cc = validate_address_list
(sanitize_address_list
(@initial_cc));
785 @bcclist = expand_aliases
(@bcclist);
786 @bcclist = validate_address_list
(sanitize_address_list
(@bcclist));
788 if ($thread && !defined $initial_reply_to && $prompting) {
789 $initial_reply_to = ask
(
790 "Message-ID to be used as In-Reply-To for the first email (if any)? ",
792 valid_re
=> qr/\@.*\./, confirm_only
=> 1);
794 if (defined $initial_reply_to) {
795 $initial_reply_to =~ s/^\s*<?//;
796 $initial_reply_to =~ s/>?\s*$//;
797 $initial_reply_to = "<$initial_reply_to>" if $initial_reply_to ne '';
800 if (!defined $smtp_server) {
801 foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
807 $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
810 if ($compose && $compose > 0) {
811 @files = ($compose_filename . ".final", @files);
814 # Variables we set as part of the loop over files
815 our ($message_id, %mail, $subject, $reply_to, $references, $message,
816 $needs_confirm, $message_num, $ask_default);
818 sub extract_valid_address
{
820 my $local_part_regexp = qr/[^<>"\s@]+/;
821 my $domain_regexp = qr/[^.<>"\s@]+(?:\.[^.<>"\s@]+)+/;
823 # check for a local address:
824 return $address if ($address =~ /^($local_part_regexp)$/);
826 $address =~ s/^\s*<(.*)>\s*$/$1/;
827 if ($have_email_valid) {
828 return scalar Email
::Valid
->address($address);
831 # less robust/correct than the monster regexp in Email::Valid,
832 # but still does a 99% job, and one less dependency
833 return $1 if $address =~ /($local_part_regexp\@$domain_regexp)/;
837 sub extract_valid_address_or_die
{
839 $address = extract_valid_address
($address);
840 die "error: unable to extract a valid address from: $address\n"
845 sub validate_address
{
847 while (!extract_valid_address
($address)) {
848 print STDERR
"error: unable to extract a valid address from: $address\n";
849 $_ = ask
("What to do with this address? ([q]uit|[d]rop|[e]dit): ",
850 valid_re
=> qr/^(?:quit|q|drop|d|edit|e)/i,
855 cleanup_compose_files
();
858 $address = ask
("Who should the email be sent to (if any)? ",
860 valid_re
=> qr/\@.*\./, confirm_only
=> 1);
865 sub validate_address_list
{
866 return (grep { defined $_ }
867 map { validate_address
($_) } @_);
870 # Usually don't need to change anything below here.
872 # we make a "fake" message id by taking the current number
873 # of seconds since the beginning of Unix time and tacking on
874 # a random number to the end, in case we are called quicker than
875 # 1 second since the last time we were called.
877 # We'll setup a template for the message id, using the "from" address:
879 my ($message_id_stamp, $message_id_serial);
880 sub make_message_id
{
882 if (!defined $message_id_stamp) {
883 $message_id_stamp = sprintf("%s-%s", time, $$);
884 $message_id_serial = 0;
886 $message_id_serial++;
887 $uniq = "$message_id_stamp-$message_id_serial";
890 for ($sender, $repocommitter, $repoauthor) {
891 $du_part = extract_valid_address
(sanitize_address
($_));
892 last if (defined $du_part and $du_part ne '');
894 if (not defined $du_part or $du_part eq '') {
895 require Sys
::Hostname
;
896 $du_part = 'user@' . Sys
::Hostname
::hostname
();
898 my $message_id_template = "<%s-git-send-email-%s>";
899 $message_id = sprintf($message_id_template, $uniq, $du_part);
900 #print "new message id = $message_id\n"; # Was useful for debugging
905 $time = time - scalar $#files;
907 sub unquote_rfc2047
{
910 s
{=\?([^?
]+)\?q
\?(.*?
)\?=}{
914 $e =~ s/=([0-9A-F]{2})/chr(hex($1))/eg;
917 return wantarray ?
($_, $encoding) : $_;
922 my $encoding = shift || 'UTF-8';
923 s/([^-a-zA-Z0-9!*+\/])/sprintf
("=%02X", ord($1))/eg
;
924 s/(.*)/=\?$encoding\?q\?$1\?=/;
928 sub is_rfc2047_quoted
{
930 my $token = qr/[^][()<>@,;:"\/?
.= \000-\037\177-\377]+/;
931 my $encoded_text = qr/[!->@-~]+/;
933 $s =~ m/^(?:"[[:ascii:]]*"|=\?$token\?$token\?$encoded_text\?=)$/o;
936 sub subject_needs_rfc2047_quoting
{
939 return ($s =~ /[^[:ascii:]]/) || ($s =~ /=\?/);
943 local $subject = shift;
944 my $encoding = shift || 'UTF-8';
946 if (subject_needs_rfc2047_quoting
($subject)) {
947 return quote_rfc2047
($subject, $encoding);
952 # use the simplest quoting being able to handle the recipient
953 sub sanitize_address
{
954 my ($recipient) = @_;
956 # remove garbage after email address
957 $recipient =~ s/(.*>).*$/$1/;
959 my ($recipient_name, $recipient_addr) = ($recipient =~ /^(.*?)\s*(<.*)/);
961 if (not $recipient_name) {
965 # if recipient_name is already quoted, do nothing
966 if (is_rfc2047_quoted
($recipient_name)) {
970 # rfc2047 is needed if a non-ascii char is included
971 if ($recipient_name =~ /[^[:ascii:]]/) {
972 $recipient_name =~ s/^"(.*)"$/$1/;
973 $recipient_name = quote_rfc2047
($recipient_name);
976 # double quotes are needed if specials or CTLs are included
977 elsif ($recipient_name =~ /[][()<>@,;:\\".\000-\037\177]/) {
978 $recipient_name =~ s/(["\\\r])/\\$1/g;
979 $recipient_name = qq["$recipient_name"];
982 return "$recipient_name $recipient_addr";
986 sub sanitize_address_list
{
987 return (map { sanitize_address
($_) } @_);
990 # Returns the local Fully Qualified Domain Name (FQDN) if available.
992 # Tightly configured MTAa require that a caller sends a real DNS
993 # domain name that corresponds the IP address in the HELO/EHLO
994 # handshake. This is used to verify the connection and prevent
995 # spammers from trying to hide their identity. If the DNS and IP don't
996 # match, the receiveing MTA may deny the connection.
998 # Here is a deny example of Net::SMTP with the default "localhost.localdomain"
1000 # Net::SMTP=GLOB(0x267ec28)>>> EHLO localhost.localdomain
1001 # Net::SMTP=GLOB(0x267ec28)<<< 550 EHLO argument does not match calling host
1003 # This maildomain*() code is based on ideas in Perl library Test::Reporter
1004 # /usr/share/perl5/Test/Reporter/Mail/Util.pm ==> sub _maildomain ()
1008 return defined $domain && !($^O
eq 'darwin' && $domain =~ /\.local$/) && $domain =~ /\./;
1011 sub maildomain_net
{
1014 if (eval { require Net
::Domain
; 1 }) {
1015 my $domain = Net
::Domain
::domainname
();
1016 $maildomain = $domain if valid_fqdn
($domain);
1022 sub maildomain_mta
{
1025 if (eval { require Net
::SMTP
; 1 }) {
1026 for my $host (qw(mailhost localhost)) {
1027 my $smtp = Net
::SMTP
->new($host);
1028 if (defined $smtp) {
1029 my $domain = $smtp->domain;
1032 $maildomain = $domain if valid_fqdn
($domain);
1034 last if $maildomain;
1043 return maildomain_net
() || maildomain_mta
() || 'localhost.localdomain';
1046 sub smtp_host_string
{
1047 if (defined $smtp_server_port) {
1048 return "$smtp_server:$smtp_server_port";
1050 return $smtp_server;
1054 # Returns 1 if authentication succeeded or was not necessary
1055 # (smtp_user was not specified), and 0 otherwise.
1057 sub smtp_auth_maybe
{
1058 if (!defined $smtp_authuser || $auth) {
1062 # Workaround AUTH PLAIN/LOGIN interaction defect
1063 # with Authen::SASL::Cyrus
1065 require Authen
::SASL
;
1066 Authen
::SASL
->import(qw(Perl));
1069 # TODO: Authentication may fail not because credentials were
1070 # invalid but due to other reasons, in which we should not
1071 # reject credentials.
1072 $auth = Git
::credential
({
1073 'protocol' => 'smtp',
1074 'host' => smtp_host_string
(),
1075 'username' => $smtp_authuser,
1076 # if there's no password, "git credential fill" will
1077 # give us one, otherwise it'll just pass this one.
1078 'password' => $smtp_authpass
1081 return !!$smtp->auth($cred->{'username'}, $cred->{'password'});
1087 sub ssl_verify_params
{
1089 require IO
::Socket
::SSL
;
1090 IO
::Socket
::SSL
->import(qw
/SSL_VERIFY_PEER SSL_VERIFY_NONE/);
1093 print STDERR
"Not using SSL_VERIFY_PEER due to out-of-date IO::Socket::SSL.\n";
1097 if (!defined $smtp_ssl_cert_path) {
1098 $smtp_ssl_cert_path = "/etc/ssl/certs";
1101 if ($smtp_ssl_cert_path eq "") {
1102 return (SSL_verify_mode
=> SSL_VERIFY_NONE
());
1103 } elsif (-d
$smtp_ssl_cert_path) {
1104 return (SSL_verify_mode
=> SSL_VERIFY_PEER
(),
1105 SSL_ca_path
=> $smtp_ssl_cert_path);
1106 } elsif (-f
$smtp_ssl_cert_path) {
1107 return (SSL_verify_mode
=> SSL_VERIFY_PEER
(),
1108 SSL_ca_file
=> $smtp_ssl_cert_path);
1110 print STDERR
"Not using SSL_VERIFY_PEER because the CA path does not exist.\n";
1111 return (SSL_verify_mode
=> SSL_VERIFY_NONE
());
1115 # Returns 1 if the message was sent, and 0 otherwise.
1116 # In actuality, the whole program dies when there
1117 # is an error sending a message.
1120 my @recipients = unique_email_list
(@to);
1121 @cc = (grep { my $cc = extract_valid_address_or_die
($_);
1122 not grep { $cc eq $_ || $_ =~ /<\Q${cc}\E>$/ } @recipients
1125 my $to = join (",\n\t", @recipients);
1126 @recipients = unique_email_list
(@recipients,@cc,@bcclist);
1127 @recipients = (map { extract_valid_address_or_die
($_) } @recipients);
1128 my $date = format_2822_time
($time++);
1129 my $gitversion = '@@GIT_VERSION@@';
1130 if ($gitversion =~ m/..GIT_VERSION../) {
1131 $gitversion = Git
::version
();
1134 my $cc = join(",\n\t", unique_email_list
(@cc));
1137 $ccline = "\nCc: $cc";
1139 make_message_id
() unless defined($message_id);
1141 my $header = "From: $sender
1145 Message-Id: $message_id
1146 X-Mailer: git-send-email $gitversion
1150 $header .= "In-Reply-To: $reply_to\n";
1151 $header .= "References: $references\n";
1154 $header .= join("\n", @xh) . "\n";
1157 my @sendmail_parameters = ('-i', @recipients);
1158 my $raw_from = $sender;
1159 if (defined $envelope_sender && $envelope_sender ne "auto") {
1160 $raw_from = $envelope_sender;
1162 $raw_from = extract_valid_address
($raw_from);
1163 unshift (@sendmail_parameters,
1164 '-f', $raw_from) if(defined $envelope_sender);
1166 if ($needs_confirm && !$dry_run) {
1167 print "\n$header\n";
1168 if ($needs_confirm eq "inform") {
1169 $confirm_unconfigured = 0; # squelch this message for the rest of this run
1170 $ask_default = "y"; # assume yes on EOF since user hasn't explicitly asked for confirmation
1171 print " The Cc list above has been expanded by additional\n";
1172 print " addresses found in the patch commit message. By default\n";
1173 print " send-email prompts before sending whenever this occurs.\n";
1174 print " This behavior is controlled by the sendemail.confirm\n";
1175 print " configuration setting.\n";
1177 print " For additional information, run 'git send-email --help'.\n";
1178 print " To retain the current behavior, but squelch this message,\n";
1179 print " run 'git config --global sendemail.confirm auto'.\n\n";
1181 $_ = ask
("Send this email? ([y]es|[n]o|[q]uit|[a]ll): ",
1182 valid_re
=> qr/^(?:yes|y|no|n|quit|q|all|a)/i,
1183 default => $ask_default);
1184 die "Send this email reply required" unless defined $_;
1188 cleanup_compose_files
();
1195 unshift (@sendmail_parameters, @smtp_server_options);
1198 # We don't want to send the email.
1199 } elsif ($smtp_server =~ m
#^/#) {
1200 my $pid = open my $sm, '|-';
1201 defined $pid or die $!;
1203 exec($smtp_server, @sendmail_parameters) or die $!;
1205 print $sm "$header\n$message";
1206 close $sm or die $!;
1209 if (!defined $smtp_server) {
1210 die "The required SMTP server is not properly defined."
1213 if ($smtp_encryption eq 'ssl') {
1214 $smtp_server_port ||= 465; # ssmtp
1215 require Net
::SMTP
::SSL
;
1216 $smtp_domain ||= maildomain
();
1217 require IO
::Socket
::SSL
;
1218 # Net::SMTP::SSL->new() does not forward any SSL options
1219 IO
::Socket
::SSL
::set_client_defaults
(
1220 ssl_verify_params
());
1221 $smtp ||= Net
::SMTP
::SSL
->new($smtp_server,
1222 Hello
=> $smtp_domain,
1223 Port
=> $smtp_server_port,
1224 Debug
=> $debug_net_smtp);
1228 $smtp_domain ||= maildomain
();
1229 $smtp_server_port ||= 25;
1230 $smtp ||= Net
::SMTP
->new($smtp_server,
1231 Hello
=> $smtp_domain,
1232 Debug
=> $debug_net_smtp,
1233 Port
=> $smtp_server_port);
1234 if ($smtp_encryption eq 'tls' && $smtp) {
1235 require Net
::SMTP
::SSL
;
1236 $smtp->command('STARTTLS');
1238 if ($smtp->code == 220) {
1239 $smtp = Net
::SMTP
::SSL
->start_SSL($smtp,
1240 ssl_verify_params
())
1241 or die "STARTTLS failed! ".IO
::Socket
::SSL
::errstr
();
1242 $smtp_encryption = '';
1243 # Send EHLO again to receive fresh
1244 # supported commands
1245 $smtp->hello($smtp_domain);
1247 die "Server does not support STARTTLS! ".$smtp->message;
1253 die "Unable to initialize SMTP properly. Check config and use --smtp-debug. ",
1254 "VALUES: server=$smtp_server ",
1255 "encryption=$smtp_encryption ",
1256 "hello=$smtp_domain",
1257 defined $smtp_server_port ?
" port=$smtp_server_port" : "";
1260 smtp_auth_maybe
or die $smtp->message;
1262 $smtp->mail( $raw_from ) or die $smtp->message;
1263 $smtp->to( @recipients ) or die $smtp->message;
1264 $smtp->data or die $smtp->message;
1265 $smtp->datasend("$header\n$message") or die $smtp->message;
1266 $smtp->dataend() or die $smtp->message;
1267 $smtp->code =~ /250|200/ or die "Failed to send $subject\n".$smtp->message;
1270 printf (($dry_run ?
"Dry-" : "")."Sent %s\n", $subject);
1272 print (($dry_run ?
"Dry-" : "")."OK. Log says:\n");
1273 if ($smtp_server !~ m
#^/#) {
1274 print "Server: $smtp_server\n";
1275 print "MAIL FROM:<$raw_from>\n";
1276 foreach my $entry (@recipients) {
1277 print "RCPT TO:<$entry>\n";
1280 print "Sendmail: $smtp_server ".join(' ',@sendmail_parameters)."\n";
1282 print $header, "\n";
1284 print "Result: ", $smtp->code, ' ',
1285 ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
1287 print "Result: OK\n";
1294 $reply_to = $initial_reply_to;
1295 $references = $initial_reply_to || '';
1296 $subject = $initial_subject;
1299 foreach my $t (@files) {
1300 open my $fh, "<", $t or die "can't open file $t";
1303 my $sauthor = undef;
1304 my $author_encoding;
1305 my $has_content_type;
1310 my $input_format = undef;
1314 # First unfold multiline header fields
1317 if (/^\s+\S/ and @header) {
1318 chomp($header[$#header]);
1320 $header[$#header] .= $_;
1325 # Now parse the header
1328 $input_format = 'mbox';
1332 if (!defined $input_format && /^[-A-Za-z]+:\s/) {
1333 $input_format = 'mbox';
1336 if (defined $input_format && $input_format eq 'mbox') {
1337 if (/^Subject:\s+(.*)$/i) {
1340 elsif (/^From:\s+(.*)$/i) {
1341 ($author, $author_encoding) = unquote_rfc2047
($1);
1342 $sauthor = sanitize_address
($author);
1343 next if $suppress_cc{'author'};
1344 next if $suppress_cc{'self'} and $sauthor eq $sender;
1345 printf("(mbox) Adding cc: %s from line '%s'\n",
1346 $1, $_) unless $quiet;
1349 elsif (/^To:\s+(.*)$/i) {
1350 foreach my $addr (parse_address_line
($1)) {
1351 printf("(mbox) Adding to: %s from line '%s'\n",
1352 $addr, $_) unless $quiet;
1356 elsif (/^Cc:\s+(.*)$/i) {
1357 foreach my $addr (parse_address_line
($1)) {
1358 my $qaddr = unquote_rfc2047
($addr);
1359 my $saddr = sanitize_address
($qaddr);
1360 if ($saddr eq $sender) {
1361 next if ($suppress_cc{'self'});
1363 next if ($suppress_cc{'cc'});
1365 printf("(mbox) Adding cc: %s from line '%s'\n",
1366 $addr, $_) unless $quiet;
1370 elsif (/^Content-type:/i) {
1371 $has_content_type = 1;
1372 if (/charset="?([^ "]+)/) {
1373 $body_encoding = $1;
1377 elsif (/^Message-Id: (.*)/i) {
1380 elsif (!/^Date:\s/i && /^[-A-Za-z]+:\s+\S/) {
1385 # In the traditional
1386 # "send lots of email" format,
1389 # So let's support that, too.
1390 $input_format = 'lots';
1391 if (@cc == 0 && !$suppress_cc{'cc'}) {
1392 printf("(non-mbox) Adding cc: %s from line '%s'\n",
1393 $_, $_) unless $quiet;
1395 } elsif (!defined $subject) {
1400 # Now parse the message body
1403 if (/^(Signed-off-by|Cc): (.*)$/i) {
1405 my ($what, $c) = ($1, $2);
1407 my $sc = sanitize_address
($c);
1408 if ($sc eq $sender) {
1409 next if ($suppress_cc{'self'});
1411 next if $suppress_cc{'sob'} and $what =~ /Signed-off-by/i;
1412 next if $suppress_cc{'bodycc'} and $what =~ /Cc/i;
1415 printf("(body) Adding cc: %s from line '%s'\n",
1416 $c, $_) unless $quiet;
1421 push @to, recipients_cmd
("to-cmd", "to", $to_cmd, $t)
1423 push @cc, recipients_cmd
("cc-cmd", "cc", $cc_cmd, $t)
1424 if defined $cc_cmd && !$suppress_cc{'cccmd'};
1426 if ($broken_encoding{$t} && !$has_content_type) {
1427 $has_content_type = 1;
1428 push @xh, "MIME-Version: 1.0",
1429 "Content-Type: text/plain; charset=$auto_8bit_encoding",
1430 "Content-Transfer-Encoding: 8bit";
1431 $body_encoding = $auto_8bit_encoding;
1434 if ($broken_encoding{$t} && !is_rfc2047_quoted
($subject)) {
1435 $subject = quote_subject
($subject, $auto_8bit_encoding);
1438 if (defined $sauthor and $sauthor ne $sender) {
1439 $message = "From: $author\n\n$message";
1440 if (defined $author_encoding) {
1441 if ($has_content_type) {
1442 if ($body_encoding eq $author_encoding) {
1443 # ok, we already have the right encoding
1446 # uh oh, we should re-encode
1450 $has_content_type = 1;
1452 'MIME-Version: 1.0',
1453 "Content-Type: text/plain; charset=$author_encoding",
1454 'Content-Transfer-Encoding: 8bit';
1460 $confirm eq "always" or
1461 ($confirm =~ /^(?:auto|cc)$/ && @cc) or
1462 ($confirm =~ /^(?:auto|compose)$/ && $compose && $message_num == 1));
1463 $needs_confirm = "inform" if ($needs_confirm && $confirm_unconfigured && @cc);
1465 @to = validate_address_list
(sanitize_address_list
(@to));
1466 @cc = validate_address_list
(sanitize_address_list
(@cc));
1468 @to = (@initial_to, @to);
1469 @cc = (@initial_cc, @cc);
1471 my $message_was_sent = send_message
();
1473 # set up for the next message
1474 if ($thread && $message_was_sent &&
1475 ($chain_reply_to || !defined $reply_to || length($reply_to) == 0 ||
1476 $message_num == 1)) {
1477 $reply_to = $message_id;
1478 if (length $references > 0) {
1479 $references .= "\n $message_id";
1481 $references = "$message_id";
1484 $message_id = undef;
1487 # Execute a command (e.g. $to_cmd) to get a list of email addresses
1488 # and return a results array
1489 sub recipients_cmd
{
1490 my ($prefix, $what, $cmd, $file) = @_;
1493 open my $fh, "-|", "$cmd \Q$file\E"
1494 or die "($prefix) Could not execute '$cmd'";
1495 while (my $address = <$fh>) {
1496 $address =~ s/^\s*//g;
1497 $address =~ s/\s*$//g;
1498 $address = sanitize_address
($address);
1499 next if ($address eq $sender and $suppress_cc{'self'});
1500 push @addresses, $address;
1501 printf("($prefix) Adding %s: %s from: '%s'\n",
1502 $what, $address, $cmd) unless $quiet;
1505 or die "($prefix) failed to close pipe to '$cmd'";
1509 cleanup_compose_files
();
1511 sub cleanup_compose_files
{
1512 unlink($compose_filename, $compose_filename . ".final") if $compose;
1515 $smtp->quit if $smtp;
1517 sub unique_email_list
{
1521 foreach my $entry (@_) {
1522 my $clean = extract_valid_address_or_die
($entry);
1523 $seen{$clean} ||= 0;
1524 next if $seen{$clean}++;
1525 push @emails, $entry;
1530 sub validate_patch
{
1532 open(my $fh, '<', $fn)
1533 or die "unable to open $fn: $!\n";
1534 while (my $line = <$fh>) {
1535 if (length($line) > 998) {
1536 return "$.: patch contains a line longer than 998 characters";
1542 sub file_has_nonascii
{
1544 open(my $fh, '<', $fn)
1545 or die "unable to open $fn: $!\n";
1546 while (my $line = <$fh>) {
1547 return 1 if $line =~ /[^[:ascii:]]/;
1552 sub body_or_subject_has_nonascii
{
1554 open(my $fh, '<', $fn)
1555 or die "unable to open $fn: $!\n";
1556 while (my $line = <$fh>) {
1557 last if $line =~ /^$/;
1558 return 1 if $line =~ /^Subject.*[^[:ascii:]]/;
1560 while (my $line = <$fh>) {
1561 return 1 if $line =~ /[^[:ascii:]]/;