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.
26 use File
::Temp qw
/ tempdir tempfile /;
30 Getopt
::Long
::Configure qw
/ pass_through /;
34 my ($class, $reason) = @_;
35 return bless \
$reason, shift;
39 die "Cannot use readline on FakeTerm: $$self";
46 git send-email [options] <file | directory | rev-list options >
49 --from <str> * Email From:
50 --[no-]to <str> * Email To:
51 --[no-]cc <str> * Email Cc:
52 --[no-]bcc <str> * Email Bcc:
53 --subject <str> * Email "Subject:"
54 --in-reply-to <str> * Email "In-Reply-To:"
55 --annotate * Review each patch that will be sent in an editor.
56 --compose * Open an editor for introduction.
59 --envelope-sender <str> * Email envelope sender.
60 --smtp-server <str:int> * Outgoing SMTP server to use. The port
61 is optional. Default 'localhost'.
62 --smtp-server-port <int> * Outgoing SMTP server port.
63 --smtp-user <str> * Username for SMTP-AUTH.
64 --smtp-pass <str> * Password for SMTP-AUTH; not necessary.
65 --smtp-encryption <str> * tls or ssl; anything else disables.
66 --smtp-ssl * Deprecated. Use '--smtp-encryption ssl'.
67 --smtp-domain <str> * The domain name sent to HELO/EHLO handshake
68 --smtp-debug <0|1> * Disable, enable Net::SMTP debug.
71 --identity <str> * Use the sendemail.<id> options.
72 --cc-cmd <str> * Email Cc: via `<str> \$patch_path`
73 --suppress-cc <str> * author, self, sob, cc, cccmd, body, bodycc, all.
74 --[no-]signed-off-by-cc * Send to Signed-off-by: addresses. Default on.
75 --[no-]suppress-from * Send to self. Default off.
76 --[no-]chain-reply-to * Chain In-Reply-To: fields. Default off.
77 --[no-]thread * Use In-Reply-To: field. Default on.
80 --confirm <str> * Confirm recipients before sending;
81 auto, cc, compose, always, or never.
82 --quiet * Output one line of info per email.
83 --dry-run * Don't actually send the emails.
84 --[no-]validate * Perform patch sanity checks. Default on.
85 --[no-]format-patch * understand any non optional arguments as
86 `git format-patch` ones.
92 # most mail servers generate the Date: header, but not all...
93 sub format_2822_time
{
95 my @localtm = localtime($time);
96 my @gmttm = gmtime($time);
97 my $localmin = $localtm[1] + $localtm[2] * 60;
98 my $gmtmin = $gmttm[1] + $gmttm[2] * 60;
99 if ($localtm[0] != $gmttm[0]) {
100 die "local zone differs from GMT by a non-minute interval\n";
102 if ((($gmttm[6] + 1) % 7) == $localtm[6]) {
104 } elsif ((($gmttm[6] - 1) % 7) == $localtm[6]) {
106 } elsif ($gmttm[6] != $localtm[6]) {
107 die "local time offset greater than or equal to 24 hours\n";
109 my $offset = $localmin - $gmtmin;
110 my $offhour = $offset / 60;
111 my $offmin = abs($offset % 60);
112 if (abs($offhour) >= 24) {
113 die ("local time offset greater than or equal to 24 hours\n");
116 return sprintf("%s, %2d %s %d %02d:%02d:%02d %s%02d%02d",
117 qw(Sun Mon Tue Wed Thu Fri Sat)[$localtm[6]],
119 qw(Jan Feb Mar Apr May Jun
120 Jul Aug Sep Oct Nov Dec)[$localtm[4]],
125 ($offset >= 0) ?
'+' : '-',
131 my $have_email_valid = eval { require Email
::Valid
; 1 };
132 my $have_mail_address = eval { require Mail
::Address
; 1 };
135 my $mail_domain_default = "localhost.localdomain";
138 sub unique_email_list
(@
);
139 sub cleanup_compose_files
();
141 # Variables we fill in automatically, or via prompting:
142 my (@to,$no_to,@cc,$no_cc,@initial_cc,@bcclist,$no_bcc,@xh,
143 $initial_reply_to,$initial_subject,@files,
144 $author,$sender,$smtp_authpass,$annotate,$compose,$time);
149 #$initial_reply_to = ''; #<20050203173208.GA23964@foobar.com>';
151 my $repo = eval { Git
->repository() };
152 my @repo = $repo ?
($repo) : ();
154 $ENV{"GIT_SEND_EMAIL_NOTTY"}
155 ? new Term
::ReadLine
'git-send-email', \
*STDIN
, \
*STDOUT
156 : new Term
::ReadLine
'git-send-email';
159 $term = new FakeTerm
"$@: going non-interactive";
162 # Behavior modification variables
163 my ($quiet, $dry_run) = (0, 0);
165 my $compose_filename;
167 # Handle interactive edition of files.
169 my $editor = Git
::command_oneline
('var', 'GIT_EDITOR');
172 if (defined($multiedit) && !$multiedit) {
174 system('sh', '-c', $editor.' "$@"', $editor, $_);
175 if (($?
& 127) || ($?
>> 8)) {
176 die("the editor exited uncleanly, aborting everything");
180 system('sh', '-c', $editor.' "$@"', $editor, @_);
181 if (($?
& 127) || ($?
>> 8)) {
182 die("the editor exited uncleanly, aborting everything");
187 # Variables with corresponding config settings
188 my ($thread, $chain_reply_to, $suppress_from, $signed_off_by_cc, $cc_cmd);
189 my ($smtp_server, $smtp_server_port, $smtp_authuser, $smtp_encryption);
190 my ($identity, $aliasfiletype, @alias_files, @smtp_host_parts);
191 my ($validate, $confirm);
194 my ($debug_net_smtp) = 0; # Net::SMTP, see send_message()
196 my $not_set_by_user = "true but not set by the user";
198 my %config_bool_settings = (
199 "thread" => [\
$thread, 1],
200 "chainreplyto" => [\
$chain_reply_to, $not_set_by_user],
201 "suppressfrom" => [\
$suppress_from, undef],
202 "signedoffbycc" => [\
$signed_off_by_cc, undef],
203 "signedoffcc" => [\
$signed_off_by_cc, undef], # Deprecated
204 "validate" => [\
$validate, 1],
207 my %config_settings = (
208 "smtpserver" => \
$smtp_server,
209 "smtpserverport" => \
$smtp_server_port,
210 "smtpuser" => \
$smtp_authuser,
211 "smtppass" => \
$smtp_authpass,
213 "cc" => \
@initial_cc,
215 "aliasfiletype" => \
$aliasfiletype,
217 "aliasesfile" => \
@alias_files,
218 "suppresscc" => \
@suppress_cc,
219 "envelopesender" => \
$envelope_sender,
220 "multiedit" => \
$multiedit,
221 "confirm" => \
$confirm,
225 # Help users prepare for 1.7.0
227 if (defined $chain_reply_to &&
228 $chain_reply_to eq $not_set_by_user) {
230 "In git 1.7.0, the default has changed to --no-chain-reply-to\n" .
231 "Set sendemail.chainreplyto configuration variable to true if\n" .
232 "you want to keep --chain-reply-to as your default.\n";
235 return $chain_reply_to;
238 # Handle Uncouth Termination
242 print color
("reset"), "\n";
244 # SMTP password masked
247 # tmp files from --compose
248 if (defined $compose_filename) {
249 if (-e
$compose_filename) {
250 print "'$compose_filename' contains an intermediate version of the email you were composing.\n";
252 if (-e
($compose_filename . ".final")) {
253 print "'$compose_filename.final' contains the composed email.\n"
260 $SIG{TERM
} = \
&signal_handler
;
261 $SIG{INT
} = \
&signal_handler
;
263 # Begin by accumulating all the variables (defined above), that we will end up
264 # needing, first, from the command line:
266 my $rc = GetOptions
("sender|from=s" => \
$sender,
267 "in-reply-to=s" => \
$initial_reply_to,
268 "subject=s" => \
$initial_subject,
271 "cc=s" => \
@initial_cc,
273 "bcc=s" => \
@bcclist,
274 "no-bcc" => \
$no_bcc,
275 "chain-reply-to!" => \
$chain_reply_to,
276 "smtp-server=s" => \
$smtp_server,
277 "smtp-server-port=s" => \
$smtp_server_port,
278 "smtp-user=s" => \
$smtp_authuser,
279 "smtp-pass:s" => \
$smtp_authpass,
280 "smtp-ssl" => sub { $smtp_encryption = 'ssl' },
281 "smtp-encryption=s" => \
$smtp_encryption,
282 "smtp-debug:i" => \
$debug_net_smtp,
283 "smtp-domain:s" => \
$mail_domain,
284 "identity=s" => \
$identity,
285 "annotate" => \
$annotate,
286 "compose" => \
$compose,
288 "cc-cmd=s" => \
$cc_cmd,
289 "suppress-from!" => \
$suppress_from,
290 "suppress-cc=s" => \
@suppress_cc,
291 "signed-off-cc|signed-off-by-cc!" => \
$signed_off_by_cc,
292 "confirm=s" => \
$confirm,
293 "dry-run" => \
$dry_run,
294 "envelope-sender=s" => \
$envelope_sender,
295 "thread!" => \
$thread,
296 "validate!" => \
$validate,
297 "format-patch!" => \
$format_patch,
304 die "Cannot run git format-patch from outside a repository\n"
305 if $format_patch and not $repo;
307 # Now, let's fill any that aren't set in with defaults:
312 foreach my $setting (keys %config_bool_settings) {
313 my $target = $config_bool_settings{$setting}->[0];
314 $$target = Git
::config_bool
(@repo, "$prefix.$setting") unless (defined $$target);
317 foreach my $setting (keys %config_settings) {
318 my $target = $config_settings{$setting};
319 next if $setting eq "to" and defined $no_to;
320 next if $setting eq "cc" and defined $no_cc;
321 next if $setting eq "bcc" and defined $no_bcc;
322 if (ref($target) eq "ARRAY") {
324 my @values = Git
::config
(@repo, "$prefix.$setting");
325 @
$target = @values if (@values && defined $values[0]);
329 $$target = Git
::config
(@repo, "$prefix.$setting") unless (defined $$target);
333 if (!defined $smtp_encryption) {
334 my $enc = Git
::config
(@repo, "$prefix.smtpencryption");
336 $smtp_encryption = $enc;
337 } elsif (Git
::config_bool
(@repo, "$prefix.smtpssl")) {
338 $smtp_encryption = 'ssl';
343 # read configuration from [sendemail "$identity"], fall back on [sendemail]
344 $identity = Git
::config
(@repo, "sendemail.identity") unless (defined $identity);
345 read_config
("sendemail.$identity") if (defined $identity);
346 read_config
("sendemail");
348 # fall back on builtin bool defaults
349 foreach my $setting (values %config_bool_settings) {
350 ${$setting->[0]} = $setting->[1] unless (defined (${$setting->[0]}));
353 # 'default' encryption is none -- this only prevents a warning
354 $smtp_encryption = '' unless (defined $smtp_encryption);
356 # Set CC suppressions
359 foreach my $entry (@suppress_cc) {
360 die "Unknown --suppress-cc field: '$entry'\n"
361 unless $entry =~ /^(all|cccmd|cc|author|self|sob|body|bodycc)$/;
362 $suppress_cc{$entry} = 1;
366 if ($suppress_cc{'all'}) {
367 foreach my $entry (qw
(cccmd cc author self sob body bodycc
)) {
368 $suppress_cc{$entry} = 1;
370 delete $suppress_cc{'all'};
373 # If explicit old-style ones are specified, they trump --suppress-cc.
374 $suppress_cc{'self'} = $suppress_from if defined $suppress_from;
375 $suppress_cc{'sob'} = !$signed_off_by_cc if defined $signed_off_by_cc;
377 if ($suppress_cc{'body'}) {
378 foreach my $entry (qw
(sob bodycc
)) {
379 $suppress_cc{$entry} = 1;
381 delete $suppress_cc{'body'};
384 # Set confirm's default value
385 my $confirm_unconfigured = !defined $confirm;
386 if ($confirm_unconfigured) {
387 $confirm = scalar %suppress_cc ?
'compose' : 'auto';
389 die "Unknown --confirm setting: '$confirm'\n"
390 unless $confirm =~ /^(?:auto|cc|compose|always|never)/;
392 # Debugging, print out the suppressions.
394 print "suppressions:\n";
395 foreach my $entry (keys %suppress_cc) {
396 printf " %-5s -> $suppress_cc{$entry}\n", $entry;
400 my ($repoauthor, $repocommitter);
401 ($repoauthor) = Git
::ident_person
(@repo, 'author');
402 ($repocommitter) = Git
::ident_person
(@repo, 'committer');
404 # Verify the user input
406 foreach my $entry (@to) {
407 die "Comma in --to entry: $entry'\n" unless $entry !~ m/,/;
410 foreach my $entry (@initial_cc) {
411 die "Comma in --cc entry: $entry'\n" unless $entry !~ m/,/;
414 foreach my $entry (@bcclist) {
415 die "Comma in --bcclist entry: $entry'\n" unless $entry !~ m/,/;
418 sub parse_address_line
{
419 if ($have_mail_address) {
420 return map { $_->format } Mail
::Address
->parse($_[0]);
422 return split_addrs
($_[0]);
427 return quotewords
('\s*,\s*', 1, @_);
432 # multiline formats can be supported in the future
433 mutt
=> sub { my $fh = shift; while (<$fh>) {
434 if (/^\s*alias\s+(?:-group\s+\S+\s+)*(\S+)\s+(.*)$/) {
435 my ($alias, $addr) = ($1, $2);
436 $addr =~ s/#.*$//; # mutt allows # comments
437 # commas delimit multiple addresses
438 $aliases{$alias} = [ split_addrs
($addr) ];
440 mailrc
=> sub { my $fh = shift; while (<$fh>) {
441 if (/^alias\s+(\S+)\s+(.*)$/) {
442 # spaces delimit multiple addresses
443 $aliases{$1} = [ quotewords
('\s+', 0, $2) ];
445 pine
=> sub { my $fh = shift; my $f='\t[^\t]*';
446 for (my $x = ''; defined($x); $x = $_) {
448 $x .= $1 while(defined($_ = <$fh>) && /^ +(.*)$/);
449 $x =~ /^(\S+)$f\t\(?([^\t]+?)\)?(:?$f){0,2}$/ or next;
450 $aliases{$1} = [ split_addrs
($2) ];
452 elm
=> sub { my $fh = shift;
454 if (/^(\S+)\s+=\s+[^=]+=\s(\S+)/) {
455 my ($alias, $addr) = ($1, $2);
456 $aliases{$alias} = [ split_addrs
($addr) ];
460 gnus
=> sub { my $fh = shift; while (<$fh>) {
461 if (/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) {
462 $aliases{$1} = [ $2 ];
466 if (@alias_files and $aliasfiletype and defined $parse_alias{$aliasfiletype}) {
467 foreach my $file (@alias_files) {
468 open my $fh, '<', $file or die "opening $file: $!\n";
469 $parse_alias{$aliasfiletype}->($fh);
474 ($sender) = expand_aliases
($sender) if defined $sender;
476 # returns 1 if the conflict must be solved using it as a format-patch argument
477 sub check_file_rev_conflict
($) {
481 $repo->command('rev-parse', '--verify', '--quiet', $f);
482 if (defined($format_patch)) {
483 return $format_patch;
486 File '$f' exists but it could also be the range of commits
487 to produce patches for. Please disambiguate by...
489 * Saying "./$f" if you mean a file; or
490 * Giving --format-patch option if you mean a range.
492 } catch Git
::Error
::Command with
{
497 # Now that all the defaults are set, process the rest of the command line
498 # arguments and collect up the files that need to be processed.
500 while (defined(my $f = shift @ARGV)) {
502 push @rev_list_opts, "--", @ARGV;
504 } elsif (-d
$f and !check_file_rev_conflict
($f)) {
506 or die "Failed to opendir $f: $!";
508 push @files, grep { -f
$_ } map { +$f . "/" . $_ }
511 } elsif ((-f
$f or -p
$f) and !check_file_rev_conflict
($f)) {
514 push @rev_list_opts, $f;
518 if (@rev_list_opts) {
519 die "Cannot run git format-patch from outside a repository\n"
521 push @files, $repo->command('format-patch', '-o', tempdir
(CLEANUP
=> 1), @rev_list_opts);
525 foreach my $f (@files) {
527 my $error = validate_patch
($f);
528 $error and die "fatal: $f: $error\nwarning: no patches were sent\n";
535 print $_,"\n" for (@files);
538 print STDERR
"\nNo patch files specified!\n\n";
542 sub get_patch_subject
($) {
544 open (my $fh, '<', $fn);
545 while (my $line = <$fh>) {
546 next unless ($line =~ /^Subject: (.*)$/);
551 die "No subject line in $fn ?";
555 # Note that this does not need to be secure, but we will make a small
556 # effort to have it be unique
557 $compose_filename = ($repo ?
558 tempfile
(".gitsendemail.msg.XXXXXX", DIR
=> $repo->repo_path()) :
559 tempfile
(".gitsendemail.msg.XXXXXX", DIR
=> "."))[1];
560 open(C
,">",$compose_filename)
561 or die "Failed to open for writing $compose_filename: $!";
564 my $tpl_sender = $sender || $repoauthor || $repocommitter || '';
565 my $tpl_subject = $initial_subject || '';
566 my $tpl_reply_to = $initial_reply_to || '';
569 From $tpl_sender # This line is ignored.
570 GIT: Lines beginning in "GIT:" will be removed.
571 GIT: Consider including an overall diffstat or table of contents
572 GIT: for the patch you are writing.
574 GIT: Clear the body content if you don't wish to send a summary.
576 Subject: $tpl_subject
577 In-Reply-To: $tpl_reply_to
581 print C get_patch_subject
($f);
586 do_edit
($compose_filename, @files);
588 do_edit
($compose_filename);
591 open(C2
,">",$compose_filename . ".final")
592 or die "Failed to open $compose_filename.final : " . $!;
594 open(C
,"<",$compose_filename)
595 or die "Failed to open $compose_filename : " . $!;
597 my $need_8bit_cte = file_has_nonascii
($compose_filename);
599 my $summary_empty = 1;
603 $summary_empty = 0 unless (/^\n$/);
606 if ($need_8bit_cte) {
607 print C2
"MIME-Version: 1.0\n",
608 "Content-Type: text/plain; ",
610 "Content-Transfer-Encoding: 8bit\n";
612 } elsif (/^MIME-Version:/i) {
614 } elsif (/^Subject:\s*(.+)\s*$/i) {
615 $initial_subject = $1;
616 my $subject = $initial_subject;
618 ($subject =~ /[^[:ascii:]]/ ?
619 quote_rfc2047
($subject) :
622 } elsif (/^In-Reply-To:\s*(.+)\s*$/i) {
623 $initial_reply_to = $1;
625 } elsif (/^From:\s*(.+)\s*$/i) {
628 } elsif (/^(?:To|Cc|Bcc):/i) {
629 print "To/Cc/Bcc fields are not interpreted yet, they have been ignored\n";
637 if ($summary_empty) {
638 print "Summary email is empty, skipping it\n";
641 } elsif ($annotate) {
646 my ($prompt, %arg) = @_;
647 my $valid_re = $arg{valid_re
};
648 my $default = $arg{default};
651 return defined $default ?
$default : undef
652 unless defined $term->IN and defined fileno($term->IN) and
653 defined $term->OUT and defined fileno($term->OUT);
655 $resp = $term->readline($prompt);
656 if (!defined $resp) { # EOF
658 return defined $default ?
$default : undef;
660 if ($resp eq '' and defined $default) {
663 if (!defined $valid_re or $resp =~ /$valid_re/) {
671 if (!defined $sender) {
672 $sender = $repoauthor || $repocommitter || '';
673 $sender = ask
("Who should the emails appear to be from? [$sender] ",
675 print "Emails will be sent from: ", $sender, "\n";
680 my $to = ask
("Who should the emails be sent to? ");
681 push @to, parse_address_line
($to) if defined $to; # sanitized/validated later
686 return map { expand_one_alias
($_) } @_;
689 my %EXPANDED_ALIASES;
690 sub expand_one_alias
{
692 if ($EXPANDED_ALIASES{$alias}) {
693 die "fatal: alias '$alias' expands to itself\n";
695 local $EXPANDED_ALIASES{$alias} = 1;
696 return $aliases{$alias} ? expand_aliases
(@
{$aliases{$alias}}) : $alias;
699 @to = expand_aliases
(@to);
700 @to = (map { sanitize_address
($_) } @to);
701 @initial_cc = expand_aliases
(@initial_cc);
702 @bcclist = expand_aliases
(@bcclist);
704 if ($thread && !defined $initial_reply_to && $prompting) {
705 $initial_reply_to = ask
(
706 "Message-ID to be used as In-Reply-To for the first email? ");
708 if (defined $initial_reply_to) {
709 $initial_reply_to =~ s/^\s*<?//;
710 $initial_reply_to =~ s/>?\s*$//;
711 $initial_reply_to = "<$initial_reply_to>" if $initial_reply_to ne '';
714 if (!defined $smtp_server) {
715 foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
721 $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
724 if ($compose && $compose > 0) {
725 @files = ($compose_filename . ".final", @files);
728 # Variables we set as part of the loop over files
729 our ($message_id, %mail, $subject, $reply_to, $references, $message,
730 $needs_confirm, $message_num, $ask_default);
732 sub extract_valid_address
{
734 my $local_part_regexp = '[^<>"\s@]+';
735 my $domain_regexp = '[^.<>"\s@]+(?:\.[^.<>"\s@]+)+';
737 # check for a local address:
738 return $address if ($address =~ /^($local_part_regexp)$/);
740 $address =~ s/^\s*<(.*)>\s*$/$1/;
741 if ($have_email_valid) {
742 return scalar Email
::Valid
->address($address);
744 # less robust/correct than the monster regexp in Email::Valid,
745 # but still does a 99% job, and one less dependency
746 $address =~ /($local_part_regexp\@$domain_regexp)/;
751 # Usually don't need to change anything below here.
753 # we make a "fake" message id by taking the current number
754 # of seconds since the beginning of Unix time and tacking on
755 # a random number to the end, in case we are called quicker than
756 # 1 second since the last time we were called.
758 # We'll setup a template for the message id, using the "from" address:
760 my ($message_id_stamp, $message_id_serial);
764 if (!defined $message_id_stamp) {
765 $message_id_stamp = sprintf("%s-%s", time, $$);
766 $message_id_serial = 0;
768 $message_id_serial++;
769 $uniq = "$message_id_stamp-$message_id_serial";
772 for ($sender, $repocommitter, $repoauthor) {
773 $du_part = extract_valid_address
(sanitize_address
($_));
774 last if (defined $du_part and $du_part ne '');
776 if (not defined $du_part or $du_part eq '') {
777 use Sys
::Hostname
qw();
778 $du_part = 'user@' . Sys
::Hostname
::hostname
();
780 my $message_id_template = "<%s-git-send-email-%s>";
781 $message_id = sprintf($message_id_template, $uniq, $du_part);
782 #print "new message id = $message_id\n"; # Was useful for debugging
787 $time = time - scalar $#files;
789 sub unquote_rfc2047
{
792 if (s/=\?([^?]+)\?q\?(.*)\?=/$2/g) {
795 s/=([0-9A-F]{2})/chr(hex($1))/eg;
797 return wantarray ?
($_, $encoding) : $_;
802 my $encoding = shift || 'UTF-8';
803 s/([^-a-zA-Z0-9!*+\/])/sprintf
("=%02X", ord($1))/eg
;
804 s/(.*)/=\?$encoding\?q\?$1\?=/;
808 sub is_rfc2047_quoted
{
810 my $token = '[^][()<>@,;:"\/?.= \000-\037\177-\377]+';
811 my $encoded_text = '[!->@-~]+';
813 $s =~ m/^(?:"[[:ascii:]]*"|=\?$token\?$token\?$encoded_text\?=)$/o;
816 # use the simplest quoting being able to handle the recipient
819 my ($recipient) = @_;
820 my ($recipient_name, $recipient_addr) = ($recipient =~ /^(.*?)\s*(<.*)/);
822 if (not $recipient_name) {
826 # if recipient_name is already quoted, do nothing
827 if (is_rfc2047_quoted
($recipient_name)) {
831 # rfc2047 is needed if a non-ascii char is included
832 if ($recipient_name =~ /[^[:ascii:]]/) {
833 $recipient_name =~ s/^"(.*)"$/$1/;
834 $recipient_name = quote_rfc2047
($recipient_name);
837 # double quotes are needed if specials or CTLs are included
838 elsif ($recipient_name =~ /[][()<>@,;:\\".\000-\037\177]/) {
839 $recipient_name =~ s/(["\\\r])/\\$1/g;
840 $recipient_name = "\"$recipient_name\"";
843 return "$recipient_name $recipient_addr";
847 # Returns the local Fully Qualified Domain Name (FQDN) if available.
849 # Tightly configured MTAa require that a caller sends a real DNS
850 # domain name that corresponds the IP address in the HELO/EHLO
851 # handshake. This is used to verify the connection and prevent
852 # spammers from trying to hide their identity. If the DNS and IP don't
853 # match, the receiveing MTA may deny the connection.
855 # Here is a deny example of Net::SMTP with the default "localhost.localdomain"
857 # Net::SMTP=GLOB(0x267ec28)>>> EHLO localhost.localdomain
858 # Net::SMTP=GLOB(0x267ec28)<<< 550 EHLO argument does not match calling host
860 # This maildomain*() code is based on ideas in Perl library Test::Reporter
861 # /usr/share/perl5/Test/Reporter/Mail/Util.pm ==> sub _maildomain ()
867 if (eval { require Net
::Domain
; 1 }) {
868 my $domain = Net
::Domain
::domainname
();
869 $maildomain = $domain
870 unless $^O
eq 'darwin' && $domain =~ /\.local$/;
880 if (eval { require Net
::SMTP
; 1 }) {
881 for my $host (qw(mailhost localhost)) {
882 my $smtp = Net
::SMTP
->new($host);
884 my $domain = $smtp->domain;
887 $maildomain = $domain
888 unless $^O
eq 'darwin' && $domain =~ /\.local$/;
900 return maildomain_net
() || maildomain_mta
() || $mail_domain_default;
903 # Returns 1 if the message was sent, and 0 otherwise.
904 # In actuality, the whole program dies when there
905 # is an error sending a message.
909 my @recipients = unique_email_list
(@to);
910 @cc = (grep { my $cc = extract_valid_address
($_);
911 not grep { $cc eq $_ } @recipients
913 map { sanitize_address
($_) }
915 my $to = join (",\n\t", @recipients);
916 @recipients = unique_email_list
(@recipients,@cc,@bcclist);
917 @recipients = (map { extract_valid_address
($_) } @recipients);
918 my $date = format_2822_time
($time++);
919 my $gitversion = '@@GIT_VERSION@@';
920 if ($gitversion =~ m/..GIT_VERSION../) {
921 $gitversion = Git
::version
();
924 my $cc = join(",\n\t", unique_email_list
(@cc));
927 $ccline = "\nCc: $cc";
929 my $sanitized_sender = sanitize_address
($sender);
930 make_message_id
() unless defined($message_id);
932 my $header = "From: $sanitized_sender
936 Message-Id: $message_id
937 X-Mailer: git-send-email $gitversion
941 $header .= "In-Reply-To: $reply_to\n";
942 $header .= "References: $references\n";
945 $header .= join("\n", @xh) . "\n";
948 my @sendmail_parameters = ('-i', @recipients);
949 my $raw_from = $sanitized_sender;
950 if (defined $envelope_sender && $envelope_sender ne "auto") {
951 $raw_from = $envelope_sender;
953 $raw_from = extract_valid_address
($raw_from);
954 unshift (@sendmail_parameters,
955 '-f', $raw_from) if(defined $envelope_sender);
957 if ($needs_confirm && !$dry_run) {
959 if ($needs_confirm eq "inform") {
960 $confirm_unconfigured = 0; # squelch this message for the rest of this run
961 $ask_default = "y"; # assume yes on EOF since user hasn't explicitly asked for confirmation
962 print " The Cc list above has been expanded by additional\n";
963 print " addresses found in the patch commit message. By default\n";
964 print " send-email prompts before sending whenever this occurs.\n";
965 print " This behavior is controlled by the sendemail.confirm\n";
966 print " configuration setting.\n";
968 print " For additional information, run 'git send-email --help'.\n";
969 print " To retain the current behavior, but squelch this message,\n";
970 print " run 'git config --global sendemail.confirm auto'.\n\n";
972 $_ = ask
("Send this email? ([y]es|[n]o|[q]uit|[a]ll): ",
973 valid_re
=> qr/^(?:yes|y|no|n|quit|q|all|a)/i,
974 default => $ask_default);
975 die "Send this email reply required" unless defined $_;
979 cleanup_compose_files
();
987 # We don't want to send the email.
988 } elsif ($smtp_server =~ m
#^/#) {
989 my $pid = open my $sm, '|-';
990 defined $pid or die $!;
992 exec($smtp_server, @sendmail_parameters) or die $!;
994 print $sm "$header\n$message";
998 if (!defined $smtp_server) {
999 die "The required SMTP server is not properly defined."
1002 if ($smtp_encryption eq 'ssl') {
1003 $smtp_server_port ||= 465; # ssmtp
1004 require Net
::SMTP
::SSL
;
1005 $mail_domain ||= maildomain
();
1006 $smtp ||= Net
::SMTP
::SSL
->new($smtp_server,
1007 Hello
=> $mail_domain,
1008 Port
=> $smtp_server_port);
1012 $mail_domain ||= maildomain
();
1013 $smtp ||= Net
::SMTP
->new((defined $smtp_server_port)
1014 ?
"$smtp_server:$smtp_server_port"
1016 Hello
=> $mail_domain,
1017 Debug
=> $debug_net_smtp);
1018 if ($smtp_encryption eq 'tls' && $smtp) {
1019 require Net
::SMTP
::SSL
;
1020 $smtp->command('STARTTLS');
1022 if ($smtp->code == 220) {
1023 $smtp = Net
::SMTP
::SSL
->start_SSL($smtp)
1024 or die "STARTTLS failed! ".$smtp->message;
1025 $smtp_encryption = '';
1026 # Send EHLO again to receive fresh
1027 # supported commands
1030 die "Server does not support STARTTLS! ".$smtp->message;
1036 die "Unable to initialize SMTP properly. Check config and use --smtp-debug. ",
1037 "VALUES: server=$smtp_server ",
1038 "encryption=$smtp_encryption ",
1039 "maildomain=$mail_domain",
1040 defined $smtp_server_port ?
"port=$smtp_server_port" : "";
1043 if (defined $smtp_authuser) {
1045 if (!defined $smtp_authpass) {
1047 system "stty -echo";
1053 } while (!defined $_);
1055 chomp($smtp_authpass = $_);
1060 $auth ||= $smtp->auth( $smtp_authuser, $smtp_authpass ) or die $smtp->message;
1063 $smtp->mail( $raw_from ) or die $smtp->message;
1064 $smtp->to( @recipients ) or die $smtp->message;
1065 $smtp->data or die $smtp->message;
1066 $smtp->datasend("$header\n$message") or die $smtp->message;
1067 $smtp->dataend() or die $smtp->message;
1068 $smtp->code =~ /250|200/ or die "Failed to send $subject\n".$smtp->message;
1071 printf (($dry_run ?
"Dry-" : "")."Sent %s\n", $subject);
1073 print (($dry_run ?
"Dry-" : "")."OK. Log says:\n");
1074 if ($smtp_server !~ m
#^/#) {
1075 print "Server: $smtp_server\n";
1076 print "MAIL FROM:<$raw_from>\n";
1077 foreach my $entry (@recipients) {
1078 print "RCPT TO:<$entry>\n";
1081 print "Sendmail: $smtp_server ".join(' ',@sendmail_parameters)."\n";
1083 print $header, "\n";
1085 print "Result: ", $smtp->code, ' ',
1086 ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
1088 print "Result: OK\n";
1095 $reply_to = $initial_reply_to;
1096 $references = $initial_reply_to || '';
1097 $subject = $initial_subject;
1100 foreach my $t (@files) {
1101 open(F
,"<",$t) or die "can't open file $t";
1104 my $author_encoding;
1105 my $has_content_type;
1109 my $input_format = undef;
1113 # First unfold multiline header fields
1116 if (/^\s+\S/ and @header) {
1117 chomp($header[$#header]);
1119 $header[$#header] .= $_;
1124 # Now parse the header
1127 $input_format = 'mbox';
1131 if (!defined $input_format && /^[-A-Za-z]+:\s/) {
1132 $input_format = 'mbox';
1135 if (defined $input_format && $input_format eq 'mbox') {
1136 if (/^Subject:\s+(.*)$/) {
1139 elsif (/^From:\s+(.*)$/) {
1140 ($author, $author_encoding) = unquote_rfc2047
($1);
1141 next if $suppress_cc{'author'};
1142 next if $suppress_cc{'self'} and $author eq $sender;
1143 printf("(mbox) Adding cc: %s from line '%s'\n",
1144 $1, $_) unless $quiet;
1147 elsif (/^Cc:\s+(.*)$/) {
1148 foreach my $addr (parse_address_line
($1)) {
1149 if (unquote_rfc2047
($addr) eq $sender) {
1150 next if ($suppress_cc{'self'});
1152 next if ($suppress_cc{'cc'});
1154 printf("(mbox) Adding cc: %s from line '%s'\n",
1155 $addr, $_) unless $quiet;
1159 elsif (/^Content-type:/i) {
1160 $has_content_type = 1;
1161 if (/charset="?([^ "]+)/) {
1162 $body_encoding = $1;
1166 elsif (/^Message-Id: (.*)/i) {
1169 elsif (!/^Date:\s/ && /^[-A-Za-z]+:\s+\S/) {
1174 # In the traditional
1175 # "send lots of email" format,
1178 # So let's support that, too.
1179 $input_format = 'lots';
1180 if (@cc == 0 && !$suppress_cc{'cc'}) {
1181 printf("(non-mbox) Adding cc: %s from line '%s'\n",
1182 $_, $_) unless $quiet;
1184 } elsif (!defined $subject) {
1189 # Now parse the message body
1192 if (/^(Signed-off-by|Cc): (.*)$/i) {
1194 my ($what, $c) = ($1, $2);
1196 if ($c eq $sender) {
1197 next if ($suppress_cc{'self'});
1199 next if $suppress_cc{'sob'} and $what =~ /Signed-off-by/i;
1200 next if $suppress_cc{'bodycc'} and $what =~ /Cc/i;
1203 printf("(body) Adding cc: %s from line '%s'\n",
1204 $c, $_) unless $quiet;
1209 if (defined $cc_cmd && !$suppress_cc{'cccmd'}) {
1210 open(F
, "$cc_cmd \Q$t\E |")
1211 or die "(cc-cmd) Could not execute '$cc_cmd'";
1216 next if ($c eq $sender and $suppress_from);
1218 printf("(cc-cmd) Adding cc: %s from: '%s'\n",
1219 $c, $cc_cmd) unless $quiet;
1222 or die "(cc-cmd) failed to close pipe to '$cc_cmd'";
1225 if (defined $author and $author ne $sender) {
1226 $message = "From: $author\n\n$message";
1227 if (defined $author_encoding) {
1228 if ($has_content_type) {
1229 if ($body_encoding eq $author_encoding) {
1230 # ok, we already have the right encoding
1233 # uh oh, we should re-encode
1238 'MIME-Version: 1.0',
1239 "Content-Type: text/plain; charset=$author_encoding",
1240 'Content-Transfer-Encoding: 8bit';
1246 $confirm eq "always" or
1247 ($confirm =~ /^(?:auto|cc)$/ && @cc) or
1248 ($confirm =~ /^(?:auto|compose)$/ && $compose && $message_num == 1));
1249 $needs_confirm = "inform" if ($needs_confirm && $confirm_unconfigured && @cc);
1251 @cc = (@initial_cc, @cc);
1253 my $message_was_sent = send_message
();
1255 # set up for the next message
1256 if ($thread && $message_was_sent &&
1257 (chain_reply_to
() || !defined $reply_to || length($reply_to) == 0)) {
1258 $reply_to = $message_id;
1259 if (length $references > 0) {
1260 $references .= "\n $message_id";
1262 $references = "$message_id";
1265 $message_id = undef;
1268 cleanup_compose_files
();
1270 sub cleanup_compose_files
() {
1271 unlink($compose_filename, $compose_filename . ".final") if $compose;
1274 $smtp->quit if $smtp;
1276 sub unique_email_list
(@
) {
1280 foreach my $entry (@_) {
1281 if (my $clean = extract_valid_address
($entry)) {
1282 $seen{$clean} ||= 0;
1283 next if $seen{$clean}++;
1284 push @emails, $entry;
1286 print STDERR
"W: unable to extract a valid address",
1293 sub validate_patch
{
1295 open(my $fh, '<', $fn)
1296 or die "unable to open $fn: $!\n";
1297 while (my $line = <$fh>) {
1298 if (length($line) > 998) {
1299 return "$.: patch contains a line longer than 998 characters";
1305 sub file_has_nonascii
{
1307 open(my $fh, '<', $fn)
1308 or die "unable to open $fn: $!\n";
1309 while (my $line = <$fh>) {
1310 return 1 if $line =~ /[^[:ascii:]]/;