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 --to <str> * Email To:
51 --cc <str> * Email Cc:
52 --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,@cc,@initial_cc,@bcclist,@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.
167 my $editor = Git
::command_oneline
('var', 'GIT_EDITOR');
170 if (defined($multiedit) && !$multiedit) {
172 system('sh', '-c', $editor.' "$@"', $editor, $_);
173 if (($?
& 127) || ($?
>> 8)) {
174 die("the editor exited uncleanly, aborting everything");
178 system('sh', '-c', $editor.' "$@"', $editor, @_);
179 if (($?
& 127) || ($?
>> 8)) {
180 die("the editor exited uncleanly, aborting everything");
185 # Variables with corresponding config settings
186 my ($thread, $chain_reply_to, $suppress_from, $signed_off_by_cc, $cc_cmd);
187 my ($smtp_server, $smtp_server_port, $smtp_authuser, $smtp_encryption);
188 my ($identity, $aliasfiletype, @alias_files, @smtp_host_parts, $smtp_domain);
189 my ($validate, $confirm);
192 my ($debug_net_smtp) = 0; # Net::SMTP, see send_message()
194 my $not_set_by_user = "true but not set by the user";
196 my %config_bool_settings = (
197 "thread" => [\
$thread, 1],
198 "chainreplyto" => [\
$chain_reply_to, $not_set_by_user],
199 "suppressfrom" => [\
$suppress_from, undef],
200 "signedoffbycc" => [\
$signed_off_by_cc, undef],
201 "signedoffcc" => [\
$signed_off_by_cc, undef], # Deprecated
202 "validate" => [\
$validate, 1],
205 my %config_settings = (
206 "smtpserver" => \
$smtp_server,
207 "smtpserverport" => \
$smtp_server_port,
208 "smtpuser" => \
$smtp_authuser,
209 "smtppass" => \
$smtp_authpass,
210 "smtpdomain" => \
$smtp_domain,
212 "cc" => \
@initial_cc,
214 "aliasfiletype" => \
$aliasfiletype,
216 "aliasesfile" => \
@alias_files,
217 "suppresscc" => \
@suppress_cc,
218 "envelopesender" => \
$envelope_sender,
219 "multiedit" => \
$multiedit,
220 "confirm" => \
$confirm,
224 # Help users prepare for 1.7.0
226 if (defined $chain_reply_to &&
227 $chain_reply_to eq $not_set_by_user) {
229 "In git 1.7.0, the default has changed to --no-chain-reply-to\n" .
230 "Set sendemail.chainreplyto configuration variable to true if\n" .
231 "you want to keep --chain-reply-to as your default.\n";
234 return $chain_reply_to;
237 # Handle Uncouth Termination
241 print color
("reset"), "\n";
243 # SMTP password masked
246 # tmp files from --compose
247 if (defined $compose_filename) {
248 if (-e
$compose_filename) {
249 print "'$compose_filename' contains an intermediate version of the email you were composing.\n";
251 if (-e
($compose_filename . ".final")) {
252 print "'$compose_filename.final' contains the composed email.\n"
259 $SIG{TERM
} = \
&signal_handler
;
260 $SIG{INT
} = \
&signal_handler
;
262 # Begin by accumulating all the variables (defined above), that we will end up
263 # needing, first, from the command line:
265 my $rc = GetOptions
("sender|from=s" => \
$sender,
266 "in-reply-to=s" => \
$initial_reply_to,
267 "subject=s" => \
$initial_subject,
269 "cc=s" => \
@initial_cc,
270 "bcc=s" => \
@bcclist,
271 "chain-reply-to!" => \
$chain_reply_to,
272 "smtp-server=s" => \
$smtp_server,
273 "smtp-server-port=s" => \
$smtp_server_port,
274 "smtp-user=s" => \
$smtp_authuser,
275 "smtp-pass:s" => \
$smtp_authpass,
276 "smtp-ssl" => sub { $smtp_encryption = 'ssl' },
277 "smtp-encryption=s" => \
$smtp_encryption,
278 "smtp-debug:i" => \
$debug_net_smtp,
279 "smtp-domain:s" => \
$smtp_domain,
280 "identity=s" => \
$identity,
281 "annotate" => \
$annotate,
282 "compose" => \
$compose,
284 "cc-cmd=s" => \
$cc_cmd,
285 "suppress-from!" => \
$suppress_from,
286 "suppress-cc=s" => \
@suppress_cc,
287 "signed-off-cc|signed-off-by-cc!" => \
$signed_off_by_cc,
288 "confirm=s" => \
$confirm,
289 "dry-run" => \
$dry_run,
290 "envelope-sender=s" => \
$envelope_sender,
291 "thread!" => \
$thread,
292 "validate!" => \
$validate,
293 "format-patch!" => \
$format_patch,
300 die "Cannot run git format-patch from outside a repository\n"
301 if $format_patch and not $repo;
303 # Now, let's fill any that aren't set in with defaults:
308 foreach my $setting (keys %config_bool_settings) {
309 my $target = $config_bool_settings{$setting}->[0];
310 $$target = Git
::config_bool
(@repo, "$prefix.$setting") unless (defined $$target);
313 foreach my $setting (keys %config_settings) {
314 my $target = $config_settings{$setting};
315 if (ref($target) eq "ARRAY") {
317 my @values = Git
::config
(@repo, "$prefix.$setting");
318 @
$target = @values if (@values && defined $values[0]);
322 $$target = Git
::config
(@repo, "$prefix.$setting") unless (defined $$target);
326 if (!defined $smtp_encryption) {
327 my $enc = Git
::config
(@repo, "$prefix.smtpencryption");
329 $smtp_encryption = $enc;
330 } elsif (Git
::config_bool
(@repo, "$prefix.smtpssl")) {
331 $smtp_encryption = 'ssl';
336 # read configuration from [sendemail "$identity"], fall back on [sendemail]
337 $identity = Git
::config
(@repo, "sendemail.identity") unless (defined $identity);
338 read_config
("sendemail.$identity") if (defined $identity);
339 read_config
("sendemail");
341 # fall back on builtin bool defaults
342 foreach my $setting (values %config_bool_settings) {
343 ${$setting->[0]} = $setting->[1] unless (defined (${$setting->[0]}));
346 # 'default' encryption is none -- this only prevents a warning
347 $smtp_encryption = '' unless (defined $smtp_encryption);
349 # Set CC suppressions
352 foreach my $entry (@suppress_cc) {
353 die "Unknown --suppress-cc field: '$entry'\n"
354 unless $entry =~ /^(all|cccmd|cc|author|self|sob|body|bodycc)$/;
355 $suppress_cc{$entry} = 1;
359 if ($suppress_cc{'all'}) {
360 foreach my $entry (qw
(cccmd cc author self sob body bodycc
)) {
361 $suppress_cc{$entry} = 1;
363 delete $suppress_cc{'all'};
366 # If explicit old-style ones are specified, they trump --suppress-cc.
367 $suppress_cc{'self'} = $suppress_from if defined $suppress_from;
368 $suppress_cc{'sob'} = !$signed_off_by_cc if defined $signed_off_by_cc;
370 if ($suppress_cc{'body'}) {
371 foreach my $entry (qw
(sob bodycc
)) {
372 $suppress_cc{$entry} = 1;
374 delete $suppress_cc{'body'};
377 # Set confirm's default value
378 my $confirm_unconfigured = !defined $confirm;
379 if ($confirm_unconfigured) {
380 $confirm = scalar %suppress_cc ?
'compose' : 'auto';
382 die "Unknown --confirm setting: '$confirm'\n"
383 unless $confirm =~ /^(?:auto|cc|compose|always|never)/;
385 # Debugging, print out the suppressions.
387 print "suppressions:\n";
388 foreach my $entry (keys %suppress_cc) {
389 printf " %-5s -> $suppress_cc{$entry}\n", $entry;
393 my ($repoauthor, $repocommitter);
394 ($repoauthor) = Git
::ident_person
(@repo, 'author');
395 ($repocommitter) = Git
::ident_person
(@repo, 'committer');
397 # Verify the user input
399 foreach my $entry (@to) {
400 die "Comma in --to entry: $entry'\n" unless $entry !~ m/,/;
403 foreach my $entry (@initial_cc) {
404 die "Comma in --cc entry: $entry'\n" unless $entry !~ m/,/;
407 foreach my $entry (@bcclist) {
408 die "Comma in --bcclist entry: $entry'\n" unless $entry !~ m/,/;
411 sub parse_address_line
{
412 if ($have_mail_address) {
413 return map { $_->format } Mail
::Address
->parse($_[0]);
415 return split_addrs
($_[0]);
420 return quotewords
('\s*,\s*', 1, @_);
425 # multiline formats can be supported in the future
426 mutt
=> sub { my $fh = shift; while (<$fh>) {
427 if (/^\s*alias\s+(?:-group\s+\S+\s+)*(\S+)\s+(.*)$/) {
428 my ($alias, $addr) = ($1, $2);
429 $addr =~ s/#.*$//; # mutt allows # comments
430 # commas delimit multiple addresses
431 $aliases{$alias} = [ split_addrs
($addr) ];
433 mailrc
=> sub { my $fh = shift; while (<$fh>) {
434 if (/^alias\s+(\S+)\s+(.*)$/) {
435 # spaces delimit multiple addresses
436 $aliases{$1} = [ quotewords
('\s+', 0, $2) ];
438 pine
=> sub { my $fh = shift; my $f='\t[^\t]*';
439 for (my $x = ''; defined($x); $x = $_) {
441 $x .= $1 while(defined($_ = <$fh>) && /^ +(.*)$/);
442 $x =~ /^(\S+)$f\t\(?([^\t]+?)\)?(:?$f){0,2}$/ or next;
443 $aliases{$1} = [ split_addrs
($2) ];
445 elm
=> sub { my $fh = shift;
447 if (/^(\S+)\s+=\s+[^=]+=\s(\S+)/) {
448 my ($alias, $addr) = ($1, $2);
449 $aliases{$alias} = [ split_addrs
($addr) ];
453 gnus
=> sub { my $fh = shift; while (<$fh>) {
454 if (/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) {
455 $aliases{$1} = [ $2 ];
459 if (@alias_files and $aliasfiletype and defined $parse_alias{$aliasfiletype}) {
460 foreach my $file (@alias_files) {
461 open my $fh, '<', $file or die "opening $file: $!\n";
462 $parse_alias{$aliasfiletype}->($fh);
467 ($sender) = expand_aliases
($sender) if defined $sender;
469 # returns 1 if the conflict must be solved using it as a format-patch argument
470 sub check_file_rev_conflict
($) {
474 $repo->command('rev-parse', '--verify', '--quiet', $f);
475 if (defined($format_patch)) {
476 return $format_patch;
479 File '$f' exists but it could also be the range of commits
480 to produce patches for. Please disambiguate by...
482 * Saying "./$f" if you mean a file; or
483 * Giving --format-patch option if you mean a range.
485 } catch Git
::Error
::Command with
{
490 # Now that all the defaults are set, process the rest of the command line
491 # arguments and collect up the files that need to be processed.
493 while (defined(my $f = shift @ARGV)) {
495 push @rev_list_opts, "--", @ARGV;
497 } elsif (-d
$f and !check_file_rev_conflict
($f)) {
499 or die "Failed to opendir $f: $!";
501 push @files, grep { -f
$_ } map { +$f . "/" . $_ }
504 } elsif ((-f
$f or -p
$f) and !check_file_rev_conflict
($f)) {
507 push @rev_list_opts, $f;
511 if (@rev_list_opts) {
512 die "Cannot run git format-patch from outside a repository\n"
514 push @files, $repo->command('format-patch', '-o', tempdir
(CLEANUP
=> 1), @rev_list_opts);
518 foreach my $f (@files) {
520 my $error = validate_patch
($f);
521 $error and die "fatal: $f: $error\nwarning: no patches were sent\n";
528 print $_,"\n" for (@files);
531 print STDERR
"\nNo patch files specified!\n\n";
535 sub get_patch_subject
($) {
537 open (my $fh, '<', $fn);
538 while (my $line = <$fh>) {
539 next unless ($line =~ /^Subject: (.*)$/);
544 die "No subject line in $fn ?";
548 # Note that this does not need to be secure, but we will make a small
549 # effort to have it be unique
550 $compose_filename = ($repo ?
551 tempfile
(".gitsendemail.msg.XXXXXX", DIR
=> $repo->repo_path()) :
552 tempfile
(".gitsendemail.msg.XXXXXX", DIR
=> "."))[1];
553 open(C
,">",$compose_filename)
554 or die "Failed to open for writing $compose_filename: $!";
557 my $tpl_sender = $sender || $repoauthor || $repocommitter || '';
558 my $tpl_subject = $initial_subject || '';
559 my $tpl_reply_to = $initial_reply_to || '';
562 From $tpl_sender # This line is ignored.
563 GIT: Lines beginning in "GIT:" will be removed.
564 GIT: Consider including an overall diffstat or table of contents
565 GIT: for the patch you are writing.
567 GIT: Clear the body content if you don't wish to send a summary.
569 Subject: $tpl_subject
570 In-Reply-To: $tpl_reply_to
574 print C get_patch_subject
($f);
579 do_edit
($compose_filename, @files);
581 do_edit
($compose_filename);
584 open(C2
,">",$compose_filename . ".final")
585 or die "Failed to open $compose_filename.final : " . $!;
587 open(C
,"<",$compose_filename)
588 or die "Failed to open $compose_filename : " . $!;
590 my $need_8bit_cte = file_has_nonascii
($compose_filename);
592 my $summary_empty = 1;
596 $summary_empty = 0 unless (/^\n$/);
599 if ($need_8bit_cte) {
600 print C2
"MIME-Version: 1.0\n",
601 "Content-Type: text/plain; ",
603 "Content-Transfer-Encoding: 8bit\n";
605 } elsif (/^MIME-Version:/i) {
607 } elsif (/^Subject:\s*(.+)\s*$/i) {
608 $initial_subject = $1;
609 my $subject = $initial_subject;
611 ($subject =~ /[^[:ascii:]]/ ?
612 quote_rfc2047
($subject) :
615 } elsif (/^In-Reply-To:\s*(.+)\s*$/i) {
616 $initial_reply_to = $1;
618 } elsif (/^From:\s*(.+)\s*$/i) {
621 } elsif (/^(?:To|Cc|Bcc):/i) {
622 print "To/Cc/Bcc fields are not interpreted yet, they have been ignored\n";
630 if ($summary_empty) {
631 print "Summary email is empty, skipping it\n";
634 } elsif ($annotate) {
639 my ($prompt, %arg) = @_;
640 my $valid_re = $arg{valid_re
};
641 my $default = $arg{default};
644 return defined $default ?
$default : undef
645 unless defined $term->IN and defined fileno($term->IN) and
646 defined $term->OUT and defined fileno($term->OUT);
648 $resp = $term->readline($prompt);
649 if (!defined $resp) { # EOF
651 return defined $default ?
$default : undef;
653 if ($resp eq '' and defined $default) {
656 if (!defined $valid_re or $resp =~ /$valid_re/) {
664 if (!defined $sender) {
665 $sender = $repoauthor || $repocommitter || '';
666 $sender = ask
("Who should the emails appear to be from? [$sender] ",
668 print "Emails will be sent from: ", $sender, "\n";
673 my $to = ask
("Who should the emails be sent to? ");
674 push @to, parse_address_line
($to) if defined $to; # sanitized/validated later
679 return map { expand_one_alias
($_) } @_;
682 my %EXPANDED_ALIASES;
683 sub expand_one_alias
{
685 if ($EXPANDED_ALIASES{$alias}) {
686 die "fatal: alias '$alias' expands to itself\n";
688 local $EXPANDED_ALIASES{$alias} = 1;
689 return $aliases{$alias} ? expand_aliases
(@
{$aliases{$alias}}) : $alias;
692 @to = expand_aliases
(@to);
693 @to = (map { sanitize_address
($_) } @to);
694 @initial_cc = expand_aliases
(@initial_cc);
695 @bcclist = expand_aliases
(@bcclist);
697 if ($thread && !defined $initial_reply_to && $prompting) {
698 $initial_reply_to = ask
(
699 "Message-ID to be used as In-Reply-To for the first email? ");
701 if (defined $initial_reply_to) {
702 $initial_reply_to =~ s/^\s*<?//;
703 $initial_reply_to =~ s/>?\s*$//;
704 $initial_reply_to = "<$initial_reply_to>" if $initial_reply_to ne '';
707 if (!defined $smtp_server) {
708 foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
714 $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
717 if ($compose && $compose > 0) {
718 @files = ($compose_filename . ".final", @files);
721 # Variables we set as part of the loop over files
722 our ($message_id, %mail, $subject, $reply_to, $references, $message,
723 $needs_confirm, $message_num, $ask_default);
725 sub extract_valid_address
{
727 my $local_part_regexp = '[^<>"\s@]+';
728 my $domain_regexp = '[^.<>"\s@]+(?:\.[^.<>"\s@]+)+';
730 # check for a local address:
731 return $address if ($address =~ /^($local_part_regexp)$/);
733 $address =~ s/^\s*<(.*)>\s*$/$1/;
734 if ($have_email_valid) {
735 return scalar Email
::Valid
->address($address);
737 # less robust/correct than the monster regexp in Email::Valid,
738 # but still does a 99% job, and one less dependency
739 $address =~ /($local_part_regexp\@$domain_regexp)/;
744 # Usually don't need to change anything below here.
746 # we make a "fake" message id by taking the current number
747 # of seconds since the beginning of Unix time and tacking on
748 # a random number to the end, in case we are called quicker than
749 # 1 second since the last time we were called.
751 # We'll setup a template for the message id, using the "from" address:
753 my ($message_id_stamp, $message_id_serial);
754 sub make_message_id
{
756 if (!defined $message_id_stamp) {
757 $message_id_stamp = sprintf("%s-%s", time, $$);
758 $message_id_serial = 0;
760 $message_id_serial++;
761 $uniq = "$message_id_stamp-$message_id_serial";
764 for ($sender, $repocommitter, $repoauthor) {
765 $du_part = extract_valid_address
(sanitize_address
($_));
766 last if (defined $du_part and $du_part ne '');
768 if (not defined $du_part or $du_part eq '') {
769 use Sys
::Hostname
qw();
770 $du_part = 'user@' . Sys
::Hostname
::hostname
();
772 my $message_id_template = "<%s-git-send-email-%s>";
773 $message_id = sprintf($message_id_template, $uniq, $du_part);
774 #print "new message id = $message_id\n"; # Was useful for debugging
779 $time = time - scalar $#files;
781 sub unquote_rfc2047
{
784 if (s/=\?([^?]+)\?q\?(.*)\?=/$2/g) {
787 s/=([0-9A-F]{2})/chr(hex($1))/eg;
789 return wantarray ?
($_, $encoding) : $_;
794 my $encoding = shift || 'UTF-8';
795 s/([^-a-zA-Z0-9!*+\/])/sprintf
("=%02X", ord($1))/eg
;
796 s/(.*)/=\?$encoding\?q\?$1\?=/;
800 sub is_rfc2047_quoted
{
802 my $token = '[^][()<>@,;:"\/?.= \000-\037\177-\377]+';
803 my $encoded_text = '[!->@-~]+';
805 $s =~ m/^(?:"[[:ascii:]]*"|=\?$token\?$token\?$encoded_text\?=)$/o;
808 # use the simplest quoting being able to handle the recipient
809 sub sanitize_address
{
810 my ($recipient) = @_;
811 my ($recipient_name, $recipient_addr) = ($recipient =~ /^(.*?)\s*(<.*)/);
813 if (not $recipient_name) {
817 # if recipient_name is already quoted, do nothing
818 if (is_rfc2047_quoted
($recipient_name)) {
822 # rfc2047 is needed if a non-ascii char is included
823 if ($recipient_name =~ /[^[:ascii:]]/) {
824 $recipient_name =~ s/^"(.*)"$/$1/;
825 $recipient_name = quote_rfc2047
($recipient_name);
828 # double quotes are needed if specials or CTLs are included
829 elsif ($recipient_name =~ /[][()<>@,;:\\".\000-\037\177]/) {
830 $recipient_name =~ s/(["\\\r])/\\$1/g;
831 $recipient_name = "\"$recipient_name\"";
834 return "$recipient_name $recipient_addr";
838 # Returns the local Fully Qualified Domain Name (FQDN) if available.
840 # Tightly configured MTAa require that a caller sends a real DNS
841 # domain name that corresponds the IP address in the HELO/EHLO
842 # handshake. This is used to verify the connection and prevent
843 # spammers from trying to hide their identity. If the DNS and IP don't
844 # match, the receiveing MTA may deny the connection.
846 # Here is a deny example of Net::SMTP with the default "localhost.localdomain"
848 # Net::SMTP=GLOB(0x267ec28)>>> EHLO localhost.localdomain
849 # Net::SMTP=GLOB(0x267ec28)<<< 550 EHLO argument does not match calling host
851 # This maildomain*() code is based on ideas in Perl library Test::Reporter
852 # /usr/share/perl5/Test/Reporter/Mail/Util.pm ==> sub _maildomain ()
856 return !($^O
eq 'darwin' && $domain =~ /\.local$/) && $domain =~ /\./;
862 if (eval { require Net
::Domain
; 1 }) {
863 my $domain = Net
::Domain
::domainname
();
864 $maildomain = $domain if valid_fqdn
($domain);
873 if (eval { require Net
::SMTP
; 1 }) {
874 for my $host (qw(mailhost localhost)) {
875 my $smtp = Net
::SMTP
->new($host);
877 my $domain = $smtp->domain;
880 $maildomain = $domain if valid_fqdn
($domain);
891 return maildomain_net
() || maildomain_mta
() || 'localhost.localdomain';
894 # Returns 1 if the message was sent, and 0 otherwise.
895 # In actuality, the whole program dies when there
896 # is an error sending a message.
899 my @recipients = unique_email_list
(@to);
900 @cc = (grep { my $cc = extract_valid_address
($_);
901 not grep { $cc eq $_ } @recipients
903 map { sanitize_address
($_) }
905 my $to = join (",\n\t", @recipients);
906 @recipients = unique_email_list
(@recipients,@cc,@bcclist);
907 @recipients = (map { extract_valid_address
($_) } @recipients);
908 my $date = format_2822_time
($time++);
909 my $gitversion = '@@GIT_VERSION@@';
910 if ($gitversion =~ m/..GIT_VERSION../) {
911 $gitversion = Git
::version
();
914 my $cc = join(",\n\t", unique_email_list
(@cc));
917 $ccline = "\nCc: $cc";
919 my $sanitized_sender = sanitize_address
($sender);
920 make_message_id
() unless defined($message_id);
922 my $header = "From: $sanitized_sender
926 Message-Id: $message_id
927 X-Mailer: git-send-email $gitversion
931 $header .= "In-Reply-To: $reply_to\n";
932 $header .= "References: $references\n";
935 $header .= join("\n", @xh) . "\n";
938 my @sendmail_parameters = ('-i', @recipients);
939 my $raw_from = $sanitized_sender;
940 if (defined $envelope_sender && $envelope_sender ne "auto") {
941 $raw_from = $envelope_sender;
943 $raw_from = extract_valid_address
($raw_from);
944 unshift (@sendmail_parameters,
945 '-f', $raw_from) if(defined $envelope_sender);
947 if ($needs_confirm && !$dry_run) {
949 if ($needs_confirm eq "inform") {
950 $confirm_unconfigured = 0; # squelch this message for the rest of this run
951 $ask_default = "y"; # assume yes on EOF since user hasn't explicitly asked for confirmation
952 print " The Cc list above has been expanded by additional\n";
953 print " addresses found in the patch commit message. By default\n";
954 print " send-email prompts before sending whenever this occurs.\n";
955 print " This behavior is controlled by the sendemail.confirm\n";
956 print " configuration setting.\n";
958 print " For additional information, run 'git send-email --help'.\n";
959 print " To retain the current behavior, but squelch this message,\n";
960 print " run 'git config --global sendemail.confirm auto'.\n\n";
962 $_ = ask
("Send this email? ([y]es|[n]o|[q]uit|[a]ll): ",
963 valid_re
=> qr/^(?:yes|y|no|n|quit|q|all|a)/i,
964 default => $ask_default);
965 die "Send this email reply required" unless defined $_;
969 cleanup_compose_files
();
977 # We don't want to send the email.
978 } elsif ($smtp_server =~ m
#^/#) {
979 my $pid = open my $sm, '|-';
980 defined $pid or die $!;
982 exec($smtp_server, @sendmail_parameters) or die $!;
984 print $sm "$header\n$message";
988 if (!defined $smtp_server) {
989 die "The required SMTP server is not properly defined."
992 if ($smtp_encryption eq 'ssl') {
993 $smtp_server_port ||= 465; # ssmtp
994 require Net
::SMTP
::SSL
;
995 $smtp_domain ||= maildomain
();
996 $smtp ||= Net
::SMTP
::SSL
->new($smtp_server,
997 Hello
=> $smtp_domain,
998 Port
=> $smtp_server_port);
1002 $smtp_domain ||= maildomain
();
1003 $smtp ||= Net
::SMTP
->new((defined $smtp_server_port)
1004 ?
"$smtp_server:$smtp_server_port"
1006 Hello
=> $smtp_domain,
1007 Debug
=> $debug_net_smtp);
1008 if ($smtp_encryption eq 'tls' && $smtp) {
1009 require Net
::SMTP
::SSL
;
1010 $smtp->command('STARTTLS');
1012 if ($smtp->code == 220) {
1013 $smtp = Net
::SMTP
::SSL
->start_SSL($smtp)
1014 or die "STARTTLS failed! ".$smtp->message;
1015 $smtp_encryption = '';
1016 # Send EHLO again to receive fresh
1017 # supported commands
1020 die "Server does not support STARTTLS! ".$smtp->message;
1026 die "Unable to initialize SMTP properly. Check config and use --smtp-debug. ",
1027 "VALUES: server=$smtp_server ",
1028 "encryption=$smtp_encryption ",
1029 "hello=$smtp_domain",
1030 defined $smtp_server_port ?
"port=$smtp_server_port" : "";
1033 if (defined $smtp_authuser) {
1035 if (!defined $smtp_authpass) {
1037 system "stty -echo";
1043 } while (!defined $_);
1045 chomp($smtp_authpass = $_);
1050 $auth ||= $smtp->auth( $smtp_authuser, $smtp_authpass ) or die $smtp->message;
1053 $smtp->mail( $raw_from ) or die $smtp->message;
1054 $smtp->to( @recipients ) or die $smtp->message;
1055 $smtp->data or die $smtp->message;
1056 $smtp->datasend("$header\n$message") or die $smtp->message;
1057 $smtp->dataend() or die $smtp->message;
1058 $smtp->code =~ /250|200/ or die "Failed to send $subject\n".$smtp->message;
1061 printf (($dry_run ?
"Dry-" : "")."Sent %s\n", $subject);
1063 print (($dry_run ?
"Dry-" : "")."OK. Log says:\n");
1064 if ($smtp_server !~ m
#^/#) {
1065 print "Server: $smtp_server\n";
1066 print "MAIL FROM:<$raw_from>\n";
1067 foreach my $entry (@recipients) {
1068 print "RCPT TO:<$entry>\n";
1071 print "Sendmail: $smtp_server ".join(' ',@sendmail_parameters)."\n";
1073 print $header, "\n";
1075 print "Result: ", $smtp->code, ' ',
1076 ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
1078 print "Result: OK\n";
1085 $reply_to = $initial_reply_to;
1086 $references = $initial_reply_to || '';
1087 $subject = $initial_subject;
1090 foreach my $t (@files) {
1091 open(F
,"<",$t) or die "can't open file $t";
1094 my $author_encoding;
1095 my $has_content_type;
1099 my $input_format = undef;
1103 # First unfold multiline header fields
1106 if (/^\s+\S/ and @header) {
1107 chomp($header[$#header]);
1109 $header[$#header] .= $_;
1114 # Now parse the header
1117 $input_format = 'mbox';
1121 if (!defined $input_format && /^[-A-Za-z]+:\s/) {
1122 $input_format = 'mbox';
1125 if (defined $input_format && $input_format eq 'mbox') {
1126 if (/^Subject:\s+(.*)$/) {
1129 elsif (/^From:\s+(.*)$/) {
1130 ($author, $author_encoding) = unquote_rfc2047
($1);
1131 next if $suppress_cc{'author'};
1132 next if $suppress_cc{'self'} and $author eq $sender;
1133 printf("(mbox) Adding cc: %s from line '%s'\n",
1134 $1, $_) unless $quiet;
1137 elsif (/^Cc:\s+(.*)$/) {
1138 foreach my $addr (parse_address_line
($1)) {
1139 if (unquote_rfc2047
($addr) eq $sender) {
1140 next if ($suppress_cc{'self'});
1142 next if ($suppress_cc{'cc'});
1144 printf("(mbox) Adding cc: %s from line '%s'\n",
1145 $addr, $_) unless $quiet;
1149 elsif (/^Content-type:/i) {
1150 $has_content_type = 1;
1151 if (/charset="?([^ "]+)/) {
1152 $body_encoding = $1;
1156 elsif (/^Message-Id: (.*)/i) {
1159 elsif (!/^Date:\s/ && /^[-A-Za-z]+:\s+\S/) {
1164 # In the traditional
1165 # "send lots of email" format,
1168 # So let's support that, too.
1169 $input_format = 'lots';
1170 if (@cc == 0 && !$suppress_cc{'cc'}) {
1171 printf("(non-mbox) Adding cc: %s from line '%s'\n",
1172 $_, $_) unless $quiet;
1174 } elsif (!defined $subject) {
1179 # Now parse the message body
1182 if (/^(Signed-off-by|Cc): (.*)$/i) {
1184 my ($what, $c) = ($1, $2);
1186 if ($c eq $sender) {
1187 next if ($suppress_cc{'self'});
1189 next if $suppress_cc{'sob'} and $what =~ /Signed-off-by/i;
1190 next if $suppress_cc{'bodycc'} and $what =~ /Cc/i;
1193 printf("(body) Adding cc: %s from line '%s'\n",
1194 $c, $_) unless $quiet;
1199 if (defined $cc_cmd && !$suppress_cc{'cccmd'}) {
1200 open(F
, "$cc_cmd \Q$t\E |")
1201 or die "(cc-cmd) Could not execute '$cc_cmd'";
1206 next if ($c eq $sender and $suppress_from);
1208 printf("(cc-cmd) Adding cc: %s from: '%s'\n",
1209 $c, $cc_cmd) unless $quiet;
1212 or die "(cc-cmd) failed to close pipe to '$cc_cmd'";
1215 if (defined $author and $author ne $sender) {
1216 $message = "From: $author\n\n$message";
1217 if (defined $author_encoding) {
1218 if ($has_content_type) {
1219 if ($body_encoding eq $author_encoding) {
1220 # ok, we already have the right encoding
1223 # uh oh, we should re-encode
1228 'MIME-Version: 1.0',
1229 "Content-Type: text/plain; charset=$author_encoding",
1230 'Content-Transfer-Encoding: 8bit';
1236 $confirm eq "always" or
1237 ($confirm =~ /^(?:auto|cc)$/ && @cc) or
1238 ($confirm =~ /^(?:auto|compose)$/ && $compose && $message_num == 1));
1239 $needs_confirm = "inform" if ($needs_confirm && $confirm_unconfigured && @cc);
1241 @cc = (@initial_cc, @cc);
1243 my $message_was_sent = send_message
();
1245 # set up for the next message
1246 if ($thread && $message_was_sent &&
1247 (chain_reply_to
() || !defined $reply_to || length($reply_to) == 0)) {
1248 $reply_to = $message_id;
1249 if (length $references > 0) {
1250 $references .= "\n $message_id";
1252 $references = "$message_id";
1255 $message_id = undef;
1258 cleanup_compose_files
();
1260 sub cleanup_compose_files
() {
1261 unlink($compose_filename, $compose_filename . ".final") if $compose;
1264 $smtp->quit if $smtp;
1266 sub unique_email_list
(@
) {
1270 foreach my $entry (@_) {
1271 if (my $clean = extract_valid_address
($entry)) {
1272 $seen{$clean} ||= 0;
1273 next if $seen{$clean}++;
1274 push @emails, $entry;
1276 print STDERR
"W: unable to extract a valid address",
1283 sub validate_patch
{
1285 open(my $fh, '<', $fn)
1286 or die "unable to open $fn: $!\n";
1287 while (my $line = <$fh>) {
1288 if (length($line) > 998) {
1289 return "$.: patch contains a line longer than 998 characters";
1295 sub file_has_nonascii
{
1297 open(my $fh, '<', $fn)
1298 or die "unable to open $fn: $!\n";
1299 while (my $line = <$fh>) {
1300 return 1 if $line =~ /[^[:ascii:]]/;