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.
22 use POSIX qw
/strftime/;
27 use File
::Temp qw
/ tempdir tempfile /;
28 use File
::Spec
::Functions
qw(catdir catfile);
29 use Git
::LoadCPAN
::Error
qw(:try);
30 use Cwd
qw(abs_path cwd);
35 use Git
::LoadCPAN
::Mail
::Address
;
37 Getopt
::Long
::Configure qw
/ pass_through /;
41 my ($class, $reason) = @_;
42 return bless \
$reason, shift;
46 die "Cannot use readline on FakeTerm: $$self";
53 git send-email [options] <file | directory | rev-list options >
54 git send-email --dump-aliases
57 --from <str> * Email From:
58 --[no-]to <str> * Email To:
59 --[no-]cc <str> * Email Cc:
60 --[no-]bcc <str> * Email Bcc:
61 --subject <str> * Email "Subject:"
62 --reply-to <str> * Email "Reply-To:"
63 --in-reply-to <str> * Email "In-Reply-To:"
64 --[no-]xmailer * Add "X-Mailer:" header (default).
65 --[no-]annotate * Review each patch that will be sent in an editor.
66 --compose * Open an editor for introduction.
67 --compose-encoding <str> * Encoding to assume for introduction.
68 --8bit-encoding <str> * Encoding to assume 8bit mails if undeclared
69 --transfer-encoding <str> * Transfer encoding to use (quoted-printable, 8bit, base64)
72 --envelope-sender <str> * Email envelope sender.
73 --smtp-server <str:int> * Outgoing SMTP server to use. The port
74 is optional. Default 'localhost'.
75 --smtp-server-option <str> * Outgoing SMTP server option to use.
76 --smtp-server-port <int> * Outgoing SMTP server port.
77 --smtp-user <str> * Username for SMTP-AUTH.
78 --smtp-pass <str> * Password for SMTP-AUTH; not necessary.
79 --smtp-encryption <str> * tls or ssl; anything else disables.
80 --smtp-ssl * Deprecated. Use '--smtp-encryption ssl'.
81 --smtp-ssl-cert-path <str> * Path to ca-certificates (either directory or file).
82 Pass an empty string to disable certificate
84 --smtp-domain <str> * The domain name sent to HELO/EHLO handshake
85 --smtp-auth <str> * Space-separated list of allowed AUTH mechanisms, or
86 "none" to disable authentication.
87 This setting forces to use one of the listed mechanisms.
88 --no-smtp-auth Disable SMTP authentication. Shorthand for
90 --smtp-debug <0|1> * Disable, enable Net::SMTP debug.
92 --batch-size <int> * send max <int> message per connection.
93 --relogin-delay <int> * delay <int> seconds between two successive login.
94 This option can only be used with --batch-size
97 --identity <str> * Use the sendemail.<id> options.
98 --to-cmd <str> * Email To: via `<str> \$patch_path`
99 --cc-cmd <str> * Email Cc: via `<str> \$patch_path`
100 --suppress-cc <str> * author, self, sob, cc, cccmd, body, bodycc, misc-by, all.
101 --[no-]cc-cover * Email Cc: addresses in the cover letter.
102 --[no-]to-cover * Email To: addresses in the cover letter.
103 --[no-]signed-off-by-cc * Send to Signed-off-by: addresses. Default on.
104 --[no-]suppress-from * Send to self. Default off.
105 --[no-]chain-reply-to * Chain In-Reply-To: fields. Default off.
106 --[no-]thread * Use In-Reply-To: field. Default on.
109 --confirm <str> * Confirm recipients before sending;
110 auto, cc, compose, always, or never.
111 --quiet * Output one line of info per email.
112 --dry-run * Don't actually send the emails.
113 --[no-]validate * Perform patch sanity checks. Default on.
114 --[no-]format-patch * understand any non optional arguments as
115 `git format-patch` ones.
116 --force * Send even if safety checks would prevent it.
119 --dump-aliases * Dump configured aliases and exit.
125 sub completion_helper
{
126 print Git
::command
('format-patch', '--git-completion-helper');
130 # most mail servers generate the Date: header, but not all...
131 sub format_2822_time
{
133 my @localtm = localtime($time);
134 my @gmttm = gmtime($time);
135 my $localmin = $localtm[1] + $localtm[2] * 60;
136 my $gmtmin = $gmttm[1] + $gmttm[2] * 60;
137 if ($localtm[0] != $gmttm[0]) {
138 die __
("local zone differs from GMT by a non-minute interval\n");
140 if ((($gmttm[6] + 1) % 7) == $localtm[6]) {
142 } elsif ((($gmttm[6] - 1) % 7) == $localtm[6]) {
144 } elsif ($gmttm[6] != $localtm[6]) {
145 die __
("local time offset greater than or equal to 24 hours\n");
147 my $offset = $localmin - $gmtmin;
148 my $offhour = $offset / 60;
149 my $offmin = abs($offset % 60);
150 if (abs($offhour) >= 24) {
151 die __
("local time offset greater than or equal to 24 hours\n");
154 return sprintf("%s, %2d %s %d %02d:%02d:%02d %s%02d%02d",
155 qw(Sun Mon Tue Wed Thu Fri Sat)[$localtm[6]],
157 qw(Jan Feb Mar Apr May Jun
158 Jul Aug Sep Oct Nov Dec)[$localtm[4]],
163 ($offset >= 0) ?
'+' : '-',
169 my $have_email_valid = eval { require Email
::Valid
; 1 };
174 # Regexes for RFC 2047 productions.
175 my $re_token = qr/[^][()<>@,;:\\"\/?
.= \000-\037\177-\377]+/;
176 my $re_encoded_text = qr/[^? \000-\037\177-\377]+/;
177 my $re_encoded_word = qr/=\?($re_token)\?($re_token)\?($re_encoded_text)\?=/;
179 # Variables we fill in automatically, or via prompting:
180 my (@to,@cc,@xh,$envelope_sender,
181 $initial_in_reply_to,$reply_to,$initial_subject,@files,
182 $author,$sender,$smtp_authpass,$annotate,$compose,$time);
183 # Things we either get from config, *or* are overridden on the
185 my ($no_cc, $no_to, $no_bcc, $no_identity);
186 my (@config_to, @getopt_to);
187 my (@config_cc, @getopt_cc);
188 my (@config_bcc, @getopt_bcc);
191 #$initial_in_reply_to = ''; #<20050203173208.GA23964@foobar.com>';
193 my $repo = eval { Git
->repository() };
194 my @repo = $repo ?
($repo) : ();
196 $ENV{"GIT_SEND_EMAIL_NOTTY"}
197 ? new Term
::ReadLine
'git-send-email', \
*STDIN
, \
*STDOUT
198 : new Term
::ReadLine
'git-send-email';
201 $term = new FakeTerm
"$@: going non-interactive";
204 # Behavior modification variables
205 my ($quiet, $dry_run) = (0, 0);
207 my $compose_filename;
209 my $dump_aliases = 0;
211 # Handle interactive edition of files.
216 if (!defined($editor)) {
217 $editor = Git
::command_oneline
('var', 'GIT_EDITOR');
219 if (defined($multiedit) && !$multiedit) {
221 system('sh', '-c', $editor.' "$@"', $editor, $_);
222 if (($?
& 127) || ($?
>> 8)) {
223 die(__
("the editor exited uncleanly, aborting everything"));
227 system('sh', '-c', $editor.' "$@"', $editor, @_);
228 if (($?
& 127) || ($?
>> 8)) {
229 die(__
("the editor exited uncleanly, aborting everything"));
234 # Variables with corresponding config settings
235 my ($suppress_from, $signed_off_by_cc);
236 my ($cover_cc, $cover_to);
237 my ($to_cmd, $cc_cmd);
238 my ($smtp_server, $smtp_server_port, @smtp_server_options);
239 my ($smtp_authuser, $smtp_encryption, $smtp_ssl_cert_path);
240 my ($batch_size, $relogin_delay);
241 my ($identity, $aliasfiletype, @alias_files, $smtp_domain, $smtp_auth);
244 my ($auto_8bit_encoding);
245 my ($compose_encoding);
246 # Variables with corresponding config settings & hardcoded defaults
247 my ($debug_net_smtp) = 0; # Net::SMTP, see send_message()
249 my $chain_reply_to = 0;
252 my $target_xfer_encoding = 'auto';
254 my %config_bool_settings = (
255 "thread" => \
$thread,
256 "chainreplyto" => \
$chain_reply_to,
257 "suppressfrom" => \
$suppress_from,
258 "signedoffbycc" => \
$signed_off_by_cc,
259 "cccover" => \
$cover_cc,
260 "tocover" => \
$cover_to,
261 "signedoffcc" => \
$signed_off_by_cc,
262 "validate" => \
$validate,
263 "multiedit" => \
$multiedit,
264 "annotate" => \
$annotate,
265 "xmailer" => \
$use_xmailer,
268 my %config_settings = (
269 "smtpserver" => \
$smtp_server,
270 "smtpserverport" => \
$smtp_server_port,
271 "smtpserveroption" => \
@smtp_server_options,
272 "smtpuser" => \
$smtp_authuser,
273 "smtppass" => \
$smtp_authpass,
274 "smtpdomain" => \
$smtp_domain,
275 "smtpauth" => \
$smtp_auth,
276 "smtpbatchsize" => \
$batch_size,
277 "smtprelogindelay" => \
$relogin_delay,
282 "aliasfiletype" => \
$aliasfiletype,
283 "bcc" => \
@config_bcc,
284 "suppresscc" => \
@suppress_cc,
285 "envelopesender" => \
$envelope_sender,
286 "confirm" => \
$confirm,
288 "assume8bitencoding" => \
$auto_8bit_encoding,
289 "composeencoding" => \
$compose_encoding,
290 "transferencoding" => \
$target_xfer_encoding,
293 my %config_path_settings = (
294 "aliasesfile" => \
@alias_files,
295 "smtpsslcertpath" => \
$smtp_ssl_cert_path,
298 # Handle Uncouth Termination
302 print color
("reset"), "\n";
304 # SMTP password masked
307 # tmp files from --compose
308 if (defined $compose_filename) {
309 if (-e
$compose_filename) {
310 printf __
("'%s' contains an intermediate version ".
311 "of the email you were composing.\n"),
314 if (-e
($compose_filename . ".final")) {
315 printf __
("'%s.final' contains the composed email.\n"),
323 $SIG{TERM
} = \
&signal_handler
;
324 $SIG{INT
} = \
&signal_handler
;
326 # Read our sendemail.* config
328 my ($configured, $prefix) = @_;
330 foreach my $setting (keys %config_bool_settings) {
331 my $target = $config_bool_settings{$setting};
332 my $v = Git
::config_bool
(@repo, "$prefix.$setting");
333 next unless defined $v;
334 next if $configured->{$setting}++;
338 foreach my $setting (keys %config_path_settings) {
339 my $target = $config_path_settings{$setting};
340 if (ref($target) eq "ARRAY") {
341 my @values = Git
::config_path
(@repo, "$prefix.$setting");
343 next if $configured->{$setting}++;
347 my $v = Git
::config_path
(@repo, "$prefix.$setting");
348 next unless defined $v;
349 next if $configured->{$setting}++;
354 foreach my $setting (keys %config_settings) {
355 my $target = $config_settings{$setting};
356 if (ref($target) eq "ARRAY") {
357 my @values = Git
::config
(@repo, "$prefix.$setting");
359 next if $configured->{$setting}++;
363 my $v = Git
::config
(@repo, "$prefix.$setting");
364 next unless defined $v;
365 next if $configured->{$setting}++;
370 if (!defined $smtp_encryption) {
371 my $setting = "$prefix.smtpencryption";
372 my $enc = Git
::config
(@repo, $setting);
373 return unless defined $enc;
374 return if $configured->{$setting}++;
376 $smtp_encryption = $enc;
377 } elsif (Git
::config_bool
(@repo, "$prefix.smtpssl")) {
378 $smtp_encryption = 'ssl';
383 # sendemail.identity yields to --identity. We must parse this
384 # special-case first before the rest of the config is read.
385 $identity = Git
::config
(@repo, "sendemail.identity");
387 "identity=s" => \
$identity,
388 "no-identity" => \
$no_identity,
391 undef $identity if $no_identity;
393 # Now we know enough to read the config
396 read_config
(\
%configured, "sendemail.$identity") if defined $identity;
397 read_config
(\
%configured, "sendemail");
400 # Begin by accumulating all the variables (defined above), that we will end up
401 # needing, first, from the command line:
404 my $git_completion_helper;
405 $rc = GetOptions
("h" => \
$help,
406 "dump-aliases" => \
$dump_aliases);
408 die __
("--dump-aliases incompatible with other options\n")
409 if !$help and $dump_aliases and @ARGV;
411 "sender|from=s" => \
$sender,
412 "in-reply-to=s" => \
$initial_in_reply_to,
413 "reply-to=s" => \
$reply_to,
414 "subject=s" => \
$initial_subject,
415 "to=s" => \
@getopt_to,
416 "to-cmd=s" => \
$to_cmd,
418 "cc=s" => \
@getopt_cc,
420 "bcc=s" => \
@getopt_bcc,
421 "no-bcc" => \
$no_bcc,
422 "chain-reply-to!" => \
$chain_reply_to,
423 "no-chain-reply-to" => sub {$chain_reply_to = 0},
424 "smtp-server=s" => \
$smtp_server,
425 "smtp-server-option=s" => \
@smtp_server_options,
426 "smtp-server-port=s" => \
$smtp_server_port,
427 "smtp-user=s" => \
$smtp_authuser,
428 "smtp-pass:s" => \
$smtp_authpass,
429 "smtp-ssl" => sub { $smtp_encryption = 'ssl' },
430 "smtp-encryption=s" => \
$smtp_encryption,
431 "smtp-ssl-cert-path=s" => \
$smtp_ssl_cert_path,
432 "smtp-debug:i" => \
$debug_net_smtp,
433 "smtp-domain:s" => \
$smtp_domain,
434 "smtp-auth=s" => \
$smtp_auth,
435 "no-smtp-auth" => sub {$smtp_auth = 'none'},
436 "annotate!" => \
$annotate,
437 "no-annotate" => sub {$annotate = 0},
438 "compose" => \
$compose,
440 "cc-cmd=s" => \
$cc_cmd,
441 "suppress-from!" => \
$suppress_from,
442 "no-suppress-from" => sub {$suppress_from = 0},
443 "suppress-cc=s" => \
@suppress_cc,
444 "signed-off-cc|signed-off-by-cc!" => \
$signed_off_by_cc,
445 "no-signed-off-cc|no-signed-off-by-cc" => sub {$signed_off_by_cc = 0},
446 "cc-cover|cc-cover!" => \
$cover_cc,
447 "no-cc-cover" => sub {$cover_cc = 0},
448 "to-cover|to-cover!" => \
$cover_to,
449 "no-to-cover" => sub {$cover_to = 0},
450 "confirm=s" => \
$confirm,
451 "dry-run" => \
$dry_run,
452 "envelope-sender=s" => \
$envelope_sender,
453 "thread!" => \
$thread,
454 "no-thread" => sub {$thread = 0},
455 "validate!" => \
$validate,
456 "no-validate" => sub {$validate = 0},
457 "transfer-encoding=s" => \
$target_xfer_encoding,
458 "format-patch!" => \
$format_patch,
459 "no-format-patch" => sub {$format_patch = 0},
460 "8bit-encoding=s" => \
$auto_8bit_encoding,
461 "compose-encoding=s" => \
$compose_encoding,
463 "xmailer!" => \
$use_xmailer,
464 "no-xmailer" => sub {$use_xmailer = 0},
465 "batch-size=i" => \
$batch_size,
466 "relogin-delay=i" => \
$relogin_delay,
467 "git-completion-helper" => \
$git_completion_helper,
470 # Munge any "either config or getopt, not both" variables
471 my @initial_to = @getopt_to ?
@getopt_to : ($no_to ?
() : @config_to);
472 my @initial_cc = @getopt_cc ?
@getopt_cc : ($no_cc ?
() : @config_cc);
473 my @initial_bcc = @getopt_bcc ?
@getopt_bcc : ($no_bcc ?
() : @config_bcc);
476 completion_helper
() if $git_completion_helper;
481 die __
("Cannot run git format-patch from outside a repository\n")
482 if $format_patch and not $repo;
484 die __
("`batch-size` and `relogin` must be specified together " .
485 "(via command-line or configuration option)\n")
486 if defined $relogin_delay and not defined $batch_size;
488 # 'default' encryption is none -- this only prevents a warning
489 $smtp_encryption = '' unless (defined $smtp_encryption);
491 # Set CC suppressions
494 foreach my $entry (@suppress_cc) {
495 # Please update $__git_send_email_suppresscc_options
496 # in git-completion.bash when you add new options.
497 die sprintf(__
("Unknown --suppress-cc field: '%s'\n"), $entry)
498 unless $entry =~ /^(?:all|cccmd|cc|author|self|sob|body|bodycc|misc-by)$/;
499 $suppress_cc{$entry} = 1;
503 if ($suppress_cc{'all'}) {
504 foreach my $entry (qw
(cccmd cc author self sob body bodycc misc
-by
)) {
505 $suppress_cc{$entry} = 1;
507 delete $suppress_cc{'all'};
510 # If explicit old-style ones are specified, they trump --suppress-cc.
511 $suppress_cc{'self'} = $suppress_from if defined $suppress_from;
512 $suppress_cc{'sob'} = !$signed_off_by_cc if defined $signed_off_by_cc;
514 if ($suppress_cc{'body'}) {
515 foreach my $entry (qw
(sob bodycc misc
-by
)) {
516 $suppress_cc{$entry} = 1;
518 delete $suppress_cc{'body'};
521 # Set confirm's default value
522 my $confirm_unconfigured = !defined $confirm;
523 if ($confirm_unconfigured) {
524 $confirm = scalar %suppress_cc ?
'compose' : 'auto';
526 # Please update $__git_send_email_confirm_options in
527 # git-completion.bash when you add new options.
528 die sprintf(__
("Unknown --confirm setting: '%s'\n"), $confirm)
529 unless $confirm =~ /^(?:auto|cc|compose|always|never)/;
531 # Debugging, print out the suppressions.
533 print "suppressions:\n";
534 foreach my $entry (keys %suppress_cc) {
535 printf " %-5s -> $suppress_cc{$entry}\n", $entry;
539 my ($repoauthor, $repocommitter);
540 ($repoauthor) = Git
::ident_person
(@repo, 'author');
541 ($repocommitter) = Git
::ident_person
(@repo, 'committer');
543 sub parse_address_line
{
544 return map { $_->format } Mail
::Address
->parse($_[0]);
548 return quotewords
('\s*,\s*', 1, @_);
553 sub parse_sendmail_alias
{
556 printf STDERR __
("warning: sendmail alias with quotes is not supported: %s\n"), $_;
557 } elsif (/:include:/) {
558 printf STDERR __
("warning: `:include:` not supported: %s\n"), $_;
560 printf STDERR __
("warning: `/file` or `|pipe` redirection not supported: %s\n"), $_;
561 } elsif (/^(\S+?)\s*:\s*(.+)$/) {
562 my ($alias, $addr) = ($1, $2);
563 $aliases{$alias} = [ split_addrs
($addr) ];
565 printf STDERR __
("warning: sendmail line is not recognized: %s\n"), $_;
569 sub parse_sendmail_aliases
{
574 next if /^\s*$/ || /^\s*#/;
575 $s .= $_, next if $s =~ s/\\$// || s/^\s+//;
576 parse_sendmail_alias
($s) if $s;
579 $s =~ s/\\$//; # silently tolerate stray '\' on last line
580 parse_sendmail_alias
($s) if $s;
584 # multiline formats can be supported in the future
585 mutt
=> sub { my $fh = shift; while (<$fh>) {
586 if (/^\s*alias\s+(?:-group\s+\S+\s+)*(\S+)\s+(.*)$/) {
587 my ($alias, $addr) = ($1, $2);
588 $addr =~ s/#.*$//; # mutt allows # comments
589 # commas delimit multiple addresses
590 my @addr = split_addrs
($addr);
592 # quotes may be escaped in the file,
593 # unescape them so we do not double-escape them later.
594 s/\\"/"/g foreach @addr;
595 $aliases{$alias} = \
@addr
597 mailrc
=> sub { my $fh = shift; while (<$fh>) {
598 if (/^alias\s+(\S+)\s+(.*?)\s*$/) {
599 # spaces delimit multiple addresses
600 $aliases{$1} = [ quotewords
('\s+', 0, $2) ];
602 pine
=> sub { my $fh = shift; my $f='\t[^\t]*';
603 for (my $x = ''; defined($x); $x = $_) {
605 $x .= $1 while(defined($_ = <$fh>) && /^ +(.*)$/);
606 $x =~ /^(\S+)$f\t\(?([^\t]+?)\)?(:?$f){0,2}$/ or next;
607 $aliases{$1} = [ split_addrs
($2) ];
609 elm
=> sub { my $fh = shift;
611 if (/^(\S+)\s+=\s+[^=]+=\s(\S+)/) {
612 my ($alias, $addr) = ($1, $2);
613 $aliases{$alias} = [ split_addrs
($addr) ];
616 sendmail
=> \
&parse_sendmail_aliases
,
617 gnus
=> sub { my $fh = shift; while (<$fh>) {
618 if (/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) {
619 $aliases{$1} = [ $2 ];
621 # Please update _git_config() in git-completion.bash when you
625 if (@alias_files and $aliasfiletype and defined $parse_alias{$aliasfiletype}) {
626 foreach my $file (@alias_files) {
627 open my $fh, '<', $file or die "opening $file: $!\n";
628 $parse_alias{$aliasfiletype}->($fh);
634 print "$_\n" for (sort keys %aliases);
638 # is_format_patch_arg($f) returns 0 if $f names a patch, or 1 if
639 # $f is a revision list specification to be passed to format-patch.
640 sub is_format_patch_arg
{
644 $repo->command('rev-parse', '--verify', '--quiet', $f);
645 if (defined($format_patch)) {
646 return $format_patch;
648 die sprintf(__
<<EOF, $f, $f);
649 File '%s' exists but it could also be the range of commits
650 to produce patches for. Please disambiguate by...
652 * Saying "./%s" if you mean a file; or
653 * Giving --format-patch option if you mean a range.
655 } catch Git
::Error
::Command with
{
656 # Not a valid revision. Treat it as a filename.
661 # Now that all the defaults are set, process the rest of the command line
662 # arguments and collect up the files that need to be processed.
664 while (defined(my $f = shift @ARGV)) {
666 push @rev_list_opts, "--", @ARGV;
668 } elsif (-d
$f and !is_format_patch_arg
($f)) {
670 or die sprintf(__
("Failed to opendir %s: %s"), $f, $!);
672 push @files, grep { -f
$_ } map { catfile
($f, $_) }
675 } elsif ((-f
$f or -p
$f) and !is_format_patch_arg
($f)) {
678 push @rev_list_opts, $f;
682 if (@rev_list_opts) {
683 die __
("Cannot run git format-patch from outside a repository\n")
685 push @files, $repo->command('format-patch', '-o', tempdir
(CLEANUP
=> 1), @rev_list_opts);
688 @files = handle_backup_files
(@files);
691 foreach my $f (@files) {
693 my $error = validate_patch
($f, $target_xfer_encoding);
694 $error and die sprintf(__
("fatal: %s: %s\nwarning: no patches were sent\n"),
702 print $_,"\n" for (@files);
705 print STDERR __
("\nNo patch files specified!\n\n");
709 sub get_patch_subject
{
711 open (my $fh, '<', $fn);
712 while (my $line = <$fh>) {
713 next unless ($line =~ /^Subject: (.*)$/);
718 die sprintf(__
("No subject line in %s?"), $fn);
722 # Note that this does not need to be secure, but we will make a small
723 # effort to have it be unique
724 $compose_filename = ($repo ?
725 tempfile
(".gitsendemail.msg.XXXXXX", DIR
=> $repo->repo_path()) :
726 tempfile
(".gitsendemail.msg.XXXXXX", DIR
=> "."))[1];
727 open my $c, ">", $compose_filename
728 or die sprintf(__
("Failed to open for writing %s: %s"), $compose_filename, $!);
731 my $tpl_sender = $sender || $repoauthor || $repocommitter || '';
732 my $tpl_subject = $initial_subject || '';
733 my $tpl_in_reply_to = $initial_in_reply_to || '';
734 my $tpl_reply_to = $reply_to || '';
736 print $c <<EOT1, Git::prefix_lines("GIT: ", __ <<EOT2), <<EOT3;
737 From $tpl_sender # This line is ignored.
739 Lines beginning in "GIT:" will be removed.
740 Consider including an overall diffstat or table of contents
741 for the patch you are writing.
743 Clear the body content if you don't wish to send a summary.
746 Reply-To: $tpl_reply_to
747 Subject: $tpl_subject
748 In-Reply-To: $tpl_in_reply_to
752 print $c get_patch_subject($f);
757 do_edit($compose_filename, @files);
759 do_edit($compose_filename);
762 open $c, "<", $compose_filename
763 or die sprintf(__("Failed to open %s: %s"), $compose_filename, $!);
765 if (!defined $compose_encoding) {
766 $compose_encoding = "UTF-8";
770 while (my $line = <$c>) {
771 next if $line =~ m/^GIT:/;
772 parse_header_line($line, \%parsed_email);
774 $parsed_email{'body'} = filter_body($c);
779 open my $c2, ">", $compose_filename . ".final"
780 or die sprintf(__("Failed to open %s.final: %s"), $compose_filename, $!);
783 if ($parsed_email{'From'}) {
784 $sender = delete($parsed_email{'From'});
786 if ($parsed_email{'In-Reply-To'}) {
787 $initial_in_reply_to = delete($parsed_email{'In-Reply-To'});
789 if ($parsed_email{'Reply-To'}) {
790 $reply_to = delete($parsed_email{'Reply-To'});
792 if ($parsed_email{'Subject'}) {
793 $initial_subject = delete($parsed_email{'Subject'});
794 print $c2 "Subject: " .
795 quote_subject($initial_subject, $compose_encoding) .
799 if ($parsed_email{'MIME-Version'}) {
800 print $c2 "MIME-Version: $parsed_email{'MIME-Version'}\n",
801 "Content-Type: $parsed_email{'Content-Type'};\n",
802 "Content-Transfer-Encoding: $parsed_email{'Content-Transfer-Encoding'}\n";
803 delete($parsed_email{'MIME-Version'});
804 delete($parsed_email{'Content-Type'});
805 delete($parsed_email{'Content-Transfer-Encoding'});
806 } elsif (file_has_nonascii($compose_filename)) {
807 my $content_type = (delete($parsed_email{'Content-Type'}) or
808 "text/plain; charset=$compose_encoding");
809 print $c2 "MIME-Version: 1.0\n",
810 "Content-Type: $content_type\n",
811 "Content-Transfer-Encoding: 8bit\n";
813 # Preserve unknown headers
814 foreach my $key (keys %parsed_email) {
815 next if $key eq 'body';
816 print $c2 "$key: $parsed_email{$key}";
819 if ($parsed_email{'body'}) {
820 print $c2 "\n$parsed_email{'body'}\n";
821 delete($parsed_email{'body'});
823 print __("Summary email is empty, skipping it\n");
829 } elsif ($annotate) {
834 my ($prompt, %arg) = @_;
835 my $valid_re = $arg{valid_re};
836 my $default = $arg{default};
837 my $confirm_only = $arg{confirm_only};
840 return defined $default ? $default : undef
841 unless defined $term->IN and defined fileno($term->IN) and
842 defined $term->OUT and defined fileno($term->OUT);
844 $resp = $term->readline($prompt);
845 if (!defined $resp) { # EOF
847 return defined $default ? $default : undef;
849 if ($resp eq '' and defined $default) {
852 if (!defined $valid_re or $resp =~ /$valid_re/) {
856 my $yesno = $term->readline(
857 # TRANSLATORS: please keep [y/N] as is.
858 sprintf(__("Are you sure you want to use <%s> [y/N]? "), $resp));
859 if (defined $yesno && $yesno =~ /y/i) {
867 sub parse_header_line {
869 my $parsed_line = shift;
870 my $addr_pat = join "|", qw(To Cc Bcc);
872 foreach (split(/\n/, $lines)) {
873 if (/^($addr_pat):\s*(.+)$/i) {
874 $parsed_line->{$1} = [ parse_address_line
($2) ];
875 } elsif (/^([^:]*):\s*(.+)\s*$/i) {
876 $parsed_line->{$1} = $2;
884 while (my $body_line = <$c>) {
885 if ($body_line !~ m/^GIT:/) {
895 sub file_declares_8bit_cte
{
897 open (my $fh, '<', $fn);
898 while (my $line = <$fh>) {
899 last if ($line =~ /^$/);
900 return 1 if ($line =~ /^Content-Transfer-Encoding: .*8bit.*$/);
906 foreach my $f (@files) {
907 next unless (body_or_subject_has_nonascii
($f)
908 && !file_declares_8bit_cte
($f));
909 $broken_encoding{$f} = 1;
912 if (!defined $auto_8bit_encoding && scalar %broken_encoding) {
913 print __
("The following files are 8bit, but do not declare " .
914 "a Content-Transfer-Encoding.\n");
915 foreach my $f (sort keys %broken_encoding) {
918 $auto_8bit_encoding = ask
(__
("Which 8bit encoding should I declare [UTF-8]? "),
919 valid_re
=> qr/.{4}/, confirm_only
=> 1,
925 if (get_patch_subject
($f) =~ /\Q*** SUBJECT HERE ***\E/) {
926 die sprintf(__
("Refusing to send because the patch\n\t%s\n"
927 . "has the template subject '*** SUBJECT HERE ***'. "
928 . "Pass --force if you really want to send.\n"), $f);
933 if (defined $sender) {
934 $sender =~ s/^\s+|\s+$//g;
935 ($sender) = expand_aliases
($sender);
937 $sender = $repoauthor || $repocommitter || '';
940 # $sender could be an already sanitized address
941 # (e.g. sendemail.from could be manually sanitized by user).
942 # But it's a no-op to run sanitize_address on an already sanitized address.
943 $sender = sanitize_address
($sender);
945 my $to_whom = __
("To whom should the emails be sent (if anyone)?");
947 if (!@initial_to && !defined $to_cmd) {
948 my $to = ask
("$to_whom ",
950 valid_re
=> qr/\@.*\./, confirm_only
=> 1);
951 push @initial_to, parse_address_line
($to) if defined $to; # sanitized/validated later
956 return map { expand_one_alias
($_) } @_;
959 my %EXPANDED_ALIASES;
960 sub expand_one_alias
{
962 if ($EXPANDED_ALIASES{$alias}) {
963 die sprintf(__
("fatal: alias '%s' expands to itself\n"), $alias);
965 local $EXPANDED_ALIASES{$alias} = 1;
966 return $aliases{$alias} ? expand_aliases
(@
{$aliases{$alias}}) : $alias;
969 @initial_to = process_address_list
(@initial_to);
970 @initial_cc = process_address_list
(@initial_cc);
971 @initial_bcc = process_address_list
(@initial_bcc);
973 if ($thread && !defined $initial_in_reply_to && $prompting) {
974 $initial_in_reply_to = ask
(
975 __
("Message-ID to be used as In-Reply-To for the first email (if any)? "),
977 valid_re
=> qr/\@.*\./, confirm_only
=> 1);
979 if (defined $initial_in_reply_to) {
980 $initial_in_reply_to =~ s/^\s*<?//;
981 $initial_in_reply_to =~ s/>?\s*$//;
982 $initial_in_reply_to = "<$initial_in_reply_to>" if $initial_in_reply_to ne '';
985 if (defined $reply_to) {
986 $reply_to =~ s/^\s+|\s+$//g;
987 ($reply_to) = expand_aliases
($reply_to);
988 $reply_to = sanitize_address
($reply_to);
991 if (!defined $smtp_server) {
992 my @sendmail_paths = qw( /usr/sbin/sendmail /usr/lib/sendmail );
993 push @sendmail_paths, map {"$_/sendmail"} split /:/, $ENV{PATH
};
994 foreach (@sendmail_paths) {
1000 $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
1003 if ($compose && $compose > 0) {
1004 @files = ($compose_filename . ".final", @files);
1007 # Variables we set as part of the loop over files
1008 our ($message_id, %mail, $subject, $in_reply_to, $references, $message,
1009 $needs_confirm, $message_num, $ask_default);
1011 sub extract_valid_address
{
1012 my $address = shift;
1013 my $local_part_regexp = qr/[^<>"\s@]+/;
1014 my $domain_regexp = qr/[^.<>"\s@]+(?:\.[^.<>"\s@]+)+/;
1016 # check for a local address:
1017 return $address if ($address =~ /^($local_part_regexp)$/);
1019 $address =~ s/^\s*<(.*)>\s*$/$1/;
1020 if ($have_email_valid) {
1021 return scalar Email
::Valid
->address($address);
1024 # less robust/correct than the monster regexp in Email::Valid,
1025 # but still does a 99% job, and one less dependency
1026 return $1 if $address =~ /($local_part_regexp\@$domain_regexp)/;
1030 sub extract_valid_address_or_die
{
1031 my $address = shift;
1032 $address = extract_valid_address
($address);
1033 die sprintf(__
("error: unable to extract a valid address from: %s\n"), $address)
1038 sub validate_address
{
1039 my $address = shift;
1040 while (!extract_valid_address
($address)) {
1041 printf STDERR __
("error: unable to extract a valid address from: %s\n"), $address;
1042 # TRANSLATORS: Make sure to include [q] [d] [e] in your
1043 # translation. The program will only accept English input
1045 $_ = ask
(__
("What to do with this address? ([q]uit|[d]rop|[e]dit): "),
1046 valid_re
=> qr/^(?:quit|q|drop|d|edit|e)/i,
1051 cleanup_compose_files
();
1054 $address = ask
("$to_whom ",
1056 valid_re
=> qr/\@.*\./, confirm_only
=> 1);
1061 sub validate_address_list
{
1062 return (grep { defined $_ }
1063 map { validate_address
($_) } @_);
1066 # Usually don't need to change anything below here.
1068 # we make a "fake" message id by taking the current number
1069 # of seconds since the beginning of Unix time and tacking on
1070 # a random number to the end, in case we are called quicker than
1071 # 1 second since the last time we were called.
1073 # We'll setup a template for the message id, using the "from" address:
1075 my ($message_id_stamp, $message_id_serial);
1076 sub make_message_id
{
1078 if (!defined $message_id_stamp) {
1079 $message_id_stamp = strftime
("%Y%m%d%H%M%S.$$", gmtime(time));
1080 $message_id_serial = 0;
1082 $message_id_serial++;
1083 $uniq = "$message_id_stamp-$message_id_serial";
1086 for ($sender, $repocommitter, $repoauthor) {
1087 $du_part = extract_valid_address
(sanitize_address
($_));
1088 last if (defined $du_part and $du_part ne '');
1090 if (not defined $du_part or $du_part eq '') {
1091 require Sys
::Hostname
;
1092 $du_part = 'user@' . Sys
::Hostname
::hostname
();
1094 my $message_id_template = "<%s-%s>";
1095 $message_id = sprintf($message_id_template, $uniq, $du_part);
1096 #print "new message id = $message_id\n"; # Was useful for debugging
1101 $time = time - scalar $#files;
1103 sub unquote_rfc2047
{
1106 my $sep = qr/[ \t]+/;
1107 s
{$re_encoded_word(?
:$sep$re_encoded_word)*}{
1108 my @words = split $sep, $&;
1110 m/$re_encoded_word/;
1114 if ($encoding eq 'q' || $encoding eq 'Q') {
1117 s/=([0-9A-F]{2})/chr(hex($1))/egi;
1119 # other encodings not supported yet
1124 return wantarray ?
($_, $charset) : $_;
1129 my $encoding = shift || 'UTF-8';
1130 s/([^-a-zA-Z0-9!*+\/])/sprintf
("=%02X", ord($1))/eg
;
1131 s/(.*)/=\?$encoding\?q\?$1\?=/;
1135 sub is_rfc2047_quoted
{
1138 $s =~ m/^(?:"[[:ascii:]]*"|$re_encoded_word)$/o;
1141 sub subject_needs_rfc2047_quoting
{
1144 return ($s =~ /[^[:ascii:]]/) || ($s =~ /=\?/);
1148 local $subject = shift;
1149 my $encoding = shift || 'UTF-8';
1151 if (subject_needs_rfc2047_quoting
($subject)) {
1152 return quote_rfc2047
($subject, $encoding);
1157 # use the simplest quoting being able to handle the recipient
1158 sub sanitize_address
{
1159 my ($recipient) = @_;
1161 # remove garbage after email address
1162 $recipient =~ s/(.*>).*$/$1/;
1164 my ($recipient_name, $recipient_addr) = ($recipient =~ /^(.*?)\s*(<.*)/);
1166 if (not $recipient_name) {
1170 # if recipient_name is already quoted, do nothing
1171 if (is_rfc2047_quoted
($recipient_name)) {
1175 # remove non-escaped quotes
1176 $recipient_name =~ s/(^|[^\\])"/$1/g;
1178 # rfc2047 is needed if a non-ascii char is included
1179 if ($recipient_name =~ /[^[:ascii:]]/) {
1180 $recipient_name = quote_rfc2047
($recipient_name);
1183 # double quotes are needed if specials or CTLs are included
1184 elsif ($recipient_name =~ /[][()<>@,;:\\".\000-\037\177]/) {
1185 $recipient_name =~ s/([\\\r])/\\$1/g;
1186 $recipient_name = qq["$recipient_name"];
1189 return "$recipient_name $recipient_addr";
1193 sub strip_garbage_one_address
{
1196 if ($addr =~ /^(("[^"]*"|[^"<]*)? *<[^>]*>).*/) {
1197 # "Foo Bar" <foobar@example.com> [possibly garbage here]
1198 # Foo Bar <foobar@example.com> [possibly garbage here]
1201 if ($addr =~ /^(<[^>]*>).*/) {
1202 # <foo@example.com> [possibly garbage here]
1203 # if garbage contains other addresses, they are ignored.
1206 if ($addr =~ /^([^"#,\s]*)/) {
1207 # address without quoting: remove anything after the address
1213 sub sanitize_address_list
{
1214 return (map { sanitize_address
($_) } @_);
1217 sub process_address_list
{
1218 my @addr_list = map { parse_address_line
($_) } @_;
1219 @addr_list = expand_aliases
(@addr_list);
1220 @addr_list = sanitize_address_list
(@addr_list);
1221 @addr_list = validate_address_list
(@addr_list);
1225 # Returns the local Fully Qualified Domain Name (FQDN) if available.
1227 # Tightly configured MTAa require that a caller sends a real DNS
1228 # domain name that corresponds the IP address in the HELO/EHLO
1229 # handshake. This is used to verify the connection and prevent
1230 # spammers from trying to hide their identity. If the DNS and IP don't
1231 # match, the receiving MTA may deny the connection.
1233 # Here is a deny example of Net::SMTP with the default "localhost.localdomain"
1235 # Net::SMTP=GLOB(0x267ec28)>>> EHLO localhost.localdomain
1236 # Net::SMTP=GLOB(0x267ec28)<<< 550 EHLO argument does not match calling host
1238 # This maildomain*() code is based on ideas in Perl library Test::Reporter
1239 # /usr/share/perl5/Test/Reporter/Mail/Util.pm ==> sub _maildomain ()
1243 return defined $domain && !($^O
eq 'darwin' && $domain =~ /\.local$/) && $domain =~ /\./;
1246 sub maildomain_net
{
1249 my $domain = Net
::Domain
::domainname
();
1250 $maildomain = $domain if valid_fqdn
($domain);
1255 sub maildomain_mta
{
1258 for my $host (qw(mailhost localhost)) {
1259 my $smtp = Net
::SMTP
->new($host);
1260 if (defined $smtp) {
1261 my $domain = $smtp->domain;
1264 $maildomain = $domain if valid_fqdn
($domain);
1266 last if $maildomain;
1274 return maildomain_net
() || maildomain_mta
() || 'localhost.localdomain';
1277 sub smtp_host_string
{
1278 if (defined $smtp_server_port) {
1279 return "$smtp_server:$smtp_server_port";
1281 return $smtp_server;
1285 # Returns 1 if authentication succeeded or was not necessary
1286 # (smtp_user was not specified), and 0 otherwise.
1288 sub smtp_auth_maybe
{
1289 if (!defined $smtp_authuser || $auth || (defined $smtp_auth && $smtp_auth eq "none")) {
1293 # Workaround AUTH PLAIN/LOGIN interaction defect
1294 # with Authen::SASL::Cyrus
1296 require Authen
::SASL
;
1297 Authen
::SASL
->import(qw(Perl));
1300 # Check mechanism naming as defined in:
1301 # https://tools.ietf.org/html/rfc4422#page-8
1302 if ($smtp_auth && $smtp_auth !~ /^(\b[A-Z0-9-_]{1,20}\s*)*$/) {
1303 die "invalid smtp auth: '${smtp_auth}'";
1306 # TODO: Authentication may fail not because credentials were
1307 # invalid but due to other reasons, in which we should not
1308 # reject credentials.
1309 $auth = Git
::credential
({
1310 'protocol' => 'smtp',
1311 'host' => smtp_host_string
(),
1312 'username' => $smtp_authuser,
1313 # if there's no password, "git credential fill" will
1314 # give us one, otherwise it'll just pass this one.
1315 'password' => $smtp_authpass
1320 my $sasl = Authen
::SASL
->new(
1321 mechanism
=> $smtp_auth,
1323 user
=> $cred->{'username'},
1324 pass
=> $cred->{'password'},
1325 authname
=> $cred->{'username'},
1329 return !!$smtp->auth($sasl);
1332 return !!$smtp->auth($cred->{'username'}, $cred->{'password'});
1338 sub ssl_verify_params
{
1340 require IO
::Socket
::SSL
;
1341 IO
::Socket
::SSL
->import(qw
/SSL_VERIFY_PEER SSL_VERIFY_NONE/);
1344 print STDERR
"Not using SSL_VERIFY_PEER due to out-of-date IO::Socket::SSL.\n";
1348 if (!defined $smtp_ssl_cert_path) {
1349 # use the OpenSSL defaults
1350 return (SSL_verify_mode
=> SSL_VERIFY_PEER
());
1353 if ($smtp_ssl_cert_path eq "") {
1354 return (SSL_verify_mode
=> SSL_VERIFY_NONE
());
1355 } elsif (-d
$smtp_ssl_cert_path) {
1356 return (SSL_verify_mode
=> SSL_VERIFY_PEER
(),
1357 SSL_ca_path
=> $smtp_ssl_cert_path);
1358 } elsif (-f
$smtp_ssl_cert_path) {
1359 return (SSL_verify_mode
=> SSL_VERIFY_PEER
(),
1360 SSL_ca_file
=> $smtp_ssl_cert_path);
1362 die sprintf(__
("CA path \"%s\" does not exist"), $smtp_ssl_cert_path);
1366 sub file_name_is_absolute
{
1369 # msys does not grok DOS drive-prefixes
1370 if ($^O
eq 'msys') {
1371 return ($path =~ m
#^/# || $path =~ m#^[a-zA-Z]\:#)
1374 require File
::Spec
::Functions
;
1375 return File
::Spec
::Functions
::file_name_is_absolute
($path);
1378 # Prepares the email, then asks the user what to do.
1380 # If the user chooses to send the email, it's sent and 1 is returned.
1381 # If the user chooses not to send the email, 0 is returned.
1382 # If the user decides they want to make further edits, -1 is returned and the
1383 # caller is expected to call send_message again after the edits are performed.
1385 # If an error occurs sending the email, this just dies.
1388 my @recipients = unique_email_list
(@to);
1389 @cc = (grep { my $cc = extract_valid_address_or_die
($_);
1390 not grep { $cc eq $_ || $_ =~ /<\Q${cc}\E>$/ } @recipients
1393 my $to = join (",\n\t", @recipients);
1394 @recipients = unique_email_list
(@recipients,@cc,@initial_bcc);
1395 @recipients = (map { extract_valid_address_or_die
($_) } @recipients);
1396 my $date = format_2822_time
($time++);
1397 my $gitversion = '@@GIT_VERSION@@';
1398 if ($gitversion =~ m/..GIT_VERSION../) {
1399 $gitversion = Git
::version
();
1402 my $cc = join(",\n\t", unique_email_list
(@cc));
1405 $ccline = "\nCc: $cc";
1407 make_message_id
() unless defined($message_id);
1409 my $header = "From: $sender
1413 Message-Id: $message_id
1416 $header .= "X-Mailer: git-send-email $gitversion\n";
1420 $header .= "In-Reply-To: $in_reply_to\n";
1421 $header .= "References: $references\n";
1424 $header .= "Reply-To: $reply_to\n";
1427 $header .= join("\n", @xh) . "\n";
1430 my @sendmail_parameters = ('-i', @recipients);
1431 my $raw_from = $sender;
1432 if (defined $envelope_sender && $envelope_sender ne "auto") {
1433 $raw_from = $envelope_sender;
1435 $raw_from = extract_valid_address
($raw_from);
1436 unshift (@sendmail_parameters,
1437 '-f', $raw_from) if(defined $envelope_sender);
1439 if ($needs_confirm && !$dry_run) {
1440 print "\n$header\n";
1441 if ($needs_confirm eq "inform") {
1442 $confirm_unconfigured = 0; # squelch this message for the rest of this run
1443 $ask_default = "y"; # assume yes on EOF since user hasn't explicitly asked for confirmation
1445 The Cc list above has been expanded by additional
1446 addresses found in the patch commit message. By default
1447 send-email prompts before sending whenever this occurs.
1448 This behavior is controlled by the sendemail.confirm
1449 configuration setting.
1451 For additional information, run 'git send-email --help'.
1452 To retain the current behavior, but squelch this message,
1453 run 'git config --global sendemail.confirm auto'.
1457 # TRANSLATORS: Make sure to include [y] [n] [e] [q] [a] in your
1458 # translation. The program will only accept English input
1460 $_ = ask
(__
("Send this email? ([y]es|[n]o|[e]dit|[q]uit|[a]ll): "),
1461 valid_re
=> qr/^(?:yes|y|no|n|edit|e|quit|q|all|a)/i,
1462 default => $ask_default);
1463 die __
("Send this email reply required") unless defined $_;
1469 cleanup_compose_files
();
1476 unshift (@sendmail_parameters, @smtp_server_options);
1479 # We don't want to send the email.
1480 } elsif (file_name_is_absolute
($smtp_server)) {
1481 my $pid = open my $sm, '|-';
1482 defined $pid or die $!;
1484 exec($smtp_server, @sendmail_parameters) or die $!;
1486 print $sm "$header\n$message";
1487 close $sm or die $!;
1490 if (!defined $smtp_server) {
1491 die __
("The required SMTP server is not properly defined.")
1495 my $use_net_smtp_ssl = version
->parse($Net::SMTP
::VERSION
) < version
->parse("2.34");
1496 $smtp_domain ||= maildomain
();
1498 if ($smtp_encryption eq 'ssl') {
1499 $smtp_server_port ||= 465; # ssmtp
1500 require IO
::Socket
::SSL
;
1502 # Suppress "variable accessed once" warning.
1505 $IO::Socket
::SSL
::DEBUG
= 1;
1508 # Net::SMTP::SSL->new() does not forward any SSL options
1509 IO
::Socket
::SSL
::set_client_defaults
(
1510 ssl_verify_params
());
1512 if ($use_net_smtp_ssl) {
1513 require Net
::SMTP
::SSL
;
1514 $smtp ||= Net
::SMTP
::SSL
->new($smtp_server,
1515 Hello
=> $smtp_domain,
1516 Port
=> $smtp_server_port,
1517 Debug
=> $debug_net_smtp);
1520 $smtp ||= Net
::SMTP
->new($smtp_server,
1521 Hello
=> $smtp_domain,
1522 Port
=> $smtp_server_port,
1523 Debug
=> $debug_net_smtp,
1528 $smtp_server_port ||= 25;
1529 $smtp ||= Net
::SMTP
->new($smtp_server,
1530 Hello
=> $smtp_domain,
1531 Debug
=> $debug_net_smtp,
1532 Port
=> $smtp_server_port);
1533 if ($smtp_encryption eq 'tls' && $smtp) {
1534 if ($use_net_smtp_ssl) {
1535 $smtp->command('STARTTLS');
1537 if ($smtp->code != 220) {
1538 die sprintf(__
("Server does not support STARTTLS! %s"), $smtp->message);
1540 require Net
::SMTP
::SSL
;
1541 $smtp = Net
::SMTP
::SSL
->start_SSL($smtp,
1542 ssl_verify_params
())
1543 or die sprintf(__
("STARTTLS failed! %s"), IO
::Socket
::SSL
::errstr
());
1546 $smtp->starttls(ssl_verify_params
())
1547 or die sprintf(__
("STARTTLS failed! %s"), IO
::Socket
::SSL
::errstr
());
1549 # Send EHLO again to receive fresh
1550 # supported commands
1551 $smtp->hello($smtp_domain);
1556 die __
("Unable to initialize SMTP properly. Check config and use --smtp-debug."),
1557 " VALUES: server=$smtp_server ",
1558 "encryption=$smtp_encryption ",
1559 "hello=$smtp_domain",
1560 defined $smtp_server_port ?
" port=$smtp_server_port" : "";
1563 smtp_auth_maybe
or die $smtp->message;
1565 $smtp->mail( $raw_from ) or die $smtp->message;
1566 $smtp->to( @recipients ) or die $smtp->message;
1567 $smtp->data or die $smtp->message;
1568 $smtp->datasend("$header\n") or die $smtp->message;
1569 my @lines = split /^/, $message;
1570 foreach my $line (@lines) {
1571 $smtp->datasend("$line") or die $smtp->message;
1573 $smtp->dataend() or die $smtp->message;
1574 $smtp->code =~ /250|200/ or die sprintf(__
("Failed to send %s\n"), $subject).$smtp->message;
1577 printf($dry_run ? __
("Dry-Sent %s\n") : __
("Sent %s\n"), $subject);
1579 print($dry_run ? __
("Dry-OK. Log says:\n") : __
("OK. Log says:\n"));
1580 if (!file_name_is_absolute
($smtp_server)) {
1581 print "Server: $smtp_server\n";
1582 print "MAIL FROM:<$raw_from>\n";
1583 foreach my $entry (@recipients) {
1584 print "RCPT TO:<$entry>\n";
1587 print "Sendmail: $smtp_server ".join(' ',@sendmail_parameters)."\n";
1589 print $header, "\n";
1591 print __
("Result: "), $smtp->code, ' ',
1592 ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
1594 print __
("Result: OK\n");
1601 $in_reply_to = $initial_in_reply_to;
1602 $references = $initial_in_reply_to || '';
1603 $subject = $initial_subject;
1606 # Prepares the email, prompts the user, sends it out
1607 # Returns 0 if an edit was done and the function should be called again, or 1
1612 open my $fh, "<", $t or die sprintf(__
("can't open file %s"), $t);
1615 my $sauthor = undef;
1616 my $author_encoding;
1617 my $has_content_type;
1620 my $has_mime_version;
1624 my $input_format = undef;
1628 # First unfold multiline header fields
1631 if (/^\s+\S/ and @header) {
1632 chomp($header[$#header]);
1634 $header[$#header] .= $_;
1639 # Now parse the header
1642 $input_format = 'mbox';
1646 if (!defined $input_format && /^[-A-Za-z]+:\s/) {
1647 $input_format = 'mbox';
1650 if (defined $input_format && $input_format eq 'mbox') {
1651 if (/^Subject:\s+(.*)$/i) {
1654 elsif (/^From:\s+(.*)$/i) {
1655 ($author, $author_encoding) = unquote_rfc2047
($1);
1656 $sauthor = sanitize_address
($author);
1657 next if $suppress_cc{'author'};
1658 next if $suppress_cc{'self'} and $sauthor eq $sender;
1659 printf(__
("(mbox) Adding cc: %s from line '%s'\n"),
1660 $1, $_) unless $quiet;
1663 elsif (/^To:\s+(.*)$/i) {
1664 foreach my $addr (parse_address_line
($1)) {
1665 printf(__
("(mbox) Adding to: %s from line '%s'\n"),
1666 $addr, $_) unless $quiet;
1670 elsif (/^Cc:\s+(.*)$/i) {
1671 foreach my $addr (parse_address_line
($1)) {
1672 my $qaddr = unquote_rfc2047
($addr);
1673 my $saddr = sanitize_address
($qaddr);
1674 if ($saddr eq $sender) {
1675 next if ($suppress_cc{'self'});
1677 next if ($suppress_cc{'cc'});
1679 printf(__
("(mbox) Adding cc: %s from line '%s'\n"),
1680 $addr, $_) unless $quiet;
1684 elsif (/^Content-type:/i) {
1685 $has_content_type = 1;
1686 if (/charset="?([^ "]+)/) {
1687 $body_encoding = $1;
1691 elsif (/^MIME-Version/i) {
1692 $has_mime_version = 1;
1695 elsif (/^Message-Id: (.*)/i) {
1698 elsif (/^Content-Transfer-Encoding: (.*)/i) {
1699 $xfer_encoding = $1 if not defined $xfer_encoding;
1701 elsif (/^In-Reply-To: (.*)/i) {
1702 if (!$initial_in_reply_to || $thread) {
1706 elsif (/^References: (.*)/i) {
1707 if (!$initial_in_reply_to || $thread) {
1711 elsif (!/^Date:\s/i && /^[-A-Za-z]+:\s+\S/) {
1715 # In the traditional
1716 # "send lots of email" format,
1719 # So let's support that, too.
1720 $input_format = 'lots';
1721 if (@cc == 0 && !$suppress_cc{'cc'}) {
1722 printf(__
("(non-mbox) Adding cc: %s from line '%s'\n"),
1723 $_, $_) unless $quiet;
1725 } elsif (!defined $subject) {
1730 # Now parse the message body
1733 if (/^([a-z][a-z-]*-by|Cc): (.*)/i) {
1735 my ($what, $c) = ($1, $2);
1736 # strip garbage for the address we'll use:
1737 $c = strip_garbage_one_address
($c);
1738 # sanitize a bit more to decide whether to suppress the address:
1739 my $sc = sanitize_address
($c);
1740 if ($sc eq $sender) {
1741 next if ($suppress_cc{'self'});
1743 if ($what =~ /^Signed-off-by$/i) {
1744 next if $suppress_cc{'sob'};
1745 } elsif ($what =~ /-by$/i) {
1746 next if $suppress_cc{'misc-by'};
1747 } elsif ($what =~ /Cc/i) {
1748 next if $suppress_cc{'bodycc'};
1751 if ($c !~ /.+@.+|<.+>/) {
1752 printf("(body) Ignoring %s from line '%s'\n",
1753 $what, $_) unless $quiet;
1757 printf(__
("(body) Adding cc: %s from line '%s'\n"),
1758 $c, $_) unless $quiet;
1763 push @to, recipients_cmd
("to-cmd", "to", $to_cmd, $t)
1765 push @cc, recipients_cmd
("cc-cmd", "cc", $cc_cmd, $t)
1766 if defined $cc_cmd && !$suppress_cc{'cccmd'};
1768 if ($broken_encoding{$t} && !$has_content_type) {
1769 $xfer_encoding = '8bit' if not defined $xfer_encoding;
1770 $has_content_type = 1;
1771 push @xh, "Content-Type: text/plain; charset=$auto_8bit_encoding";
1772 $body_encoding = $auto_8bit_encoding;
1775 if ($broken_encoding{$t} && !is_rfc2047_quoted
($subject)) {
1776 $subject = quote_subject
($subject, $auto_8bit_encoding);
1779 if (defined $sauthor and $sauthor ne $sender) {
1780 $message = "From: $author\n\n$message";
1781 if (defined $author_encoding) {
1782 if ($has_content_type) {
1783 if ($body_encoding eq $author_encoding) {
1784 # ok, we already have the right encoding
1787 # uh oh, we should re-encode
1791 $xfer_encoding = '8bit' if not defined $xfer_encoding;
1792 $has_content_type = 1;
1794 "Content-Type: text/plain; charset=$author_encoding";
1798 $xfer_encoding = '8bit' if not defined $xfer_encoding;
1799 ($message, $xfer_encoding) = apply_transfer_encoding
(
1800 $message, $xfer_encoding, $target_xfer_encoding);
1801 push @xh, "Content-Transfer-Encoding: $xfer_encoding";
1802 unshift @xh, 'MIME-Version: 1.0' unless $has_mime_version;
1805 $confirm eq "always" or
1806 ($confirm =~ /^(?:auto|cc)$/ && @cc) or
1807 ($confirm =~ /^(?:auto|compose)$/ && $compose && $message_num == 1));
1808 $needs_confirm = "inform" if ($needs_confirm && $confirm_unconfigured && @cc);
1810 @to = process_address_list
(@to);
1811 @cc = process_address_list
(@cc);
1813 @to = (@initial_to, @to);
1814 @cc = (@initial_cc, @cc);
1816 if ($message_num == 1) {
1817 if (defined $cover_cc and $cover_cc) {
1820 if (defined $cover_to and $cover_to) {
1825 my $message_was_sent = send_message
();
1826 if ($message_was_sent == -1) {
1831 # set up for the next message
1832 if ($thread && $message_was_sent &&
1833 ($chain_reply_to || !defined $in_reply_to || length($in_reply_to) == 0 ||
1834 $message_num == 1)) {
1835 $in_reply_to = $message_id;
1836 if (length $references > 0) {
1837 $references .= "\n $message_id";
1839 $references = "$message_id";
1842 $message_id = undef;
1844 if (defined $batch_size && $num_sent == $batch_size) {
1846 $smtp->quit if defined $smtp;
1849 sleep($relogin_delay) if defined $relogin_delay;
1855 foreach my $t (@files) {
1856 while (!process_file
($t)) {
1857 # user edited the file
1861 # Execute a command (e.g. $to_cmd) to get a list of email addresses
1862 # and return a results array
1863 sub recipients_cmd
{
1864 my ($prefix, $what, $cmd, $file) = @_;
1867 open my $fh, "-|", "$cmd \Q$file\E"
1868 or die sprintf(__
("(%s) Could not execute '%s'"), $prefix, $cmd);
1869 while (my $address = <$fh>) {
1870 $address =~ s/^\s*//g;
1871 $address =~ s/\s*$//g;
1872 $address = sanitize_address
($address);
1873 next if ($address eq $sender and $suppress_cc{'self'});
1874 push @addresses, $address;
1875 printf(__
("(%s) Adding %s: %s from: '%s'\n"),
1876 $prefix, $what, $address, $cmd) unless $quiet;
1879 or die sprintf(__
("(%s) failed to close pipe to '%s'"), $prefix, $cmd);
1883 cleanup_compose_files
();
1885 sub cleanup_compose_files
{
1886 unlink($compose_filename, $compose_filename . ".final") if $compose;
1889 $smtp->quit if $smtp;
1891 sub apply_transfer_encoding
{
1892 my $message = shift;
1896 return ($message, $to) if ($from eq $to and $from ne '7bit');
1898 require MIME
::QuotedPrint
;
1899 require MIME
::Base64
;
1901 $message = MIME
::QuotedPrint
::decode
($message)
1902 if ($from eq 'quoted-printable');
1903 $message = MIME
::Base64
::decode
($message)
1904 if ($from eq 'base64');
1906 $to = ($message =~ /(?:.{999,}|\r)/) ?
'quoted-printable' : '8bit'
1909 die __
("cannot send message as 7bit")
1910 if ($to eq '7bit' and $message =~ /[^[:ascii:]]/);
1911 return ($message, $to)
1912 if ($to eq '7bit' or $to eq '8bit');
1913 return (MIME
::QuotedPrint
::encode
($message, "\n", 0), $to)
1914 if ($to eq 'quoted-printable');
1915 return (MIME
::Base64
::encode
($message, "\n"), $to)
1916 if ($to eq 'base64');
1917 die __
("invalid transfer encoding");
1920 sub unique_email_list
{
1924 foreach my $entry (@_) {
1925 my $clean = extract_valid_address_or_die
($entry);
1926 $seen{$clean} ||= 0;
1927 next if $seen{$clean}++;
1928 push @emails, $entry;
1933 sub validate_patch
{
1934 my ($fn, $xfer_encoding) = @_;
1937 my $validate_hook = catfile
(catdir
($repo->repo_path(), 'hooks'),
1938 'sendemail-validate');
1940 if (-x
$validate_hook) {
1941 my $target = abs_path
($fn);
1942 # The hook needs a correct cwd and GIT_DIR.
1943 my $cwd_save = cwd
();
1944 chdir($repo->wc_path() or $repo->repo_path())
1945 or die("chdir: $!");
1946 local $ENV{"GIT_DIR"} = $repo->repo_path();
1947 $hook_error = "rejected by sendemail-validate hook"
1948 if system($validate_hook, $target);
1949 chdir($cwd_save) or die("chdir: $!");
1951 return $hook_error if $hook_error;
1954 # Any long lines will be automatically fixed if we use a suitable transfer
1956 unless ($xfer_encoding =~ /^(?:auto|quoted-printable|base64)$/) {
1957 open(my $fh, '<', $fn)
1958 or die sprintf(__
("unable to open %s: %s\n"), $fn, $!);
1959 while (my $line = <$fh>) {
1960 if (length($line) > 998) {
1961 return sprintf(__
("%s: patch contains a line longer than 998 characters"), $.);
1969 my ($last, $lastlen, $file, $known_suffix) = @_;
1970 my ($suffix, $skip);
1973 if (defined $last &&
1974 ($lastlen < length($file)) &&
1975 (substr($file, 0, $lastlen) eq $last) &&
1976 ($suffix = substr($file, $lastlen)) !~ /^[a-z0-9]/i) {
1977 if (defined $known_suffix && $suffix eq $known_suffix) {
1978 printf(__
("Skipping %s with backup suffix '%s'.\n"), $file, $known_suffix);
1981 # TRANSLATORS: please keep "[y|N]" as is.
1982 my $answer = ask
(sprintf(__
("Do you really want to send %s? [y|N]: "), $file),
1983 valid_re
=> qr/^(?:y|n)/i,
1985 $skip = ($answer ne 'y');
1987 $known_suffix = $suffix;
1991 return ($skip, $known_suffix);
1994 sub handle_backup_files
{
1996 my ($last, $lastlen, $known_suffix, $skip, @result);
1997 for my $file (@file) {
1998 ($skip, $known_suffix) = handle_backup
($last, $lastlen,
1999 $file, $known_suffix);
2000 push @result, $file unless $skip;
2002 $lastlen = length($file);
2007 sub file_has_nonascii
{
2009 open(my $fh, '<', $fn)
2010 or die sprintf(__
("unable to open %s: %s\n"), $fn, $!);
2011 while (my $line = <$fh>) {
2012 return 1 if $line =~ /[^[:ascii:]]/;
2017 sub body_or_subject_has_nonascii
{
2019 open(my $fh, '<', $fn)
2020 or die sprintf(__
("unable to open %s: %s\n"), $fn, $!);
2021 while (my $line = <$fh>) {
2022 last if $line =~ /^$/;
2023 return 1 if $line =~ /^Subject.*[^[:ascii:]]/;
2025 while (my $line = <$fh>) {
2026 return 1 if $line =~ /[^[:ascii:]]/;