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.
21 use warnings
$ENV{GIT_PERL_FATAL_WARNINGS
} ?
qw(FATAL all) : ();
23 use Git
::LoadCPAN
::Error
qw(:try);
27 Getopt
::Long
::Configure qw
/ pass_through /;
31 my ($class, $reason) = @_;
32 return bless \
$reason, shift;
36 die "Cannot use readline on FakeTerm: $$self";
43 git send-email' [<options>] <file|directory>
44 git send-email' [<options>] <format-patch options>
45 git send-email --dump-aliases
48 --from <str> * Email From:
49 --[no-]to <str> * Email To:
50 --[no-]cc <str> * Email Cc:
51 --[no-]bcc <str> * Email Bcc:
52 --subject <str> * Email "Subject:"
53 --reply-to <str> * Email "Reply-To:"
54 --in-reply-to <str> * Email "In-Reply-To:"
55 --[no-]xmailer * Add "X-Mailer:" header (default).
56 --[no-]annotate * Review each patch that will be sent in an editor.
57 --compose * Open an editor for introduction.
58 --compose-encoding <str> * Encoding to assume for introduction.
59 --8bit-encoding <str> * Encoding to assume 8bit mails if undeclared
60 --transfer-encoding <str> * Transfer encoding to use (quoted-printable, 8bit, base64)
63 --envelope-sender <str> * Email envelope sender.
64 --sendmail-cmd <str> * Command to run to send email.
65 --smtp-server <str:int> * Outgoing SMTP server to use. The port
66 is optional. Default 'localhost'.
67 --smtp-server-option <str> * Outgoing SMTP server option to use.
68 --smtp-server-port <int> * Outgoing SMTP server port.
69 --smtp-user <str> * Username for SMTP-AUTH.
70 --smtp-pass <str> * Password for SMTP-AUTH; not necessary.
71 --smtp-encryption <str> * tls or ssl; anything else disables.
72 --smtp-ssl * Deprecated. Use '--smtp-encryption ssl'.
73 --smtp-ssl-cert-path <str> * Path to ca-certificates (either directory or file).
74 Pass an empty string to disable certificate
76 --smtp-domain <str> * The domain name sent to HELO/EHLO handshake
77 --smtp-auth <str> * Space-separated list of allowed AUTH mechanisms, or
78 "none" to disable authentication.
79 This setting forces to use one of the listed mechanisms.
80 --no-smtp-auth Disable SMTP authentication. Shorthand for
82 --smtp-debug <0|1> * Disable, enable Net::SMTP debug.
84 --batch-size <int> * send max <int> message per connection.
85 --relogin-delay <int> * delay <int> seconds between two successive login.
86 This option can only be used with --batch-size
89 --identity <str> * Use the sendemail.<id> options.
90 --to-cmd <str> * Email To: via `<str> \$patch_path`
91 --cc-cmd <str> * Email Cc: via `<str> \$patch_path`
92 --suppress-cc <str> * author, self, sob, cc, cccmd, body, bodycc, misc-by, all.
93 --[no-]cc-cover * Email Cc: addresses in the cover letter.
94 --[no-]to-cover * Email To: addresses in the cover letter.
95 --[no-]signed-off-by-cc * Send to Signed-off-by: addresses. Default on.
96 --[no-]suppress-from * Send to self. Default off.
97 --[no-]chain-reply-to * Chain In-Reply-To: fields. Default off.
98 --[no-]thread * Use In-Reply-To: field. Default on.
101 --confirm <str> * Confirm recipients before sending;
102 auto, cc, compose, always, or never.
103 --quiet * Output one line of info per email.
104 --dry-run * Don't actually send the emails.
105 --[no-]validate * Perform patch sanity checks. Default on.
106 --[no-]format-patch * understand any non optional arguments as
107 `git format-patch` ones.
108 --force * Send even if safety checks would prevent it.
111 --dump-aliases * Dump configured aliases and exit.
119 grep !$seen{$_}++, @_;
122 sub completion_helper
{
123 my ($original_opts) = @_;
124 my %not_for_completion = (
125 "git-completion-helper" => undef,
128 my @send_email_opts = ();
130 foreach my $key (keys %$original_opts) {
131 unless (exists $not_for_completion{$key}) {
134 if ($key =~ /[:=][si]$/) {
135 $key =~ s/[:=][si]$//;
136 push (@send_email_opts, "--$_=") foreach (split (/\|/, $key));
138 push (@send_email_opts, "--$_") foreach (split (/\|/, $key));
143 my @format_patch_opts = split(/ /, Git
::command
('format-patch', '--git-completion-helper'));
144 my @opts = (@send_email_opts, @format_patch_opts);
145 @opts = uniq
(grep !/^$/, @opts);
146 # There's an implicit '\n' here already, no need to add an explicit one.
151 # most mail servers generate the Date: header, but not all...
152 sub format_2822_time
{
154 my @localtm = localtime($time);
155 my @gmttm = gmtime($time);
156 my $localmin = $localtm[1] + $localtm[2] * 60;
157 my $gmtmin = $gmttm[1] + $gmttm[2] * 60;
158 if ($localtm[0] != $gmttm[0]) {
159 die __
("local zone differs from GMT by a non-minute interval\n");
161 if ((($gmttm[6] + 1) % 7) == $localtm[6]) {
163 } elsif ((($gmttm[6] - 1) % 7) == $localtm[6]) {
165 } elsif ($gmttm[6] != $localtm[6]) {
166 die __
("local time offset greater than or equal to 24 hours\n");
168 my $offset = $localmin - $gmtmin;
169 my $offhour = $offset / 60;
170 my $offmin = abs($offset % 60);
171 if (abs($offhour) >= 24) {
172 die __
("local time offset greater than or equal to 24 hours\n");
175 return sprintf("%s, %2d %s %d %02d:%02d:%02d %s%02d%02d",
176 qw(Sun Mon Tue Wed Thu Fri Sat)[$localtm[6]],
178 qw(Jan Feb Mar Apr May Jun
179 Jul Aug Sep Oct Nov Dec)[$localtm[4]],
184 ($offset >= 0) ?
'+' : '-',
194 # Regexes for RFC 2047 productions.
195 my $re_token = qr/[^][()<>@,;:\\"\/?
.= \000-\037\177-\377]+/;
196 my $re_encoded_text = qr/[^? \000-\037\177-\377]+/;
197 my $re_encoded_word = qr/=\?($re_token)\?($re_token)\?($re_encoded_text)\?=/;
199 # Variables we fill in automatically, or via prompting:
200 my (@to,@cc,@xh,$envelope_sender,
201 $initial_in_reply_to,$reply_to,$initial_subject,@files,
202 $author,$sender,$smtp_authpass,$annotate,$compose,$time);
203 # Things we either get from config, *or* are overridden on the
205 my ($no_cc, $no_to, $no_bcc, $no_identity);
206 my (@config_to, @getopt_to);
207 my (@config_cc, @getopt_cc);
208 my (@config_bcc, @getopt_bcc);
211 #$initial_in_reply_to = ''; #<20050203173208.GA23964@foobar.com>';
213 my $repo = eval { Git
->repository() };
214 my @repo = $repo ?
($repo) : ();
216 # Behavior modification variables
217 my ($quiet, $dry_run) = (0, 0);
219 my $compose_filename;
221 my $dump_aliases = 0;
223 # Variables to prevent short format-patch options from being captured
224 # as abbreviated send-email options
227 # Handle interactive edition of files.
232 my ($args, $msg, $cmd_name) = @_;
234 my $signalled = $?
& 127;
235 my $exit_code = $?
>> 8;
236 return unless $signalled or $exit_code;
238 my @sprintf_args = ($cmd_name ?
$cmd_name : $args->[0], $exit_code);
240 # Quiet the 'redundant' warning category, except we
241 # need to support down to Perl 5.8, so we can't do a
242 # "no warnings 'redundant'", since that category was
243 # introduced in perl 5.22, and asking for it will die
246 return sprintf($msg, @sprintf_args);
248 return sprintf(__
("fatal: command '%s' died with exit code %d"),
253 my $msg = system_or_msg
(@_);
258 if (!defined($editor)) {
259 $editor = Git
::command_oneline
('var', 'GIT_EDITOR');
261 my $die_msg = __
("the editor exited uncleanly, aborting everything");
262 if (defined($multiedit) && !$multiedit) {
263 system_or_die
(['sh', '-c', $editor.' "$@"', $editor, $_], $die_msg) for @_;
265 system_or_die
(['sh', '-c', $editor.' "$@"', $editor, @_], $die_msg);
269 # Variables with corresponding config settings
270 my ($suppress_from, $signed_off_by_cc);
271 my ($cover_cc, $cover_to);
272 my ($to_cmd, $cc_cmd);
273 my ($smtp_server, $smtp_server_port, @smtp_server_options);
274 my ($smtp_authuser, $smtp_encryption, $smtp_ssl_cert_path);
275 my ($batch_size, $relogin_delay);
276 my ($identity, $aliasfiletype, @alias_files, $smtp_domain, $smtp_auth);
279 my ($auto_8bit_encoding);
280 my ($compose_encoding);
282 # Variables with corresponding config settings & hardcoded defaults
283 my ($debug_net_smtp) = 0; # Net::SMTP, see send_message()
285 my $chain_reply_to = 0;
288 my $target_xfer_encoding = 'auto';
289 my $forbid_sendmail_variables = 1;
291 my %config_bool_settings = (
292 "thread" => \
$thread,
293 "chainreplyto" => \
$chain_reply_to,
294 "suppressfrom" => \
$suppress_from,
295 "signedoffbycc" => \
$signed_off_by_cc,
296 "cccover" => \
$cover_cc,
297 "tocover" => \
$cover_to,
298 "signedoffcc" => \
$signed_off_by_cc,
299 "validate" => \
$validate,
300 "multiedit" => \
$multiedit,
301 "annotate" => \
$annotate,
302 "xmailer" => \
$use_xmailer,
303 "forbidsendmailvariables" => \
$forbid_sendmail_variables,
306 my %config_settings = (
307 "smtpencryption" => \
$smtp_encryption,
308 "smtpserver" => \
$smtp_server,
309 "smtpserverport" => \
$smtp_server_port,
310 "smtpserveroption" => \
@smtp_server_options,
311 "smtpuser" => \
$smtp_authuser,
312 "smtppass" => \
$smtp_authpass,
313 "smtpdomain" => \
$smtp_domain,
314 "smtpauth" => \
$smtp_auth,
315 "smtpbatchsize" => \
$batch_size,
316 "smtprelogindelay" => \
$relogin_delay,
321 "aliasfiletype" => \
$aliasfiletype,
322 "bcc" => \
@config_bcc,
323 "suppresscc" => \
@suppress_cc,
324 "envelopesender" => \
$envelope_sender,
325 "confirm" => \
$confirm,
327 "assume8bitencoding" => \
$auto_8bit_encoding,
328 "composeencoding" => \
$compose_encoding,
329 "transferencoding" => \
$target_xfer_encoding,
330 "sendmailcmd" => \
$sendmail_cmd,
333 my %config_path_settings = (
334 "aliasesfile" => \
@alias_files,
335 "smtpsslcertpath" => \
$smtp_ssl_cert_path,
338 # Handle Uncouth Termination
341 require Term
::ANSIColor
;
342 print Term
::ANSIColor
::color
("reset"), "\n";
344 # SMTP password masked
347 # tmp files from --compose
348 if (defined $compose_filename) {
349 if (-e
$compose_filename) {
350 printf __
("'%s' contains an intermediate version ".
351 "of the email you were composing.\n"),
354 if (-e
($compose_filename . ".final")) {
355 printf __
("'%s.final' contains the composed email.\n"),
363 $SIG{TERM
} = \
&signal_handler
;
364 $SIG{INT
} = \
&signal_handler
;
366 # Read our sendemail.* config
368 my ($known_keys, $configured, $prefix) = @_;
370 foreach my $setting (keys %config_bool_settings) {
371 my $target = $config_bool_settings{$setting};
372 my $key = "$prefix.$setting";
373 next unless exists $known_keys->{$key};
374 my $v = (@
{$known_keys->{$key}} == 1 &&
375 (defined $known_keys->{$key}->[0] &&
376 $known_keys->{$key}->[0] =~ /^(?:true|false)$/s))
377 ?
$known_keys->{$key}->[0] eq 'true'
378 : Git
::config_bool
(@repo, $key);
379 next unless defined $v;
380 next if $configured->{$setting}++;
384 foreach my $setting (keys %config_path_settings) {
385 my $target = $config_path_settings{$setting};
386 my $key = "$prefix.$setting";
387 next unless exists $known_keys->{$key};
388 if (ref($target) eq "ARRAY") {
389 my @values = Git
::config_path
(@repo, $key);
391 next if $configured->{$setting}++;
395 my $v = Git
::config_path
(@repo, "$prefix.$setting");
396 next unless defined $v;
397 next if $configured->{$setting}++;
402 foreach my $setting (keys %config_settings) {
403 my $target = $config_settings{$setting};
404 my $key = "$prefix.$setting";
405 next unless exists $known_keys->{$key};
406 if (ref($target) eq "ARRAY") {
407 my @values = @
{$known_keys->{$key}};
408 @values = grep { defined } @values;
409 next if $configured->{$setting}++;
413 my $v = $known_keys->{$key}->[-1];
414 next unless defined $v;
415 next if $configured->{$setting}++;
425 my $ret = Git
::command
(
432 # We must always return ($k, $v) here, since
433 # empty config values will be just "key\0",
434 # not "key\nvalue\0".
435 my ($k, $v) = split /\n/, $_, 2;
440 # If we have no keys we're OK, otherwise re-throw
441 die $@
if $@
->value != 1;
446 # Save ourselves a lot of work of shelling out to 'git config' (it
447 # parses 'bool' etc.) by only doing so for config keys that exist.
448 my %known_config_keys;
450 my @kv = config_regexp
("^sende?mail[.]");
451 while (my ($k, $v) = splice @kv, 0, 2) {
452 push @
{$known_config_keys{$k}} => $v;
456 # sendemail.identity yields to --identity. We must parse this
457 # special-case first before the rest of the config is read.
459 my $key = "sendemail.identity";
460 $identity = Git
::config
(@repo, $key) if exists $known_config_keys{$key};
462 my %identity_options = (
463 "identity=s" => \
$identity,
464 "no-identity" => \
$no_identity,
466 my $rc = GetOptions
(%identity_options);
468 undef $identity if $no_identity;
470 # Now we know enough to read the config
473 read_config
(\
%known_config_keys, \
%configured, "sendemail.$identity") if defined $identity;
474 read_config
(\
%known_config_keys, \
%configured, "sendemail");
477 # Begin by accumulating all the variables (defined above), that we will end up
478 # needing, first, from the command line:
481 my $git_completion_helper;
482 my %dump_aliases_options = (
484 "dump-aliases" => \
$dump_aliases,
486 $rc = GetOptions
(%dump_aliases_options);
488 die __
("--dump-aliases incompatible with other options\n")
489 if !$help and $dump_aliases and @ARGV;
491 "sender|from=s" => \
$sender,
492 "in-reply-to=s" => \
$initial_in_reply_to,
493 "reply-to=s" => \
$reply_to,
494 "subject=s" => \
$initial_subject,
495 "to=s" => \
@getopt_to,
496 "to-cmd=s" => \
$to_cmd,
498 "cc=s" => \
@getopt_cc,
500 "bcc=s" => \
@getopt_bcc,
501 "no-bcc" => \
$no_bcc,
502 "chain-reply-to!" => \
$chain_reply_to,
503 "no-chain-reply-to" => sub {$chain_reply_to = 0},
504 "sendmail-cmd=s" => \
$sendmail_cmd,
505 "smtp-server=s" => \
$smtp_server,
506 "smtp-server-option=s" => \
@smtp_server_options,
507 "smtp-server-port=s" => \
$smtp_server_port,
508 "smtp-user=s" => \
$smtp_authuser,
509 "smtp-pass:s" => \
$smtp_authpass,
510 "smtp-ssl" => sub { $smtp_encryption = 'ssl' },
511 "smtp-encryption=s" => \
$smtp_encryption,
512 "smtp-ssl-cert-path=s" => \
$smtp_ssl_cert_path,
513 "smtp-debug:i" => \
$debug_net_smtp,
514 "smtp-domain:s" => \
$smtp_domain,
515 "smtp-auth=s" => \
$smtp_auth,
516 "no-smtp-auth" => sub {$smtp_auth = 'none'},
517 "annotate!" => \
$annotate,
518 "no-annotate" => sub {$annotate = 0},
519 "compose" => \
$compose,
521 "cc-cmd=s" => \
$cc_cmd,
522 "suppress-from!" => \
$suppress_from,
523 "no-suppress-from" => sub {$suppress_from = 0},
524 "suppress-cc=s" => \
@suppress_cc,
525 "signed-off-cc|signed-off-by-cc!" => \
$signed_off_by_cc,
526 "no-signed-off-cc|no-signed-off-by-cc" => sub {$signed_off_by_cc = 0},
527 "cc-cover|cc-cover!" => \
$cover_cc,
528 "no-cc-cover" => sub {$cover_cc = 0},
529 "to-cover|to-cover!" => \
$cover_to,
530 "no-to-cover" => sub {$cover_to = 0},
531 "confirm=s" => \
$confirm,
532 "dry-run" => \
$dry_run,
533 "envelope-sender=s" => \
$envelope_sender,
534 "thread!" => \
$thread,
535 "no-thread" => sub {$thread = 0},
536 "validate!" => \
$validate,
537 "no-validate" => sub {$validate = 0},
538 "transfer-encoding=s" => \
$target_xfer_encoding,
539 "format-patch!" => \
$format_patch,
540 "no-format-patch" => sub {$format_patch = 0},
541 "8bit-encoding=s" => \
$auto_8bit_encoding,
542 "compose-encoding=s" => \
$compose_encoding,
544 "xmailer!" => \
$use_xmailer,
545 "no-xmailer" => sub {$use_xmailer = 0},
546 "batch-size=i" => \
$batch_size,
547 "relogin-delay=i" => \
$relogin_delay,
548 "git-completion-helper" => \
$git_completion_helper,
549 "v=s" => \
$reroll_count,
551 $rc = GetOptions
(%options);
553 # Munge any "either config or getopt, not both" variables
554 my @initial_to = @getopt_to ?
@getopt_to : ($no_to ?
() : @config_to);
555 my @initial_cc = @getopt_cc ?
@getopt_cc : ($no_cc ?
() : @config_cc);
556 my @initial_bcc = @getopt_bcc ?
@getopt_bcc : ($no_bcc ?
() : @config_bcc);
559 my %all_options = (%options, %dump_aliases_options, %identity_options);
560 completion_helper
(\
%all_options) if $git_completion_helper;
565 if ($forbid_sendmail_variables && grep { /^sendmail/s } keys %known_config_keys) {
566 die __
("fatal: found configuration options for 'sendmail'\n" .
567 "git-send-email is configured with the sendemail.* options - note the 'e'.\n" .
568 "Set sendemail.forbidSendmailVariables to false to disable this check.\n");
571 die __
("Cannot run git format-patch from outside a repository\n")
572 if $format_patch and not $repo;
574 die __
("`batch-size` and `relogin` must be specified together " .
575 "(via command-line or configuration option)\n")
576 if defined $relogin_delay and not defined $batch_size;
578 # 'default' encryption is none -- this only prevents a warning
579 $smtp_encryption = '' unless (defined $smtp_encryption);
581 # Set CC suppressions
584 foreach my $entry (@suppress_cc) {
585 # Please update $__git_send_email_suppresscc_options
586 # in git-completion.bash when you add new options.
587 die sprintf(__
("Unknown --suppress-cc field: '%s'\n"), $entry)
588 unless $entry =~ /^(?:all|cccmd|cc|author|self|sob|body|bodycc|misc-by)$/;
589 $suppress_cc{$entry} = 1;
593 if ($suppress_cc{'all'}) {
594 foreach my $entry (qw
(cccmd cc author self sob body bodycc misc
-by
)) {
595 $suppress_cc{$entry} = 1;
597 delete $suppress_cc{'all'};
600 # If explicit old-style ones are specified, they trump --suppress-cc.
601 $suppress_cc{'self'} = $suppress_from if defined $suppress_from;
602 $suppress_cc{'sob'} = !$signed_off_by_cc if defined $signed_off_by_cc;
604 if ($suppress_cc{'body'}) {
605 foreach my $entry (qw
(sob bodycc misc
-by
)) {
606 $suppress_cc{$entry} = 1;
608 delete $suppress_cc{'body'};
611 # Set confirm's default value
612 my $confirm_unconfigured = !defined $confirm;
613 if ($confirm_unconfigured) {
614 $confirm = scalar %suppress_cc ?
'compose' : 'auto';
616 # Please update $__git_send_email_confirm_options in
617 # git-completion.bash when you add new options.
618 die sprintf(__
("Unknown --confirm setting: '%s'\n"), $confirm)
619 unless $confirm =~ /^(?:auto|cc|compose|always|never)/;
621 # Debugging, print out the suppressions.
623 print "suppressions:\n";
624 foreach my $entry (keys %suppress_cc) {
625 printf " %-5s -> $suppress_cc{$entry}\n", $entry;
629 my ($repoauthor, $repocommitter);
632 my ($author, $committer);
635 return $cache{$what} if exists $cache{$what};
636 ($cache{$what}) = Git
::ident_person
(@repo, $what);
637 return $cache{$what};
639 $repoauthor = sub { $common->('author') };
640 $repocommitter = sub { $common->('committer') };
643 sub parse_address_line
{
644 require Git
::LoadCPAN
::Mail
::Address
;
645 return map { $_->format } Mail
::Address
->parse($_[0]);
649 require Text
::ParseWords
;
650 return Text
::ParseWords
::quotewords
('\s*,\s*', 1, @_);
655 sub parse_sendmail_alias
{
658 printf STDERR __
("warning: sendmail alias with quotes is not supported: %s\n"), $_;
659 } elsif (/:include:/) {
660 printf STDERR __
("warning: `:include:` not supported: %s\n"), $_;
662 printf STDERR __
("warning: `/file` or `|pipe` redirection not supported: %s\n"), $_;
663 } elsif (/^(\S+?)\s*:\s*(.+)$/) {
664 my ($alias, $addr) = ($1, $2);
665 $aliases{$alias} = [ split_addrs
($addr) ];
667 printf STDERR __
("warning: sendmail line is not recognized: %s\n"), $_;
671 sub parse_sendmail_aliases
{
676 next if /^\s*$/ || /^\s*#/;
677 $s .= $_, next if $s =~ s/\\$// || s/^\s+//;
678 parse_sendmail_alias
($s) if $s;
681 $s =~ s/\\$//; # silently tolerate stray '\' on last line
682 parse_sendmail_alias
($s) if $s;
686 # multiline formats can be supported in the future
687 mutt
=> sub { my $fh = shift; while (<$fh>) {
688 if (/^\s*alias\s+(?:-group\s+\S+\s+)*(\S+)\s+(.*)$/) {
689 my ($alias, $addr) = ($1, $2);
690 $addr =~ s/#.*$//; # mutt allows # comments
691 # commas delimit multiple addresses
692 my @addr = split_addrs
($addr);
694 # quotes may be escaped in the file,
695 # unescape them so we do not double-escape them later.
696 s/\\"/"/g foreach @addr;
697 $aliases{$alias} = \
@addr
699 mailrc
=> sub { my $fh = shift; while (<$fh>) {
700 if (/^alias\s+(\S+)\s+(.*?)\s*$/) {
701 require Text
::ParseWords
;
702 # spaces delimit multiple addresses
703 $aliases{$1} = [ Text
::ParseWords
::quotewords
('\s+', 0, $2) ];
705 pine
=> sub { my $fh = shift; my $f='\t[^\t]*';
706 for (my $x = ''; defined($x); $x = $_) {
708 $x .= $1 while(defined($_ = <$fh>) && /^ +(.*)$/);
709 $x =~ /^(\S+)$f\t\(?([^\t]+?)\)?(:?$f){0,2}$/ or next;
710 $aliases{$1} = [ split_addrs
($2) ];
712 elm
=> sub { my $fh = shift;
714 if (/^(\S+)\s+=\s+[^=]+=\s(\S+)/) {
715 my ($alias, $addr) = ($1, $2);
716 $aliases{$alias} = [ split_addrs
($addr) ];
719 sendmail
=> \
&parse_sendmail_aliases
,
720 gnus
=> sub { my $fh = shift; while (<$fh>) {
721 if (/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) {
722 $aliases{$1} = [ $2 ];
724 # Please update _git_config() in git-completion.bash when you
728 if (@alias_files and $aliasfiletype and defined $parse_alias{$aliasfiletype}) {
729 foreach my $file (@alias_files) {
730 open my $fh, '<', $file or die "opening $file: $!\n";
731 $parse_alias{$aliasfiletype}->($fh);
737 print "$_\n" for (sort keys %aliases);
741 # is_format_patch_arg($f) returns 0 if $f names a patch, or 1 if
742 # $f is a revision list specification to be passed to format-patch.
743 sub is_format_patch_arg
{
747 $repo->command('rev-parse', '--verify', '--quiet', $f);
748 if (defined($format_patch)) {
749 return $format_patch;
751 die sprintf(__
(<<EOF), $f, $f);
752 File '%s' exists but it could also be the range of commits
753 to produce patches for. Please disambiguate by...
755 * Saying "./%s" if you mean a file; or
756 * Giving --format-patch option if you mean a range.
758 } catch Git
::Error
::Command with
{
759 # Not a valid revision. Treat it as a filename.
764 # Now that all the defaults are set, process the rest of the command line
765 # arguments and collect up the files that need to be processed.
767 while (defined(my $f = shift @ARGV)) {
769 push @rev_list_opts, "--", @ARGV;
771 } elsif (-d
$f and !is_format_patch_arg
($f)) {
773 or die sprintf(__
("Failed to opendir %s: %s"), $f, $!);
776 push @files, grep { -f
$_ } map { File
::Spec
->catfile($f, $_) }
779 } elsif ((-f
$f or -p
$f) and !is_format_patch_arg
($f)) {
782 push @rev_list_opts, $f;
786 if (@rev_list_opts) {
787 die __
("Cannot run git format-patch from outside a repository\n")
790 push @files, $repo->command('format-patch', '-o', File
::Temp
::tempdir
(CLEANUP
=> 1),
791 defined $reroll_count ?
('-v', $reroll_count) : (),
795 if (defined $sender) {
796 $sender =~ s/^\s+|\s+$//g;
797 ($sender) = expand_aliases
($sender);
799 $sender = $repoauthor->() || $repocommitter->() || '';
802 # $sender could be an already sanitized address
803 # (e.g. sendemail.from could be manually sanitized by user).
804 # But it's a no-op to run sanitize_address on an already sanitized address.
805 $sender = sanitize_address
($sender);
807 $time = time - scalar $#files;
810 # FIFOs can only be read once, exclude them from validation.
812 foreach my $f (@files) {
814 push(@real_files, $f);
818 # Run the loop once again to avoid gaps in the counter due to FIFO
819 # arguments provided by the user.
821 my $num_files = scalar @real_files;
822 $ENV{GIT_SENDEMAIL_FILE_TOTAL
} = "$num_files";
823 foreach my $r (@real_files) {
824 $ENV{GIT_SENDEMAIL_FILE_COUNTER
} = "$num";
825 pre_process_file
($r, 1);
826 validate_patch
($r, $target_xfer_encoding);
829 delete $ENV{GIT_SENDEMAIL_FILE_COUNTER
};
830 delete $ENV{GIT_SENDEMAIL_FILE_TOTAL
};
833 @files = handle_backup_files
(@files);
837 print $_,"\n" for (@files);
840 print STDERR __
("\nNo patch files specified!\n\n");
844 sub get_patch_subject
{
846 open (my $fh, '<', $fn);
847 while (my $line = <$fh>) {
848 next unless ($line =~ /^Subject: (.*)$/);
853 die sprintf(__
("No subject line in %s?"), $fn);
857 # Note that this does not need to be secure, but we will make a small
858 # effort to have it be unique
860 $compose_filename = ($repo ?
861 File
::Temp
::tempfile
(".gitsendemail.msg.XXXXXX", DIR
=> $repo->repo_path()) :
862 File
::Temp
::tempfile
(".gitsendemail.msg.XXXXXX", DIR
=> "."))[1];
863 open my $c, ">", $compose_filename
864 or die sprintf(__
("Failed to open for writing %s: %s"), $compose_filename, $!);
867 my $tpl_sender = $sender || $repoauthor->() || $repocommitter->() || '';
868 my $tpl_subject = $initial_subject || '';
869 my $tpl_in_reply_to = $initial_in_reply_to || '';
870 my $tpl_reply_to = $reply_to || '';
872 print $c <<EOT1, Git::prefix_lines("GIT: ", __(<<EOT2)), <<EOT3;
873 From $tpl_sender # This line is ignored.
875 Lines beginning in "GIT:" will be removed.
876 Consider including an overall diffstat or table of contents
877 for the patch you are writing.
879 Clear the body content if you don't wish to send a summary.
882 Reply-To: $tpl_reply_to
883 Subject: $tpl_subject
884 In-Reply-To: $tpl_in_reply_to
888 print $c get_patch_subject($f);
893 do_edit($compose_filename, @files);
895 do_edit($compose_filename);
898 open $c, "<", $compose_filename
899 or die sprintf(__("Failed to open %s: %s"), $compose_filename, $!);
901 if (!defined $compose_encoding) {
902 $compose_encoding = "UTF-8";
906 while (my $line = <$c>) {
907 next if $line =~ m/^GIT:/;
908 parse_header_line($line, \%parsed_email);
910 $parsed_email{'body'} = filter_body($c);
915 open my $c2, ">", $compose_filename . ".final"
916 or die sprintf(__("Failed to open %s.final: %s"), $compose_filename, $!);
919 if ($parsed_email{'From'}) {
920 $sender = delete($parsed_email{'From'});
922 if ($parsed_email{'In-Reply-To'}) {
923 $initial_in_reply_to = delete($parsed_email{'In-Reply-To'});
925 if ($parsed_email{'Reply-To'}) {
926 $reply_to = delete($parsed_email{'Reply-To'});
928 if ($parsed_email{'Subject'}) {
929 $initial_subject = delete($parsed_email{'Subject'});
930 print $c2 "Subject: " .
931 quote_subject($initial_subject, $compose_encoding) .
935 if ($parsed_email{'MIME-Version'}) {
936 print $c2 "MIME-Version: $parsed_email{'MIME-Version'}\n",
937 "Content-Type: $parsed_email{'Content-Type'};\n",
938 "Content-Transfer-Encoding: $parsed_email{'Content-Transfer-Encoding'}\n";
939 delete($parsed_email{'MIME-Version'});
940 delete($parsed_email{'Content-Type'});
941 delete($parsed_email{'Content-Transfer-Encoding'});
942 } elsif (file_has_nonascii($compose_filename)) {
943 my $content_type = (delete($parsed_email{'Content-Type'}) or
944 "text/plain; charset=$compose_encoding");
945 print $c2 "MIME-Version: 1.0\n",
946 "Content-Type: $content_type\n",
947 "Content-Transfer-Encoding: 8bit\n";
949 # Preserve unknown headers
950 foreach my $key (keys %parsed_email) {
951 next if $key eq 'body';
952 print $c2 "$key: $parsed_email{$key}";
955 if ($parsed_email{'body'}) {
956 print $c2 "\n$parsed_email{'body'}\n";
957 delete($parsed_email{'body'});
959 print __("Summary email is empty, skipping it\n");
965 } elsif ($annotate) {
971 require Term::ReadLine;
972 $ENV{"GIT_SEND_EMAIL_NOTTY"}
973 ? Term::ReadLine->new('git-send-email', \*STDIN, \*STDOUT)
974 : Term::ReadLine->new('git-send-email');
977 $term = FakeTerm->new("$@: going non-interactive");
983 my ($prompt, %arg) = @_;
984 my $valid_re = $arg{valid_re};
985 my $default = $arg{default};
986 my $confirm_only = $arg{confirm_only};
990 return defined $default ? $default : undef
991 unless defined $term->IN and defined fileno($term->IN) and
992 defined $term->OUT and defined fileno($term->OUT);
994 $resp = $term->readline($prompt);
995 if (!defined $resp) { # EOF
997 return defined $default ? $default : undef;
999 if ($resp eq '' and defined $default) {
1002 if (!defined $valid_re or $resp =~ /$valid_re/) {
1005 if ($confirm_only) {
1006 my $yesno = $term->readline(
1007 # TRANSLATORS: please keep [y/N] as is.
1008 sprintf(__("Are you sure you want to use <%s> [y/N]? "), $resp));
1009 if (defined $yesno && $yesno =~ /y/i) {
1017 sub parse_header_line {
1019 my $parsed_line = shift;
1020 my $addr_pat = join "|", qw(To Cc Bcc);
1022 foreach (split(/\n/, $lines)) {
1023 if (/^($addr_pat):\s*(.+)$/i) {
1024 $parsed_line->{$1} = [ parse_address_line
($2) ];
1025 } elsif (/^([^:]*):\s*(.+)\s*$/i) {
1026 $parsed_line->{$1} = $2;
1034 while (my $body_line = <$c>) {
1035 if ($body_line !~ m/^GIT:/) {
1036 $body .= $body_line;
1043 my %broken_encoding;
1045 sub file_declares_8bit_cte
{
1047 open (my $fh, '<', $fn);
1048 while (my $line = <$fh>) {
1049 last if ($line =~ /^$/);
1050 return 1 if ($line =~ /^Content-Transfer-Encoding: .*8bit.*$/);
1056 foreach my $f (@files) {
1057 next unless (body_or_subject_has_nonascii
($f)
1058 && !file_declares_8bit_cte
($f));
1059 $broken_encoding{$f} = 1;
1062 if (!defined $auto_8bit_encoding && scalar %broken_encoding) {
1063 print __
("The following files are 8bit, but do not declare " .
1064 "a Content-Transfer-Encoding.\n");
1065 foreach my $f (sort keys %broken_encoding) {
1068 $auto_8bit_encoding = ask
(__
("Which 8bit encoding should I declare [UTF-8]? "),
1069 valid_re
=> qr/.{4}/, confirm_only
=> 1,
1070 default => "UTF-8");
1074 for my $f (@files) {
1075 if (get_patch_subject
($f) =~ /\Q*** SUBJECT HERE ***\E/) {
1076 die sprintf(__
("Refusing to send because the patch\n\t%s\n"
1077 . "has the template subject '*** SUBJECT HERE ***'. "
1078 . "Pass --force if you really want to send.\n"), $f);
1083 my $to_whom = __
("To whom should the emails be sent (if anyone)?");
1085 if (!@initial_to && !defined $to_cmd) {
1086 my $to = ask
("$to_whom ",
1088 valid_re
=> qr/\@.*\./, confirm_only
=> 1);
1089 push @initial_to, parse_address_line
($to) if defined $to; # sanitized/validated later
1093 sub expand_aliases
{
1094 return map { expand_one_alias
($_) } @_;
1097 my %EXPANDED_ALIASES;
1098 sub expand_one_alias
{
1100 if ($EXPANDED_ALIASES{$alias}) {
1101 die sprintf(__
("fatal: alias '%s' expands to itself\n"), $alias);
1103 local $EXPANDED_ALIASES{$alias} = 1;
1104 return $aliases{$alias} ? expand_aliases
(@
{$aliases{$alias}}) : $alias;
1107 @initial_to = process_address_list
(@initial_to);
1108 @initial_cc = process_address_list
(@initial_cc);
1109 @initial_bcc = process_address_list
(@initial_bcc);
1111 if ($thread && !defined $initial_in_reply_to && $prompting) {
1112 $initial_in_reply_to = ask
(
1113 __
("Message-ID to be used as In-Reply-To for the first email (if any)? "),
1115 valid_re
=> qr/\@.*\./, confirm_only
=> 1);
1117 if (defined $initial_in_reply_to) {
1118 $initial_in_reply_to =~ s/^\s*<?//;
1119 $initial_in_reply_to =~ s/>?\s*$//;
1120 $initial_in_reply_to = "<$initial_in_reply_to>" if $initial_in_reply_to ne '';
1123 if (defined $reply_to) {
1124 $reply_to =~ s/^\s+|\s+$//g;
1125 ($reply_to) = expand_aliases
($reply_to);
1126 $reply_to = sanitize_address
($reply_to);
1129 if (!defined $sendmail_cmd && !defined $smtp_server) {
1130 my @sendmail_paths = qw( /usr/sbin/sendmail /usr/lib/sendmail );
1131 push @sendmail_paths, map {"$_/sendmail"} split /:/, $ENV{PATH
};
1132 foreach (@sendmail_paths) {
1139 if (!defined $sendmail_cmd) {
1140 $smtp_server = 'localhost'; # could be 127.0.0.1, too... *shrug*
1144 if ($compose && $compose > 0) {
1145 @files = ($compose_filename . ".final", @files);
1148 # Variables we set as part of the loop over files
1149 our ($message_id, %mail, $subject, $in_reply_to, $references, $message,
1150 $needs_confirm, $message_num, $ask_default);
1152 sub extract_valid_address
{
1153 my $address = shift;
1154 my $local_part_regexp = qr/[^<>"\s@]+/;
1155 my $domain_regexp = qr/[^.<>"\s@]+(?:\.[^.<>"\s@]+)+/;
1157 # check for a local address:
1158 return $address if ($address =~ /^($local_part_regexp)$/);
1160 $address =~ s/^\s*<(.*)>\s*$/$1/;
1161 my $have_email_valid = eval { require Email
::Valid
; 1 };
1162 if ($have_email_valid) {
1163 return scalar Email
::Valid
->address($address);
1166 # less robust/correct than the monster regexp in Email::Valid,
1167 # but still does a 99% job, and one less dependency
1168 return $1 if $address =~ /($local_part_regexp\@$domain_regexp)/;
1172 sub extract_valid_address_or_die
{
1173 my $address = shift;
1174 $address = extract_valid_address
($address);
1175 die sprintf(__
("error: unable to extract a valid address from: %s\n"), $address)
1180 sub validate_address
{
1181 my $address = shift;
1182 while (!extract_valid_address
($address)) {
1183 printf STDERR __
("error: unable to extract a valid address from: %s\n"), $address;
1184 # TRANSLATORS: Make sure to include [q] [d] [e] in your
1185 # translation. The program will only accept English input
1187 $_ = ask
(__
("What to do with this address? ([q]uit|[d]rop|[e]dit): "),
1188 valid_re
=> qr/^(?:quit|q|drop|d|edit|e)/i,
1193 cleanup_compose_files
();
1196 $address = ask
("$to_whom ",
1198 valid_re
=> qr/\@.*\./, confirm_only
=> 1);
1203 sub validate_address_list
{
1204 return (grep { defined $_ }
1205 map { validate_address
($_) } @_);
1208 # Usually don't need to change anything below here.
1210 # we make a "fake" message id by taking the current number
1211 # of seconds since the beginning of Unix time and tacking on
1212 # a random number to the end, in case we are called quicker than
1213 # 1 second since the last time we were called.
1215 # We'll setup a template for the message id, using the "from" address:
1217 my ($message_id_stamp, $message_id_serial);
1218 sub make_message_id
{
1220 if (!defined $message_id_stamp) {
1222 $message_id_stamp = POSIX
::strftime
("%Y%m%d%H%M%S.$$", gmtime(time));
1223 $message_id_serial = 0;
1225 $message_id_serial++;
1226 $uniq = "$message_id_stamp-$message_id_serial";
1229 for ($sender, $repocommitter->(), $repoauthor->()) {
1230 $du_part = extract_valid_address
(sanitize_address
($_));
1231 last if (defined $du_part and $du_part ne '');
1233 if (not defined $du_part or $du_part eq '') {
1234 require Sys
::Hostname
;
1235 $du_part = 'user@' . Sys
::Hostname
::hostname
();
1237 my $message_id_template = "<%s-%s>";
1238 $message_id = sprintf($message_id_template, $uniq, $du_part);
1239 #print "new message id = $message_id\n"; # Was useful for debugging
1242 sub unquote_rfc2047
{
1245 my $sep = qr/[ \t]+/;
1246 s
{$re_encoded_word(?
:$sep$re_encoded_word)*}{
1247 my @words = split $sep, $&;
1249 m/$re_encoded_word/;
1253 if ($encoding eq 'q' || $encoding eq 'Q') {
1256 s/=([0-9A-F]{2})/chr(hex($1))/egi;
1258 # other encodings not supported yet
1263 return wantarray ?
($_, $charset) : $_;
1268 my $encoding = shift || 'UTF-8';
1269 s/([^-a-zA-Z0-9!*+\/])/sprintf
("=%02X", ord($1))/eg
;
1270 s/(.*)/=\?$encoding\?q\?$1\?=/;
1274 sub is_rfc2047_quoted
{
1277 $s =~ m/^(?:"[[:ascii:]]*"|$re_encoded_word)$/o;
1280 sub subject_needs_rfc2047_quoting
{
1283 return ($s =~ /[^[:ascii:]]/) || ($s =~ /=\?/);
1287 local $subject = shift;
1288 my $encoding = shift || 'UTF-8';
1290 if (subject_needs_rfc2047_quoting
($subject)) {
1291 return quote_rfc2047
($subject, $encoding);
1296 # use the simplest quoting being able to handle the recipient
1297 sub sanitize_address
{
1298 my ($recipient) = @_;
1300 # remove garbage after email address
1301 $recipient =~ s/(.*>).*$/$1/;
1303 my ($recipient_name, $recipient_addr) = ($recipient =~ /^(.*?)\s*(<.*)/);
1305 if (not $recipient_name) {
1309 # if recipient_name is already quoted, do nothing
1310 if (is_rfc2047_quoted
($recipient_name)) {
1314 # remove non-escaped quotes
1315 $recipient_name =~ s/(^|[^\\])"/$1/g;
1317 # rfc2047 is needed if a non-ascii char is included
1318 if ($recipient_name =~ /[^[:ascii:]]/) {
1319 $recipient_name = quote_rfc2047
($recipient_name);
1322 # double quotes are needed if specials or CTLs are included
1323 elsif ($recipient_name =~ /[][()<>@,;:\\".\000-\037\177]/) {
1324 $recipient_name =~ s/([\\\r])/\\$1/g;
1325 $recipient_name = qq["$recipient_name"];
1328 return "$recipient_name $recipient_addr";
1332 sub strip_garbage_one_address
{
1335 if ($addr =~ /^(("[^"]*"|[^"<]*)? *<[^>]*>).*/) {
1336 # "Foo Bar" <foobar@example.com> [possibly garbage here]
1337 # Foo Bar <foobar@example.com> [possibly garbage here]
1340 if ($addr =~ /^(<[^>]*>).*/) {
1341 # <foo@example.com> [possibly garbage here]
1342 # if garbage contains other addresses, they are ignored.
1345 if ($addr =~ /^([^"#,\s]*)/) {
1346 # address without quoting: remove anything after the address
1352 sub sanitize_address_list
{
1353 return (map { sanitize_address
($_) } @_);
1356 sub process_address_list
{
1357 my @addr_list = map { parse_address_line
($_) } @_;
1358 @addr_list = expand_aliases
(@addr_list);
1359 @addr_list = sanitize_address_list
(@addr_list);
1360 @addr_list = validate_address_list
(@addr_list);
1364 # Returns the local Fully Qualified Domain Name (FQDN) if available.
1366 # Tightly configured MTAa require that a caller sends a real DNS
1367 # domain name that corresponds the IP address in the HELO/EHLO
1368 # handshake. This is used to verify the connection and prevent
1369 # spammers from trying to hide their identity. If the DNS and IP don't
1370 # match, the receiving MTA may deny the connection.
1372 # Here is a deny example of Net::SMTP with the default "localhost.localdomain"
1374 # Net::SMTP=GLOB(0x267ec28)>>> EHLO localhost.localdomain
1375 # Net::SMTP=GLOB(0x267ec28)<<< 550 EHLO argument does not match calling host
1377 # This maildomain*() code is based on ideas in Perl library Test::Reporter
1378 # /usr/share/perl5/Test/Reporter/Mail/Util.pm ==> sub _maildomain ()
1382 return defined $domain && !($^O
eq 'darwin' && $domain =~ /\.local$/) && $domain =~ /\./;
1385 sub maildomain_net
{
1388 require Net
::Domain
;
1389 my $domain = Net
::Domain
::domainname
();
1390 $maildomain = $domain if valid_fqdn
($domain);
1395 sub maildomain_mta
{
1398 for my $host (qw(mailhost localhost)) {
1400 my $smtp = Net
::SMTP
->new($host);
1401 if (defined $smtp) {
1402 my $domain = $smtp->domain;
1405 $maildomain = $domain if valid_fqdn
($domain);
1407 last if $maildomain;
1415 return maildomain_net
() || maildomain_mta
() || 'localhost.localdomain';
1418 sub smtp_host_string
{
1419 if (defined $smtp_server_port) {
1420 return "$smtp_server:$smtp_server_port";
1422 return $smtp_server;
1426 # Returns 1 if authentication succeeded or was not necessary
1427 # (smtp_user was not specified), and 0 otherwise.
1429 sub smtp_auth_maybe
{
1430 if (!defined $smtp_authuser || $auth || (defined $smtp_auth && $smtp_auth eq "none")) {
1434 # Workaround AUTH PLAIN/LOGIN interaction defect
1435 # with Authen::SASL::Cyrus
1437 require Authen
::SASL
;
1438 Authen
::SASL
->import(qw(Perl));
1441 # Check mechanism naming as defined in:
1442 # https://tools.ietf.org/html/rfc4422#page-8
1443 if ($smtp_auth && $smtp_auth !~ /^(\b[A-Z0-9-_]{1,20}\s*)*$/) {
1444 die "invalid smtp auth: '${smtp_auth}'";
1447 # TODO: Authentication may fail not because credentials were
1448 # invalid but due to other reasons, in which we should not
1449 # reject credentials.
1450 $auth = Git
::credential
({
1451 'protocol' => 'smtp',
1452 'host' => smtp_host_string
(),
1453 'username' => $smtp_authuser,
1454 # if there's no password, "git credential fill" will
1455 # give us one, otherwise it'll just pass this one.
1456 'password' => $smtp_authpass
1461 my $sasl = Authen
::SASL
->new(
1462 mechanism
=> $smtp_auth,
1464 user
=> $cred->{'username'},
1465 pass
=> $cred->{'password'},
1466 authname
=> $cred->{'username'},
1470 return !!$smtp->auth($sasl);
1473 return !!$smtp->auth($cred->{'username'}, $cred->{'password'});
1479 sub ssl_verify_params
{
1481 require IO
::Socket
::SSL
;
1482 IO
::Socket
::SSL
->import(qw
/SSL_VERIFY_PEER SSL_VERIFY_NONE/);
1485 print STDERR
"Not using SSL_VERIFY_PEER due to out-of-date IO::Socket::SSL.\n";
1489 if (!defined $smtp_ssl_cert_path) {
1490 # use the OpenSSL defaults
1491 return (SSL_verify_mode
=> SSL_VERIFY_PEER
());
1494 if ($smtp_ssl_cert_path eq "") {
1495 return (SSL_verify_mode
=> SSL_VERIFY_NONE
());
1496 } elsif (-d
$smtp_ssl_cert_path) {
1497 return (SSL_verify_mode
=> SSL_VERIFY_PEER
(),
1498 SSL_ca_path
=> $smtp_ssl_cert_path);
1499 } elsif (-f
$smtp_ssl_cert_path) {
1500 return (SSL_verify_mode
=> SSL_VERIFY_PEER
(),
1501 SSL_ca_file
=> $smtp_ssl_cert_path);
1503 die sprintf(__
("CA path \"%s\" does not exist"), $smtp_ssl_cert_path);
1507 sub file_name_is_absolute
{
1510 # msys does not grok DOS drive-prefixes
1511 if ($^O
eq 'msys') {
1512 return ($path =~ m
#^/# || $path =~ m#^[a-zA-Z]\:#)
1515 require File
::Spec
::Functions
;
1516 return File
::Spec
::Functions
::file_name_is_absolute
($path);
1520 my @recipients = unique_email_list
(@to);
1521 @cc = (grep { my $cc = extract_valid_address_or_die
($_);
1522 not grep { $cc eq $_ || $_ =~ /<\Q${cc}\E>$/ } @recipients
1525 my $to = join (",\n\t", @recipients);
1526 @recipients = unique_email_list
(@recipients,@cc,@initial_bcc);
1527 @recipients = (map { extract_valid_address_or_die
($_) } @recipients);
1528 my $date = format_2822_time
($time++);
1529 my $gitversion = '@@GIT_VERSION@@';
1530 if ($gitversion =~ m/..GIT_VERSION../) {
1531 $gitversion = Git
::version
();
1534 my $cc = join(",\n\t", unique_email_list
(@cc));
1537 $ccline = "\nCc: $cc";
1539 make_message_id
() unless defined($message_id);
1541 my $header = "From: $sender
1545 Message-ID: $message_id
1548 $header .= "X-Mailer: git-send-email $gitversion\n";
1552 $header .= "In-Reply-To: $in_reply_to\n";
1553 $header .= "References: $references\n";
1556 $header .= "Reply-To: $reply_to\n";
1559 $header .= join("\n", @xh) . "\n";
1561 my $recipients_ref = \
@recipients;
1562 return ($recipients_ref, $to, $date, $gitversion, $cc, $ccline, $header);
1565 # Prepares the email, then asks the user what to do.
1567 # If the user chooses to send the email, it's sent and 1 is returned.
1568 # If the user chooses not to send the email, 0 is returned.
1569 # If the user decides they want to make further edits, -1 is returned and the
1570 # caller is expected to call send_message again after the edits are performed.
1572 # If an error occurs sending the email, this just dies.
1575 my ($recipients_ref, $to, $date, $gitversion, $cc, $ccline, $header) = gen_header
();
1576 my @recipients = @
$recipients_ref;
1578 my @sendmail_parameters = ('-i', @recipients);
1579 my $raw_from = $sender;
1580 if (defined $envelope_sender && $envelope_sender ne "auto") {
1581 $raw_from = $envelope_sender;
1583 $raw_from = extract_valid_address
($raw_from);
1584 unshift (@sendmail_parameters,
1585 '-f', $raw_from) if(defined $envelope_sender);
1587 if ($needs_confirm && !$dry_run) {
1588 print "\n$header\n";
1589 if ($needs_confirm eq "inform") {
1590 $confirm_unconfigured = 0; # squelch this message for the rest of this run
1591 $ask_default = "y"; # assume yes on EOF since user hasn't explicitly asked for confirmation
1593 The Cc list above has been expanded by additional
1594 addresses found in the patch commit message. By default
1595 send-email prompts before sending whenever this occurs.
1596 This behavior is controlled by the sendemail.confirm
1597 configuration setting.
1599 For additional information, run 'git send-email --help'.
1600 To retain the current behavior, but squelch this message,
1601 run 'git config --global sendemail.confirm auto'.
1605 # TRANSLATORS: Make sure to include [y] [n] [e] [q] [a] in your
1606 # translation. The program will only accept English input
1608 $_ = ask
(__
("Send this email? ([y]es|[n]o|[e]dit|[q]uit|[a]ll): "),
1609 valid_re
=> qr/^(?:yes|y|no|n|edit|e|quit|q|all|a)/i,
1610 default => $ask_default);
1611 die __
("Send this email reply required") unless defined $_;
1617 cleanup_compose_files
();
1624 unshift (@sendmail_parameters, @smtp_server_options);
1627 # We don't want to send the email.
1628 } elsif (defined $sendmail_cmd || file_name_is_absolute
($smtp_server)) {
1629 my $pid = open my $sm, '|-';
1630 defined $pid or die $!;
1632 if (defined $sendmail_cmd) {
1633 exec ("sh", "-c", "$sendmail_cmd \"\$@\"", "-", @sendmail_parameters)
1636 exec ($smtp_server, @sendmail_parameters)
1640 print $sm "$header\n$message";
1641 close $sm or die $!;
1644 if (!defined $smtp_server) {
1645 die __
("The required SMTP server is not properly defined.")
1649 my $use_net_smtp_ssl = version
->parse($Net::SMTP
::VERSION
) < version
->parse("2.34");
1650 $smtp_domain ||= maildomain
();
1652 if ($smtp_encryption eq 'ssl') {
1653 $smtp_server_port ||= 465; # ssmtp
1654 require IO
::Socket
::SSL
;
1656 # Suppress "variable accessed once" warning.
1659 $IO::Socket
::SSL
::DEBUG
= 1;
1662 # Net::SMTP::SSL->new() does not forward any SSL options
1663 IO
::Socket
::SSL
::set_client_defaults
(
1664 ssl_verify_params
());
1666 if ($use_net_smtp_ssl) {
1667 require Net
::SMTP
::SSL
;
1668 $smtp ||= Net
::SMTP
::SSL
->new($smtp_server,
1669 Hello
=> $smtp_domain,
1670 Port
=> $smtp_server_port,
1671 Debug
=> $debug_net_smtp);
1674 $smtp ||= Net
::SMTP
->new($smtp_server,
1675 Hello
=> $smtp_domain,
1676 Port
=> $smtp_server_port,
1677 Debug
=> $debug_net_smtp,
1682 $smtp_server_port ||= 25;
1683 $smtp ||= Net
::SMTP
->new($smtp_server,
1684 Hello
=> $smtp_domain,
1685 Debug
=> $debug_net_smtp,
1686 Port
=> $smtp_server_port);
1687 if ($smtp_encryption eq 'tls' && $smtp) {
1688 if ($use_net_smtp_ssl) {
1689 $smtp->command('STARTTLS');
1691 if ($smtp->code != 220) {
1692 die sprintf(__
("Server does not support STARTTLS! %s"), $smtp->message);
1694 require Net
::SMTP
::SSL
;
1695 $smtp = Net
::SMTP
::SSL
->start_SSL($smtp,
1696 ssl_verify_params
())
1697 or die sprintf(__
("STARTTLS failed! %s"), IO
::Socket
::SSL
::errstr
());
1700 $smtp->starttls(ssl_verify_params
())
1701 or die sprintf(__
("STARTTLS failed! %s"), IO
::Socket
::SSL
::errstr
());
1703 # Send EHLO again to receive fresh
1704 # supported commands
1705 $smtp->hello($smtp_domain);
1710 die __
("Unable to initialize SMTP properly. Check config and use --smtp-debug."),
1711 " VALUES: server=$smtp_server ",
1712 "encryption=$smtp_encryption ",
1713 "hello=$smtp_domain",
1714 defined $smtp_server_port ?
" port=$smtp_server_port" : "";
1717 smtp_auth_maybe
or die $smtp->message;
1719 $smtp->mail( $raw_from ) or die $smtp->message;
1720 $smtp->to( @recipients ) or die $smtp->message;
1721 $smtp->data or die $smtp->message;
1722 $smtp->datasend("$header\n") or die $smtp->message;
1723 my @lines = split /^/, $message;
1724 foreach my $line (@lines) {
1725 $smtp->datasend("$line") or die $smtp->message;
1727 $smtp->dataend() or die $smtp->message;
1728 $smtp->code =~ /250|200/ or die sprintf(__
("Failed to send %s\n"), $subject).$smtp->message;
1731 printf($dry_run ? __
("Dry-Sent %s\n") : __
("Sent %s\n"), $subject);
1733 print($dry_run ? __
("Dry-OK. Log says:\n") : __
("OK. Log says:\n"));
1734 if (!defined $sendmail_cmd && !file_name_is_absolute
($smtp_server)) {
1735 print "Server: $smtp_server\n";
1736 print "MAIL FROM:<$raw_from>\n";
1737 foreach my $entry (@recipients) {
1738 print "RCPT TO:<$entry>\n";
1742 if (defined $sendmail_cmd) {
1743 $sm = $sendmail_cmd;
1748 print "Sendmail: $sm ".join(' ',@sendmail_parameters)."\n";
1750 print $header, "\n";
1752 print __
("Result: "), $smtp->code, ' ',
1753 ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
1755 print __
("Result: OK\n");
1762 $in_reply_to = $initial_in_reply_to;
1763 $references = $initial_in_reply_to || '';
1766 sub pre_process_file
{
1767 my ($t, $quiet) = @_;
1769 open my $fh, "<", $t or die sprintf(__
("can't open file %s"), $t);
1772 my $sauthor = undef;
1773 my $author_encoding;
1774 my $has_content_type;
1777 my $has_mime_version;
1781 my $input_format = undef;
1783 $subject = $initial_subject;
1786 # First unfold multiline header fields
1789 if (/^\s+\S/ and @header) {
1790 chomp($header[$#header]);
1792 $header[$#header] .= $_;
1797 # Now parse the header
1800 $input_format = 'mbox';
1804 if (!defined $input_format && /^[-A-Za-z]+:\s/) {
1805 $input_format = 'mbox';
1808 if (defined $input_format && $input_format eq 'mbox') {
1809 if (/^Subject:\s+(.*)$/i) {
1812 elsif (/^From:\s+(.*)$/i) {
1813 ($author, $author_encoding) = unquote_rfc2047
($1);
1814 $sauthor = sanitize_address
($author);
1815 next if $suppress_cc{'author'};
1816 next if $suppress_cc{'self'} and $sauthor eq $sender;
1817 printf(__
("(mbox) Adding cc: %s from line '%s'\n"),
1818 $1, $_) unless $quiet;
1821 elsif (/^To:\s+(.*)$/i) {
1822 foreach my $addr (parse_address_line
($1)) {
1823 printf(__
("(mbox) Adding to: %s from line '%s'\n"),
1824 $addr, $_) unless $quiet;
1828 elsif (/^Cc:\s+(.*)$/i) {
1829 foreach my $addr (parse_address_line
($1)) {
1830 my $qaddr = unquote_rfc2047
($addr);
1831 my $saddr = sanitize_address
($qaddr);
1832 if ($saddr eq $sender) {
1833 next if ($suppress_cc{'self'});
1835 next if ($suppress_cc{'cc'});
1837 printf(__
("(mbox) Adding cc: %s from line '%s'\n"),
1838 $addr, $_) unless $quiet;
1842 elsif (/^Content-type:/i) {
1843 $has_content_type = 1;
1844 if (/charset="?([^ "]+)/) {
1845 $body_encoding = $1;
1849 elsif (/^MIME-Version/i) {
1850 $has_mime_version = 1;
1853 elsif (/^Message-ID: (.*)/i) {
1856 elsif (/^Content-Transfer-Encoding: (.*)/i) {
1857 $xfer_encoding = $1 if not defined $xfer_encoding;
1859 elsif (/^In-Reply-To: (.*)/i) {
1860 if (!$initial_in_reply_to || $thread) {
1864 elsif (/^References: (.*)/i) {
1865 if (!$initial_in_reply_to || $thread) {
1869 elsif (!/^Date:\s/i && /^[-A-Za-z]+:\s+\S/) {
1873 # In the traditional
1874 # "send lots of email" format,
1877 # So let's support that, too.
1878 $input_format = 'lots';
1879 if (@cc == 0 && !$suppress_cc{'cc'}) {
1880 printf(__
("(non-mbox) Adding cc: %s from line '%s'\n"),
1881 $_, $_) unless $quiet;
1883 } elsif (!defined $subject) {
1888 # Now parse the message body
1891 if (/^([a-z][a-z-]*-by|Cc): (.*)/i) {
1893 my ($what, $c) = ($1, $2);
1894 # strip garbage for the address we'll use:
1895 $c = strip_garbage_one_address
($c);
1896 # sanitize a bit more to decide whether to suppress the address:
1897 my $sc = sanitize_address
($c);
1898 if ($sc eq $sender) {
1899 next if ($suppress_cc{'self'});
1901 if ($what =~ /^Signed-off-by$/i) {
1902 next if $suppress_cc{'sob'};
1903 } elsif ($what =~ /-by$/i) {
1904 next if $suppress_cc{'misc-by'};
1905 } elsif ($what =~ /Cc/i) {
1906 next if $suppress_cc{'bodycc'};
1909 if ($c !~ /.+@.+|<.+>/) {
1910 printf("(body) Ignoring %s from line '%s'\n",
1911 $what, $_) unless $quiet;
1915 printf(__
("(body) Adding cc: %s from line '%s'\n"),
1916 $c, $_) unless $quiet;
1921 push @to, recipients_cmd
("to-cmd", "to", $to_cmd, $t, $quiet)
1923 push @cc, recipients_cmd
("cc-cmd", "cc", $cc_cmd, $t, $quiet)
1924 if defined $cc_cmd && !$suppress_cc{'cccmd'};
1926 if ($broken_encoding{$t} && !$has_content_type) {
1927 $xfer_encoding = '8bit' if not defined $xfer_encoding;
1928 $has_content_type = 1;
1929 push @xh, "Content-Type: text/plain; charset=$auto_8bit_encoding";
1930 $body_encoding = $auto_8bit_encoding;
1933 if ($broken_encoding{$t} && !is_rfc2047_quoted
($subject)) {
1934 $subject = quote_subject
($subject, $auto_8bit_encoding);
1937 if (defined $sauthor and $sauthor ne $sender) {
1938 $message = "From: $author\n\n$message";
1939 if (defined $author_encoding) {
1940 if ($has_content_type) {
1941 if ($body_encoding eq $author_encoding) {
1942 # ok, we already have the right encoding
1945 # uh oh, we should re-encode
1949 $xfer_encoding = '8bit' if not defined $xfer_encoding;
1950 $has_content_type = 1;
1952 "Content-Type: text/plain; charset=$author_encoding";
1956 $xfer_encoding = '8bit' if not defined $xfer_encoding;
1957 ($message, $xfer_encoding) = apply_transfer_encoding
(
1958 $message, $xfer_encoding, $target_xfer_encoding);
1959 push @xh, "Content-Transfer-Encoding: $xfer_encoding";
1960 unshift @xh, 'MIME-Version: 1.0' unless $has_mime_version;
1963 $confirm eq "always" or
1964 ($confirm =~ /^(?:auto|cc)$/ && @cc) or
1965 ($confirm =~ /^(?:auto|compose)$/ && $compose && $message_num == 1));
1966 $needs_confirm = "inform" if ($needs_confirm && $confirm_unconfigured && @cc);
1968 @to = process_address_list
(@to);
1969 @cc = process_address_list
(@cc);
1971 @to = (@initial_to, @to);
1972 @cc = (@initial_cc, @cc);
1974 if ($message_num == 1) {
1975 if (defined $cover_cc and $cover_cc) {
1978 if (defined $cover_to and $cover_to) {
1984 # Prepares the email, prompts the user, and sends it out
1985 # Returns 0 if an edit was done and the function should be called again, or 1
1986 # on the email being successfully sent out.
1990 pre_process_file
($t, $quiet);
1992 my $message_was_sent = send_message
();
1993 if ($message_was_sent == -1) {
1998 # set up for the next message
2000 if ($message_was_sent &&
2001 ($chain_reply_to || !defined $in_reply_to || length($in_reply_to) == 0 ||
2002 $message_num == 1)) {
2003 $in_reply_to = $message_id;
2004 if (length $references > 0) {
2005 $references .= "\n $message_id";
2007 $references = "$message_id";
2010 } elsif (!defined $initial_in_reply_to) {
2011 # --thread and --in-reply-to manage the "In-Reply-To" header and by
2012 # extension the "References" header. If these commands are not used, reset
2013 # the header values to their defaults.
2014 $in_reply_to = undef;
2017 $message_id = undef;
2019 if (defined $batch_size && $num_sent == $batch_size) {
2021 $smtp->quit if defined $smtp;
2024 sleep($relogin_delay) if defined $relogin_delay;
2030 foreach my $t (@files) {
2031 while (!process_file
($t)) {
2032 # user edited the file
2036 # Execute a command (e.g. $to_cmd) to get a list of email addresses
2037 # and return a results array
2038 sub recipients_cmd
{
2039 my ($prefix, $what, $cmd, $file, $quiet) = @_;
2042 open my $fh, "-|", "$cmd \Q$file\E"
2043 or die sprintf(__
("(%s) Could not execute '%s'"), $prefix, $cmd);
2044 while (my $address = <$fh>) {
2045 $address =~ s/^\s*//g;
2046 $address =~ s/\s*$//g;
2047 $address = sanitize_address
($address);
2048 next if ($address eq $sender and $suppress_cc{'self'});
2049 push @addresses, $address;
2050 printf(__
("(%s) Adding %s: %s from: '%s'\n"),
2051 $prefix, $what, $address, $cmd) unless $quiet;
2054 or die sprintf(__
("(%s) failed to close pipe to '%s'"), $prefix, $cmd);
2058 cleanup_compose_files
();
2060 sub cleanup_compose_files
{
2061 unlink($compose_filename, $compose_filename . ".final") if $compose;
2064 $smtp->quit if $smtp;
2066 sub apply_transfer_encoding
{
2067 my $message = shift;
2071 return ($message, $to) if ($from eq $to and $from ne '7bit');
2073 require MIME
::QuotedPrint
;
2074 require MIME
::Base64
;
2076 $message = MIME
::QuotedPrint
::decode
($message)
2077 if ($from eq 'quoted-printable');
2078 $message = MIME
::Base64
::decode
($message)
2079 if ($from eq 'base64');
2081 $to = ($message =~ /(?:.{999,}|\r)/) ?
'quoted-printable' : '8bit'
2084 die __
("cannot send message as 7bit")
2085 if ($to eq '7bit' and $message =~ /[^[:ascii:]]/);
2086 return ($message, $to)
2087 if ($to eq '7bit' or $to eq '8bit');
2088 return (MIME
::QuotedPrint
::encode
($message, "\n", 0), $to)
2089 if ($to eq 'quoted-printable');
2090 return (MIME
::Base64
::encode
($message, "\n"), $to)
2091 if ($to eq 'base64');
2092 die __
("invalid transfer encoding");
2095 sub unique_email_list
{
2099 foreach my $entry (@_) {
2100 my $clean = extract_valid_address_or_die
($entry);
2101 $seen{$clean} ||= 0;
2102 next if $seen{$clean}++;
2103 push @emails, $entry;
2108 sub validate_patch
{
2109 my ($fn, $xfer_encoding) = @_;
2112 my $hook_name = 'sendemail-validate';
2113 my $hooks_path = $repo->command_oneline('rev-parse', '--git-path', 'hooks');
2115 my $validate_hook = File
::Spec
->catfile($hooks_path, $hook_name);
2117 if (-x
$validate_hook) {
2119 my $target = Cwd
::abs_path
($fn);
2120 # The hook needs a correct cwd and GIT_DIR.
2121 my $cwd_save = Cwd
::getcwd
();
2122 chdir($repo->wc_path() or $repo->repo_path())
2123 or die("chdir: $!");
2124 local $ENV{"GIT_DIR"} = $repo->repo_path();
2126 my ($recipients_ref, $to, $date, $gitversion, $cc, $ccline, $header) = gen_header
();
2129 my ($header_filehandle, $header_filename) = File
::Temp
::tempfile
(
2130 TEMPLATE
=> ".gitsendemail.header.XXXXXX",
2131 DIR
=> $repo->repo_path(),
2134 print $header_filehandle $header;
2136 my @cmd = ("git", "hook", "run", "--ignore-missing",
2138 my @cmd_msg = (@cmd, "<patch>", "<header>");
2139 my @cmd_run = (@cmd, $target, $header_filename);
2140 $hook_error = system_or_msg
(\
@cmd_run, undef, "@cmd_msg");
2141 chdir($cwd_save) or die("chdir: $!");
2144 $hook_error = sprintf(
2145 __
("fatal: %s: rejected by %s hook\n%s\nwarning: no patches were sent\n"),
2146 $fn, $hook_name, $hook_error);
2151 # Any long lines will be automatically fixed if we use a suitable transfer
2153 unless ($xfer_encoding =~ /^(?:auto|quoted-printable|base64)$/) {
2154 open(my $fh, '<', $fn)
2155 or die sprintf(__
("unable to open %s: %s\n"), $fn, $!);
2156 while (my $line = <$fh>) {
2157 if (length($line) > 998) {
2158 die sprintf(__
("fatal: %s:%d is longer than 998 characters\n" .
2159 "warning: no patches were sent\n"), $fn, $.);
2167 my ($last, $lastlen, $file, $known_suffix) = @_;
2168 my ($suffix, $skip);
2171 if (defined $last &&
2172 ($lastlen < length($file)) &&
2173 (substr($file, 0, $lastlen) eq $last) &&
2174 ($suffix = substr($file, $lastlen)) !~ /^[a-z0-9]/i) {
2175 if (defined $known_suffix && $suffix eq $known_suffix) {
2176 printf(__
("Skipping %s with backup suffix '%s'.\n"), $file, $known_suffix);
2179 # TRANSLATORS: please keep "[y|N]" as is.
2180 my $answer = ask
(sprintf(__
("Do you really want to send %s? [y|N]: "), $file),
2181 valid_re
=> qr/^(?:y|n)/i,
2183 $skip = ($answer ne 'y');
2185 $known_suffix = $suffix;
2189 return ($skip, $known_suffix);
2192 sub handle_backup_files
{
2194 my ($last, $lastlen, $known_suffix, $skip, @result);
2195 for my $file (@file) {
2196 ($skip, $known_suffix) = handle_backup
($last, $lastlen,
2197 $file, $known_suffix);
2198 push @result, $file unless $skip;
2200 $lastlen = length($file);
2205 sub file_has_nonascii
{
2207 open(my $fh, '<', $fn)
2208 or die sprintf(__
("unable to open %s: %s\n"), $fn, $!);
2209 while (my $line = <$fh>) {
2210 return 1 if $line =~ /[^[:ascii:]]/;
2215 sub body_or_subject_has_nonascii
{
2217 open(my $fh, '<', $fn)
2218 or die sprintf(__
("unable to open %s: %s\n"), $fn, $!);
2219 while (my $line = <$fh>) {
2220 last if $line =~ /^$/;
2221 return 1 if $line =~ /^Subject.*[^[:ascii:]]/;
2223 while (my $line = <$fh>) {
2224 return 1 if $line =~ /[^[:ascii:]]/;