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 };
136 sub unique_email_list
(@
);
137 sub cleanup_compose_files
();
139 # Variables we fill in automatically, or via prompting:
140 my (@to,$no_to,@cc,$no_cc,@initial_cc,@bcclist,$no_bcc,@xh,
141 $initial_reply_to,$initial_subject,@files,
142 $author,$sender,$smtp_authpass,$annotate,$compose,$time);
147 #$initial_reply_to = ''; #<20050203173208.GA23964@foobar.com>';
149 my $repo = eval { Git
->repository() };
150 my @repo = $repo ?
($repo) : ();
152 $ENV{"GIT_SEND_EMAIL_NOTTY"}
153 ? new Term
::ReadLine
'git-send-email', \
*STDIN
, \
*STDOUT
154 : new Term
::ReadLine
'git-send-email';
157 $term = new FakeTerm
"$@: going non-interactive";
160 # Behavior modification variables
161 my ($quiet, $dry_run) = (0, 0);
163 my $compose_filename;
165 # Handle interactive edition of files.
170 if (!defined($editor)) {
171 $editor = Git
::command_oneline
('var', 'GIT_EDITOR');
173 if (defined($multiedit) && !$multiedit) {
175 system('sh', '-c', $editor.' "$@"', $editor, $_);
176 if (($?
& 127) || ($?
>> 8)) {
177 die("the editor exited uncleanly, aborting everything");
181 system('sh', '-c', $editor.' "$@"', $editor, @_);
182 if (($?
& 127) || ($?
>> 8)) {
183 die("the editor exited uncleanly, aborting everything");
188 # Variables with corresponding config settings
189 my ($thread, $chain_reply_to, $suppress_from, $signed_off_by_cc, $cc_cmd);
190 my ($smtp_server, $smtp_server_port, $smtp_authuser, $smtp_encryption);
191 my ($identity, $aliasfiletype, @alias_files, @smtp_host_parts, $smtp_domain);
192 my ($validate, $confirm);
195 my ($debug_net_smtp) = 0; # Net::SMTP, see send_message()
197 my $not_set_by_user = "true but not set by the user";
199 my %config_bool_settings = (
200 "thread" => [\
$thread, 1],
201 "chainreplyto" => [\
$chain_reply_to, $not_set_by_user],
202 "suppressfrom" => [\
$suppress_from, undef],
203 "signedoffbycc" => [\
$signed_off_by_cc, undef],
204 "signedoffcc" => [\
$signed_off_by_cc, undef], # Deprecated
205 "validate" => [\
$validate, 1],
208 my %config_settings = (
209 "smtpserver" => \
$smtp_server,
210 "smtpserverport" => \
$smtp_server_port,
211 "smtpuser" => \
$smtp_authuser,
212 "smtppass" => \
$smtp_authpass,
213 "smtpdomain" => \
$smtp_domain,
215 "cc" => \
@initial_cc,
217 "aliasfiletype" => \
$aliasfiletype,
219 "aliasesfile" => \
@alias_files,
220 "suppresscc" => \
@suppress_cc,
221 "envelopesender" => \
$envelope_sender,
222 "multiedit" => \
$multiedit,
223 "confirm" => \
$confirm,
227 # Help users prepare for 1.7.0
229 if (defined $chain_reply_to &&
230 $chain_reply_to eq $not_set_by_user) {
232 "In git 1.7.0, the default has changed to --no-chain-reply-to\n" .
233 "Set sendemail.chainreplyto configuration variable to true if\n" .
234 "you want to keep --chain-reply-to as your default.\n";
237 return $chain_reply_to;
240 # Handle Uncouth Termination
244 print color
("reset"), "\n";
246 # SMTP password masked
249 # tmp files from --compose
250 if (defined $compose_filename) {
251 if (-e
$compose_filename) {
252 print "'$compose_filename' contains an intermediate version of the email you were composing.\n";
254 if (-e
($compose_filename . ".final")) {
255 print "'$compose_filename.final' contains the composed email.\n"
262 $SIG{TERM
} = \
&signal_handler
;
263 $SIG{INT
} = \
&signal_handler
;
265 # Begin by accumulating all the variables (defined above), that we will end up
266 # needing, first, from the command line:
268 my $rc = GetOptions
("sender|from=s" => \
$sender,
269 "in-reply-to=s" => \
$initial_reply_to,
270 "subject=s" => \
$initial_subject,
273 "cc=s" => \
@initial_cc,
275 "bcc=s" => \
@bcclist,
276 "no-bcc" => \
$no_bcc,
277 "chain-reply-to!" => \
$chain_reply_to,
278 "smtp-server=s" => \
$smtp_server,
279 "smtp-server-port=s" => \
$smtp_server_port,
280 "smtp-user=s" => \
$smtp_authuser,
281 "smtp-pass:s" => \
$smtp_authpass,
282 "smtp-ssl" => sub { $smtp_encryption = 'ssl' },
283 "smtp-encryption=s" => \
$smtp_encryption,
284 "smtp-debug:i" => \
$debug_net_smtp,
285 "smtp-domain:s" => \
$smtp_domain,
286 "identity=s" => \
$identity,
287 "annotate" => \
$annotate,
288 "compose" => \
$compose,
290 "cc-cmd=s" => \
$cc_cmd,
291 "suppress-from!" => \
$suppress_from,
292 "suppress-cc=s" => \
@suppress_cc,
293 "signed-off-cc|signed-off-by-cc!" => \
$signed_off_by_cc,
294 "confirm=s" => \
$confirm,
295 "dry-run" => \
$dry_run,
296 "envelope-sender=s" => \
$envelope_sender,
297 "thread!" => \
$thread,
298 "validate!" => \
$validate,
299 "format-patch!" => \
$format_patch,
306 die "Cannot run git format-patch from outside a repository\n"
307 if $format_patch and not $repo;
309 # Now, let's fill any that aren't set in with defaults:
314 foreach my $setting (keys %config_bool_settings) {
315 my $target = $config_bool_settings{$setting}->[0];
316 $$target = Git
::config_bool
(@repo, "$prefix.$setting") unless (defined $$target);
319 foreach my $setting (keys %config_settings) {
320 my $target = $config_settings{$setting};
321 next if $setting eq "to" and defined $no_to;
322 next if $setting eq "cc" and defined $no_cc;
323 next if $setting eq "bcc" and defined $no_bcc;
324 if (ref($target) eq "ARRAY") {
326 my @values = Git
::config
(@repo, "$prefix.$setting");
327 @
$target = @values if (@values && defined $values[0]);
331 $$target = Git
::config
(@repo, "$prefix.$setting") unless (defined $$target);
335 if (!defined $smtp_encryption) {
336 my $enc = Git
::config
(@repo, "$prefix.smtpencryption");
338 $smtp_encryption = $enc;
339 } elsif (Git
::config_bool
(@repo, "$prefix.smtpssl")) {
340 $smtp_encryption = 'ssl';
345 # read configuration from [sendemail "$identity"], fall back on [sendemail]
346 $identity = Git
::config
(@repo, "sendemail.identity") unless (defined $identity);
347 read_config
("sendemail.$identity") if (defined $identity);
348 read_config
("sendemail");
350 # fall back on builtin bool defaults
351 foreach my $setting (values %config_bool_settings) {
352 ${$setting->[0]} = $setting->[1] unless (defined (${$setting->[0]}));
355 # 'default' encryption is none -- this only prevents a warning
356 $smtp_encryption = '' unless (defined $smtp_encryption);
358 # Set CC suppressions
361 foreach my $entry (@suppress_cc) {
362 die "Unknown --suppress-cc field: '$entry'\n"
363 unless $entry =~ /^(all|cccmd|cc|author|self|sob|body|bodycc)$/;
364 $suppress_cc{$entry} = 1;
368 if ($suppress_cc{'all'}) {
369 foreach my $entry (qw
(cccmd cc author self sob body bodycc
)) {
370 $suppress_cc{$entry} = 1;
372 delete $suppress_cc{'all'};
375 # If explicit old-style ones are specified, they trump --suppress-cc.
376 $suppress_cc{'self'} = $suppress_from if defined $suppress_from;
377 $suppress_cc{'sob'} = !$signed_off_by_cc if defined $signed_off_by_cc;
379 if ($suppress_cc{'body'}) {
380 foreach my $entry (qw
(sob bodycc
)) {
381 $suppress_cc{$entry} = 1;
383 delete $suppress_cc{'body'};
386 # Set confirm's default value
387 my $confirm_unconfigured = !defined $confirm;
388 if ($confirm_unconfigured) {
389 $confirm = scalar %suppress_cc ?
'compose' : 'auto';
391 die "Unknown --confirm setting: '$confirm'\n"
392 unless $confirm =~ /^(?:auto|cc|compose|always|never)/;
394 # Debugging, print out the suppressions.
396 print "suppressions:\n";
397 foreach my $entry (keys %suppress_cc) {
398 printf " %-5s -> $suppress_cc{$entry}\n", $entry;
402 my ($repoauthor, $repocommitter);
403 ($repoauthor) = Git
::ident_person
(@repo, 'author');
404 ($repocommitter) = Git
::ident_person
(@repo, 'committer');
406 # Verify the user input
408 foreach my $entry (@to) {
409 die "Comma in --to entry: $entry'\n" unless $entry !~ m/,/;
412 foreach my $entry (@initial_cc) {
413 die "Comma in --cc entry: $entry'\n" unless $entry !~ m/,/;
416 foreach my $entry (@bcclist) {
417 die "Comma in --bcclist entry: $entry'\n" unless $entry !~ m/,/;
420 sub parse_address_line
{
421 if ($have_mail_address) {
422 return map { $_->format } Mail
::Address
->parse($_[0]);
424 return split_addrs
($_[0]);
429 return quotewords
('\s*,\s*', 1, @_);
434 # multiline formats can be supported in the future
435 mutt
=> sub { my $fh = shift; while (<$fh>) {
436 if (/^\s*alias\s+(?:-group\s+\S+\s+)*(\S+)\s+(.*)$/) {
437 my ($alias, $addr) = ($1, $2);
438 $addr =~ s/#.*$//; # mutt allows # comments
439 # commas delimit multiple addresses
440 $aliases{$alias} = [ split_addrs
($addr) ];
442 mailrc
=> sub { my $fh = shift; while (<$fh>) {
443 if (/^alias\s+(\S+)\s+(.*)$/) {
444 # spaces delimit multiple addresses
445 $aliases{$1} = [ quotewords
('\s+', 0, $2) ];
447 pine
=> sub { my $fh = shift; my $f='\t[^\t]*';
448 for (my $x = ''; defined($x); $x = $_) {
450 $x .= $1 while(defined($_ = <$fh>) && /^ +(.*)$/);
451 $x =~ /^(\S+)$f\t\(?([^\t]+?)\)?(:?$f){0,2}$/ or next;
452 $aliases{$1} = [ split_addrs
($2) ];
454 elm
=> sub { my $fh = shift;
456 if (/^(\S+)\s+=\s+[^=]+=\s(\S+)/) {
457 my ($alias, $addr) = ($1, $2);
458 $aliases{$alias} = [ split_addrs
($addr) ];
462 gnus
=> sub { my $fh = shift; while (<$fh>) {
463 if (/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) {
464 $aliases{$1} = [ $2 ];
468 if (@alias_files and $aliasfiletype and defined $parse_alias{$aliasfiletype}) {
469 foreach my $file (@alias_files) {
470 open my $fh, '<', $file or die "opening $file: $!\n";
471 $parse_alias{$aliasfiletype}->($fh);
476 ($sender) = expand_aliases
($sender) if defined $sender;
478 # returns 1 if the conflict must be solved using it as a format-patch argument
479 sub check_file_rev_conflict
($) {
483 $repo->command('rev-parse', '--verify', '--quiet', $f);
484 if (defined($format_patch)) {
485 return $format_patch;
488 File '$f' exists but it could also be the range of commits
489 to produce patches for. Please disambiguate by...
491 * Saying "./$f" if you mean a file; or
492 * Giving --format-patch option if you mean a range.
494 } catch Git
::Error
::Command with
{
499 # Now that all the defaults are set, process the rest of the command line
500 # arguments and collect up the files that need to be processed.
502 while (defined(my $f = shift @ARGV)) {
504 push @rev_list_opts, "--", @ARGV;
506 } elsif (-d
$f and !check_file_rev_conflict
($f)) {
508 or die "Failed to opendir $f: $!";
510 push @files, grep { -f
$_ } map { +$f . "/" . $_ }
513 } elsif ((-f
$f or -p
$f) and !check_file_rev_conflict
($f)) {
516 push @rev_list_opts, $f;
520 if (@rev_list_opts) {
521 die "Cannot run git format-patch from outside a repository\n"
523 push @files, $repo->command('format-patch', '-o', tempdir
(CLEANUP
=> 1), @rev_list_opts);
527 foreach my $f (@files) {
529 my $error = validate_patch
($f);
530 $error and die "fatal: $f: $error\nwarning: no patches were sent\n";
537 print $_,"\n" for (@files);
540 print STDERR
"\nNo patch files specified!\n\n";
544 sub get_patch_subject
($) {
546 open (my $fh, '<', $fn);
547 while (my $line = <$fh>) {
548 next unless ($line =~ /^Subject: (.*)$/);
553 die "No subject line in $fn ?";
557 # Note that this does not need to be secure, but we will make a small
558 # effort to have it be unique
559 $compose_filename = ($repo ?
560 tempfile
(".gitsendemail.msg.XXXXXX", DIR
=> $repo->repo_path()) :
561 tempfile
(".gitsendemail.msg.XXXXXX", DIR
=> "."))[1];
562 open(C
,">",$compose_filename)
563 or die "Failed to open for writing $compose_filename: $!";
566 my $tpl_sender = $sender || $repoauthor || $repocommitter || '';
567 my $tpl_subject = $initial_subject || '';
568 my $tpl_reply_to = $initial_reply_to || '';
571 From $tpl_sender # This line is ignored.
572 GIT: Lines beginning in "GIT:" will be removed.
573 GIT: Consider including an overall diffstat or table of contents
574 GIT: for the patch you are writing.
576 GIT: Clear the body content if you don't wish to send a summary.
578 Subject: $tpl_subject
579 In-Reply-To: $tpl_reply_to
583 print C get_patch_subject
($f);
588 do_edit
($compose_filename, @files);
590 do_edit
($compose_filename);
593 open(C2
,">",$compose_filename . ".final")
594 or die "Failed to open $compose_filename.final : " . $!;
596 open(C
,"<",$compose_filename)
597 or die "Failed to open $compose_filename : " . $!;
599 my $need_8bit_cte = file_has_nonascii
($compose_filename);
601 my $summary_empty = 1;
605 $summary_empty = 0 unless (/^\n$/);
608 if ($need_8bit_cte) {
609 print C2
"MIME-Version: 1.0\n",
610 "Content-Type: text/plain; ",
612 "Content-Transfer-Encoding: 8bit\n";
614 } elsif (/^MIME-Version:/i) {
616 } elsif (/^Subject:\s*(.+)\s*$/i) {
617 $initial_subject = $1;
618 my $subject = $initial_subject;
620 ($subject =~ /[^[:ascii:]]/ ?
621 quote_rfc2047
($subject) :
624 } elsif (/^In-Reply-To:\s*(.+)\s*$/i) {
625 $initial_reply_to = $1;
627 } elsif (/^From:\s*(.+)\s*$/i) {
630 } elsif (/^(?:To|Cc|Bcc):/i) {
631 print "To/Cc/Bcc fields are not interpreted yet, they have been ignored\n";
639 if ($summary_empty) {
640 print "Summary email is empty, skipping it\n";
643 } elsif ($annotate) {
648 my ($prompt, %arg) = @_;
649 my $valid_re = $arg{valid_re
};
650 my $default = $arg{default};
653 return defined $default ?
$default : undef
654 unless defined $term->IN and defined fileno($term->IN) and
655 defined $term->OUT and defined fileno($term->OUT);
657 $resp = $term->readline($prompt);
658 if (!defined $resp) { # EOF
660 return defined $default ?
$default : undef;
662 if ($resp eq '' and defined $default) {
665 if (!defined $valid_re or $resp =~ /$valid_re/) {
673 if (!defined $sender) {
674 $sender = $repoauthor || $repocommitter || '';
675 $sender = ask
("Who should the emails appear to be from? [$sender] ",
677 print "Emails will be sent from: ", $sender, "\n";
682 my $to = ask
("Who should the emails be sent to? ");
683 push @to, parse_address_line
($to) if defined $to; # sanitized/validated later
688 return map { expand_one_alias
($_) } @_;
691 my %EXPANDED_ALIASES;
692 sub expand_one_alias
{
694 if ($EXPANDED_ALIASES{$alias}) {
695 die "fatal: alias '$alias' expands to itself\n";
697 local $EXPANDED_ALIASES{$alias} = 1;
698 return $aliases{$alias} ? expand_aliases
(@
{$aliases{$alias}}) : $alias;
701 @to = expand_aliases
(@to);
702 @to = (map { sanitize_address
($_) } @to);
703 @initial_cc = expand_aliases
(@initial_cc);
704 @bcclist = expand_aliases
(@bcclist);
706 if ($thread && !defined $initial_reply_to && $prompting) {
707 $initial_reply_to = ask
(
708 "Message-ID to be used as In-Reply-To for the first email? ");
710 if (defined $initial_reply_to) {
711 $initial_reply_to =~ s/^\s*<?//;
712 $initial_reply_to =~ s/>?\s*$//;
713 $initial_reply_to = "<$initial_reply_to>" if $initial_reply_to ne '';
716 if (!defined $smtp_server) {
717 foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
723 $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
726 if ($compose && $compose > 0) {
727 @files = ($compose_filename . ".final", @files);
730 # Variables we set as part of the loop over files
731 our ($message_id, %mail, $subject, $reply_to, $references, $message,
732 $needs_confirm, $message_num, $ask_default);
734 sub extract_valid_address
{
736 my $local_part_regexp = '[^<>"\s@]+';
737 my $domain_regexp = '[^.<>"\s@]+(?:\.[^.<>"\s@]+)+';
739 # check for a local address:
740 return $address if ($address =~ /^($local_part_regexp)$/);
742 $address =~ s/^\s*<(.*)>\s*$/$1/;
743 if ($have_email_valid) {
744 return scalar Email
::Valid
->address($address);
746 # less robust/correct than the monster regexp in Email::Valid,
747 # but still does a 99% job, and one less dependency
748 $address =~ /($local_part_regexp\@$domain_regexp)/;
753 # Usually don't need to change anything below here.
755 # we make a "fake" message id by taking the current number
756 # of seconds since the beginning of Unix time and tacking on
757 # a random number to the end, in case we are called quicker than
758 # 1 second since the last time we were called.
760 # We'll setup a template for the message id, using the "from" address:
762 my ($message_id_stamp, $message_id_serial);
763 sub make_message_id
{
765 if (!defined $message_id_stamp) {
766 $message_id_stamp = sprintf("%s-%s", time, $$);
767 $message_id_serial = 0;
769 $message_id_serial++;
770 $uniq = "$message_id_stamp-$message_id_serial";
773 for ($sender, $repocommitter, $repoauthor) {
774 $du_part = extract_valid_address
(sanitize_address
($_));
775 last if (defined $du_part and $du_part ne '');
777 if (not defined $du_part or $du_part eq '') {
778 use Sys
::Hostname
qw();
779 $du_part = 'user@' . Sys
::Hostname
::hostname
();
781 my $message_id_template = "<%s-git-send-email-%s>";
782 $message_id = sprintf($message_id_template, $uniq, $du_part);
783 #print "new message id = $message_id\n"; # Was useful for debugging
788 $time = time - scalar $#files;
790 sub unquote_rfc2047
{
793 if (s/=\?([^?]+)\?q\?(.*)\?=/$2/g) {
796 s/=([0-9A-F]{2})/chr(hex($1))/eg;
798 return wantarray ?
($_, $encoding) : $_;
803 my $encoding = shift || 'UTF-8';
804 s/([^-a-zA-Z0-9!*+\/])/sprintf
("=%02X", ord($1))/eg
;
805 s/(.*)/=\?$encoding\?q\?$1\?=/;
809 sub is_rfc2047_quoted
{
811 my $token = '[^][()<>@,;:"\/?.= \000-\037\177-\377]+';
812 my $encoded_text = '[!->@-~]+';
814 $s =~ m/^(?:"[[:ascii:]]*"|=\?$token\?$token\?$encoded_text\?=)$/o;
817 # use the simplest quoting being able to handle the recipient
818 sub sanitize_address
{
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 ()
865 return !($^O
eq 'darwin' && $domain =~ /\.local$/) && $domain =~ /\./;
871 if (eval { require Net
::Domain
; 1 }) {
872 my $domain = Net
::Domain
::domainname
();
873 $maildomain = $domain if valid_fqdn
($domain);
882 if (eval { require Net
::SMTP
; 1 }) {
883 for my $host (qw(mailhost localhost)) {
884 my $smtp = Net
::SMTP
->new($host);
886 my $domain = $smtp->domain;
889 $maildomain = $domain if valid_fqdn
($domain);
900 return maildomain_net
() || maildomain_mta
() || 'localhost.localdomain';
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.
908 my @recipients = unique_email_list
(@to);
909 @cc = (grep { my $cc = extract_valid_address
($_);
910 not grep { $cc eq $_ } @recipients
912 map { sanitize_address
($_) }
914 my $to = join (",\n\t", @recipients);
915 @recipients = unique_email_list
(@recipients,@cc,@bcclist);
916 @recipients = (map { extract_valid_address
($_) } @recipients);
917 my $date = format_2822_time
($time++);
918 my $gitversion = '@@GIT_VERSION@@';
919 if ($gitversion =~ m/..GIT_VERSION../) {
920 $gitversion = Git
::version
();
923 my $cc = join(",\n\t", unique_email_list
(@cc));
926 $ccline = "\nCc: $cc";
928 my $sanitized_sender = sanitize_address
($sender);
929 make_message_id
() unless defined($message_id);
931 my $header = "From: $sanitized_sender
935 Message-Id: $message_id
936 X-Mailer: git-send-email $gitversion
940 $header .= "In-Reply-To: $reply_to\n";
941 $header .= "References: $references\n";
944 $header .= join("\n", @xh) . "\n";
947 my @sendmail_parameters = ('-i', @recipients);
948 my $raw_from = $sanitized_sender;
949 if (defined $envelope_sender && $envelope_sender ne "auto") {
950 $raw_from = $envelope_sender;
952 $raw_from = extract_valid_address
($raw_from);
953 unshift (@sendmail_parameters,
954 '-f', $raw_from) if(defined $envelope_sender);
956 if ($needs_confirm && !$dry_run) {
958 if ($needs_confirm eq "inform") {
959 $confirm_unconfigured = 0; # squelch this message for the rest of this run
960 $ask_default = "y"; # assume yes on EOF since user hasn't explicitly asked for confirmation
961 print " The Cc list above has been expanded by additional\n";
962 print " addresses found in the patch commit message. By default\n";
963 print " send-email prompts before sending whenever this occurs.\n";
964 print " This behavior is controlled by the sendemail.confirm\n";
965 print " configuration setting.\n";
967 print " For additional information, run 'git send-email --help'.\n";
968 print " To retain the current behavior, but squelch this message,\n";
969 print " run 'git config --global sendemail.confirm auto'.\n\n";
971 $_ = ask
("Send this email? ([y]es|[n]o|[q]uit|[a]ll): ",
972 valid_re
=> qr/^(?:yes|y|no|n|quit|q|all|a)/i,
973 default => $ask_default);
974 die "Send this email reply required" unless defined $_;
978 cleanup_compose_files
();
986 # We don't want to send the email.
987 } elsif ($smtp_server =~ m
#^/#) {
988 my $pid = open my $sm, '|-';
989 defined $pid or die $!;
991 exec($smtp_server, @sendmail_parameters) or die $!;
993 print $sm "$header\n$message";
997 if (!defined $smtp_server) {
998 die "The required SMTP server is not properly defined."
1001 if ($smtp_encryption eq 'ssl') {
1002 $smtp_server_port ||= 465; # ssmtp
1003 require Net
::SMTP
::SSL
;
1004 $smtp_domain ||= maildomain
();
1005 $smtp ||= Net
::SMTP
::SSL
->new($smtp_server,
1006 Hello
=> $smtp_domain,
1007 Port
=> $smtp_server_port);
1011 $smtp_domain ||= maildomain
();
1012 $smtp ||= Net
::SMTP
->new((defined $smtp_server_port)
1013 ?
"$smtp_server:$smtp_server_port"
1015 Hello
=> $smtp_domain,
1016 Debug
=> $debug_net_smtp);
1017 if ($smtp_encryption eq 'tls' && $smtp) {
1018 require Net
::SMTP
::SSL
;
1019 $smtp->command('STARTTLS');
1021 if ($smtp->code == 220) {
1022 $smtp = Net
::SMTP
::SSL
->start_SSL($smtp)
1023 or die "STARTTLS failed! ".$smtp->message;
1024 $smtp_encryption = '';
1025 # Send EHLO again to receive fresh
1026 # supported commands
1029 die "Server does not support STARTTLS! ".$smtp->message;
1035 die "Unable to initialize SMTP properly. Check config and use --smtp-debug. ",
1036 "VALUES: server=$smtp_server ",
1037 "encryption=$smtp_encryption ",
1038 "hello=$smtp_domain",
1039 defined $smtp_server_port ?
"port=$smtp_server_port" : "";
1042 if (defined $smtp_authuser) {
1044 if (!defined $smtp_authpass) {
1046 system "stty -echo";
1052 } while (!defined $_);
1054 chomp($smtp_authpass = $_);
1059 $auth ||= $smtp->auth( $smtp_authuser, $smtp_authpass ) or die $smtp->message;
1062 $smtp->mail( $raw_from ) or die $smtp->message;
1063 $smtp->to( @recipients ) or die $smtp->message;
1064 $smtp->data or die $smtp->message;
1065 $smtp->datasend("$header\n$message") or die $smtp->message;
1066 $smtp->dataend() or die $smtp->message;
1067 $smtp->code =~ /250|200/ or die "Failed to send $subject\n".$smtp->message;
1070 printf (($dry_run ?
"Dry-" : "")."Sent %s\n", $subject);
1072 print (($dry_run ?
"Dry-" : "")."OK. Log says:\n");
1073 if ($smtp_server !~ m
#^/#) {
1074 print "Server: $smtp_server\n";
1075 print "MAIL FROM:<$raw_from>\n";
1076 foreach my $entry (@recipients) {
1077 print "RCPT TO:<$entry>\n";
1080 print "Sendmail: $smtp_server ".join(' ',@sendmail_parameters)."\n";
1082 print $header, "\n";
1084 print "Result: ", $smtp->code, ' ',
1085 ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
1087 print "Result: OK\n";
1094 $reply_to = $initial_reply_to;
1095 $references = $initial_reply_to || '';
1096 $subject = $initial_subject;
1099 foreach my $t (@files) {
1100 open(F
,"<",$t) or die "can't open file $t";
1103 my $author_encoding;
1104 my $has_content_type;
1108 my $input_format = undef;
1112 # First unfold multiline header fields
1115 if (/^\s+\S/ and @header) {
1116 chomp($header[$#header]);
1118 $header[$#header] .= $_;
1123 # Now parse the header
1126 $input_format = 'mbox';
1130 if (!defined $input_format && /^[-A-Za-z]+:\s/) {
1131 $input_format = 'mbox';
1134 if (defined $input_format && $input_format eq 'mbox') {
1135 if (/^Subject:\s+(.*)$/) {
1138 elsif (/^From:\s+(.*)$/) {
1139 ($author, $author_encoding) = unquote_rfc2047
($1);
1140 next if $suppress_cc{'author'};
1141 next if $suppress_cc{'self'} and $author eq $sender;
1142 printf("(mbox) Adding cc: %s from line '%s'\n",
1143 $1, $_) unless $quiet;
1146 elsif (/^Cc:\s+(.*)$/) {
1147 foreach my $addr (parse_address_line
($1)) {
1148 if (unquote_rfc2047
($addr) eq $sender) {
1149 next if ($suppress_cc{'self'});
1151 next if ($suppress_cc{'cc'});
1153 printf("(mbox) Adding cc: %s from line '%s'\n",
1154 $addr, $_) unless $quiet;
1158 elsif (/^Content-type:/i) {
1159 $has_content_type = 1;
1160 if (/charset="?([^ "]+)/) {
1161 $body_encoding = $1;
1165 elsif (/^Message-Id: (.*)/i) {
1168 elsif (!/^Date:\s/ && /^[-A-Za-z]+:\s+\S/) {
1173 # In the traditional
1174 # "send lots of email" format,
1177 # So let's support that, too.
1178 $input_format = 'lots';
1179 if (@cc == 0 && !$suppress_cc{'cc'}) {
1180 printf("(non-mbox) Adding cc: %s from line '%s'\n",
1181 $_, $_) unless $quiet;
1183 } elsif (!defined $subject) {
1188 # Now parse the message body
1191 if (/^(Signed-off-by|Cc): (.*)$/i) {
1193 my ($what, $c) = ($1, $2);
1195 if ($c eq $sender) {
1196 next if ($suppress_cc{'self'});
1198 next if $suppress_cc{'sob'} and $what =~ /Signed-off-by/i;
1199 next if $suppress_cc{'bodycc'} and $what =~ /Cc/i;
1202 printf("(body) Adding cc: %s from line '%s'\n",
1203 $c, $_) unless $quiet;
1208 if (defined $cc_cmd && !$suppress_cc{'cccmd'}) {
1209 open(F
, "$cc_cmd \Q$t\E |")
1210 or die "(cc-cmd) Could not execute '$cc_cmd'";
1215 next if ($c eq $sender and $suppress_from);
1217 printf("(cc-cmd) Adding cc: %s from: '%s'\n",
1218 $c, $cc_cmd) unless $quiet;
1221 or die "(cc-cmd) failed to close pipe to '$cc_cmd'";
1224 if (defined $author and $author ne $sender) {
1225 $message = "From: $author\n\n$message";
1226 if (defined $author_encoding) {
1227 if ($has_content_type) {
1228 if ($body_encoding eq $author_encoding) {
1229 # ok, we already have the right encoding
1232 # uh oh, we should re-encode
1237 'MIME-Version: 1.0',
1238 "Content-Type: text/plain; charset=$author_encoding",
1239 'Content-Transfer-Encoding: 8bit';
1245 $confirm eq "always" or
1246 ($confirm =~ /^(?:auto|cc)$/ && @cc) or
1247 ($confirm =~ /^(?:auto|compose)$/ && $compose && $message_num == 1));
1248 $needs_confirm = "inform" if ($needs_confirm && $confirm_unconfigured && @cc);
1250 @cc = (@initial_cc, @cc);
1252 my $message_was_sent = send_message
();
1254 # set up for the next message
1255 if ($thread && $message_was_sent &&
1256 (chain_reply_to
() || !defined $reply_to || length($reply_to) == 0)) {
1257 $reply_to = $message_id;
1258 if (length $references > 0) {
1259 $references .= "\n $message_id";
1261 $references = "$message_id";
1264 $message_id = undef;
1267 cleanup_compose_files
();
1269 sub cleanup_compose_files
() {
1270 unlink($compose_filename, $compose_filename . ".final") if $compose;
1273 $smtp->quit if $smtp;
1275 sub unique_email_list
(@
) {
1279 foreach my $entry (@_) {
1280 if (my $clean = extract_valid_address
($entry)) {
1281 $seen{$clean} ||= 0;
1282 next if $seen{$clean}++;
1283 push @emails, $entry;
1285 print STDERR
"W: unable to extract a valid address",
1292 sub validate_patch
{
1294 open(my $fh, '<', $fn)
1295 or die "unable to open $fn: $!\n";
1296 while (my $line = <$fh>) {
1297 if (length($line) > 998) {
1298 return "$.: patch contains a line longer than 998 characters";
1304 sub file_has_nonascii
{
1306 open(my $fh, '<', $fn)
1307 or die "unable to open $fn: $!\n";
1308 while (my $line = <$fh>) {
1309 return 1 if $line =~ /[^[:ascii:]]/;