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 /;
27 use File
::Spec
::Functions
qw(catfile);
31 Getopt
::Long
::Configure qw
/ pass_through /;
35 my ($class, $reason) = @_;
36 return bless \
$reason, shift;
40 die "Cannot use readline on FakeTerm: $$self";
47 git send-email [options] <file | directory | rev-list options >
50 --from <str> * Email From:
51 --[no-]to <str> * Email To:
52 --[no-]cc <str> * Email Cc:
53 --[no-]bcc <str> * Email Bcc:
54 --subject <str> * Email "Subject:"
55 --in-reply-to <str> * Email "In-Reply-To:"
56 --annotate * Review each patch that will be sent in an editor.
57 --compose * Open an editor for introduction.
58 --8bit-encoding <str> * Encoding to assume 8bit mails if undeclared
61 --envelope-sender <str> * Email envelope sender.
62 --smtp-server <str:int> * Outgoing SMTP server to use. The port
63 is optional. Default 'localhost'.
64 --smtp-server-port <int> * Outgoing SMTP server port.
65 --smtp-user <str> * Username for SMTP-AUTH.
66 --smtp-pass <str> * Password for SMTP-AUTH; not necessary.
67 --smtp-encryption <str> * tls or ssl; anything else disables.
68 --smtp-ssl * Deprecated. Use '--smtp-encryption ssl'.
69 --smtp-domain <str> * The domain name sent to HELO/EHLO handshake
70 --smtp-debug <0|1> * Disable, enable Net::SMTP debug.
73 --identity <str> * Use the sendemail.<id> options.
74 --cc-cmd <str> * Email Cc: via `<str> \$patch_path`
75 --suppress-cc <str> * author, self, sob, cc, cccmd, body, bodycc, all.
76 --[no-]signed-off-by-cc * Send to Signed-off-by: addresses. Default on.
77 --[no-]suppress-from * Send to self. Default off.
78 --[no-]chain-reply-to * Chain In-Reply-To: fields. Default off.
79 --[no-]thread * Use In-Reply-To: field. Default on.
82 --confirm <str> * Confirm recipients before sending;
83 auto, cc, compose, always, or never.
84 --quiet * Output one line of info per email.
85 --dry-run * Don't actually send the emails.
86 --[no-]validate * Perform patch sanity checks. Default on.
87 --[no-]format-patch * understand any non optional arguments as
88 `git format-patch` ones.
89 --force * Send even if safety checks would prevent it.
95 # most mail servers generate the Date: header, but not all...
96 sub format_2822_time
{
98 my @localtm = localtime($time);
99 my @gmttm = gmtime($time);
100 my $localmin = $localtm[1] + $localtm[2] * 60;
101 my $gmtmin = $gmttm[1] + $gmttm[2] * 60;
102 if ($localtm[0] != $gmttm[0]) {
103 die "local zone differs from GMT by a non-minute interval\n";
105 if ((($gmttm[6] + 1) % 7) == $localtm[6]) {
107 } elsif ((($gmttm[6] - 1) % 7) == $localtm[6]) {
109 } elsif ($gmttm[6] != $localtm[6]) {
110 die "local time offset greater than or equal to 24 hours\n";
112 my $offset = $localmin - $gmtmin;
113 my $offhour = $offset / 60;
114 my $offmin = abs($offset % 60);
115 if (abs($offhour) >= 24) {
116 die ("local time offset greater than or equal to 24 hours\n");
119 return sprintf("%s, %2d %s %d %02d:%02d:%02d %s%02d%02d",
120 qw(Sun Mon Tue Wed Thu Fri Sat)[$localtm[6]],
122 qw(Jan Feb Mar Apr May Jun
123 Jul Aug Sep Oct Nov Dec)[$localtm[4]],
128 ($offset >= 0) ?
'+' : '-',
134 my $have_email_valid = eval { require Email
::Valid
; 1 };
135 my $have_mail_address = eval { require Mail
::Address
; 1 };
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;
166 # Handle interactive edition of files.
171 if (!defined($editor)) {
172 $editor = Git
::command_oneline
('var', 'GIT_EDITOR');
174 if (defined($multiedit) && !$multiedit) {
176 system('sh', '-c', $editor.' "$@"', $editor, $_);
177 if (($?
& 127) || ($?
>> 8)) {
178 die("the editor exited uncleanly, aborting everything");
182 system('sh', '-c', $editor.' "$@"', $editor, @_);
183 if (($?
& 127) || ($?
>> 8)) {
184 die("the editor exited uncleanly, aborting everything");
189 # Variables with corresponding config settings
190 my ($thread, $chain_reply_to, $suppress_from, $signed_off_by_cc, $cc_cmd);
191 my ($smtp_server, $smtp_server_port, $smtp_authuser, $smtp_encryption);
192 my ($identity, $aliasfiletype, @alias_files, @smtp_host_parts, $smtp_domain);
193 my ($validate, $confirm);
195 my ($auto_8bit_encoding);
197 my ($debug_net_smtp) = 0; # Net::SMTP, see send_message()
199 my $not_set_by_user = "true but not set by the user";
201 my %config_bool_settings = (
202 "thread" => [\
$thread, 1],
203 "chainreplyto" => [\
$chain_reply_to, $not_set_by_user],
204 "suppressfrom" => [\
$suppress_from, undef],
205 "signedoffbycc" => [\
$signed_off_by_cc, undef],
206 "signedoffcc" => [\
$signed_off_by_cc, undef], # Deprecated
207 "validate" => [\
$validate, 1],
210 my %config_settings = (
211 "smtpserver" => \
$smtp_server,
212 "smtpserverport" => \
$smtp_server_port,
213 "smtpuser" => \
$smtp_authuser,
214 "smtppass" => \
$smtp_authpass,
215 "smtpdomain" => \
$smtp_domain,
217 "cc" => \
@initial_cc,
219 "aliasfiletype" => \
$aliasfiletype,
221 "aliasesfile" => \
@alias_files,
222 "suppresscc" => \
@suppress_cc,
223 "envelopesender" => \
$envelope_sender,
224 "multiedit" => \
$multiedit,
225 "confirm" => \
$confirm,
227 "assume8bitencoding" => \
$auto_8bit_encoding,
230 # Help users prepare for 1.7.0
232 if (defined $chain_reply_to &&
233 $chain_reply_to eq $not_set_by_user) {
235 "In git 1.7.0, the default has changed to --no-chain-reply-to\n" .
236 "Set sendemail.chainreplyto configuration variable to true if\n" .
237 "you want to keep --chain-reply-to as your default.\n";
240 return $chain_reply_to;
243 # Handle Uncouth Termination
247 print color
("reset"), "\n";
249 # SMTP password masked
252 # tmp files from --compose
253 if (defined $compose_filename) {
254 if (-e
$compose_filename) {
255 print "'$compose_filename' contains an intermediate version of the email you were composing.\n";
257 if (-e
($compose_filename . ".final")) {
258 print "'$compose_filename.final' contains the composed email.\n"
265 $SIG{TERM
} = \
&signal_handler
;
266 $SIG{INT
} = \
&signal_handler
;
268 # Begin by accumulating all the variables (defined above), that we will end up
269 # needing, first, from the command line:
271 my $rc = GetOptions
("sender|from=s" => \
$sender,
272 "in-reply-to=s" => \
$initial_reply_to,
273 "subject=s" => \
$initial_subject,
276 "cc=s" => \
@initial_cc,
278 "bcc=s" => \
@bcclist,
279 "no-bcc" => \
$no_bcc,
280 "chain-reply-to!" => \
$chain_reply_to,
281 "smtp-server=s" => \
$smtp_server,
282 "smtp-server-port=s" => \
$smtp_server_port,
283 "smtp-user=s" => \
$smtp_authuser,
284 "smtp-pass:s" => \
$smtp_authpass,
285 "smtp-ssl" => sub { $smtp_encryption = 'ssl' },
286 "smtp-encryption=s" => \
$smtp_encryption,
287 "smtp-debug:i" => \
$debug_net_smtp,
288 "smtp-domain:s" => \
$smtp_domain,
289 "identity=s" => \
$identity,
290 "annotate" => \
$annotate,
291 "compose" => \
$compose,
293 "cc-cmd=s" => \
$cc_cmd,
294 "suppress-from!" => \
$suppress_from,
295 "suppress-cc=s" => \
@suppress_cc,
296 "signed-off-cc|signed-off-by-cc!" => \
$signed_off_by_cc,
297 "confirm=s" => \
$confirm,
298 "dry-run" => \
$dry_run,
299 "envelope-sender=s" => \
$envelope_sender,
300 "thread!" => \
$thread,
301 "validate!" => \
$validate,
302 "format-patch!" => \
$format_patch,
303 "8bit-encoding=s" => \
$auto_8bit_encoding,
311 die "Cannot run git format-patch from outside a repository\n"
312 if $format_patch and not $repo;
314 # Now, let's fill any that aren't set in with defaults:
319 foreach my $setting (keys %config_bool_settings) {
320 my $target = $config_bool_settings{$setting}->[0];
321 $$target = Git
::config_bool
(@repo, "$prefix.$setting") unless (defined $$target);
324 foreach my $setting (keys %config_settings) {
325 my $target = $config_settings{$setting};
326 next if $setting eq "to" and defined $no_to;
327 next if $setting eq "cc" and defined $no_cc;
328 next if $setting eq "bcc" and defined $no_bcc;
329 if (ref($target) eq "ARRAY") {
331 my @values = Git
::config
(@repo, "$prefix.$setting");
332 @
$target = @values if (@values && defined $values[0]);
336 $$target = Git
::config
(@repo, "$prefix.$setting") unless (defined $$target);
340 if (!defined $smtp_encryption) {
341 my $enc = Git
::config
(@repo, "$prefix.smtpencryption");
343 $smtp_encryption = $enc;
344 } elsif (Git
::config_bool
(@repo, "$prefix.smtpssl")) {
345 $smtp_encryption = 'ssl';
350 # read configuration from [sendemail "$identity"], fall back on [sendemail]
351 $identity = Git
::config
(@repo, "sendemail.identity") unless (defined $identity);
352 read_config
("sendemail.$identity") if (defined $identity);
353 read_config
("sendemail");
355 # fall back on builtin bool defaults
356 foreach my $setting (values %config_bool_settings) {
357 ${$setting->[0]} = $setting->[1] unless (defined (${$setting->[0]}));
360 # 'default' encryption is none -- this only prevents a warning
361 $smtp_encryption = '' unless (defined $smtp_encryption);
363 # Set CC suppressions
366 foreach my $entry (@suppress_cc) {
367 die "Unknown --suppress-cc field: '$entry'\n"
368 unless $entry =~ /^(?:all|cccmd|cc|author|self|sob|body|bodycc)$/;
369 $suppress_cc{$entry} = 1;
373 if ($suppress_cc{'all'}) {
374 foreach my $entry (qw
(cccmd cc author self sob body bodycc
)) {
375 $suppress_cc{$entry} = 1;
377 delete $suppress_cc{'all'};
380 # If explicit old-style ones are specified, they trump --suppress-cc.
381 $suppress_cc{'self'} = $suppress_from if defined $suppress_from;
382 $suppress_cc{'sob'} = !$signed_off_by_cc if defined $signed_off_by_cc;
384 if ($suppress_cc{'body'}) {
385 foreach my $entry (qw
(sob bodycc
)) {
386 $suppress_cc{$entry} = 1;
388 delete $suppress_cc{'body'};
391 # Set confirm's default value
392 my $confirm_unconfigured = !defined $confirm;
393 if ($confirm_unconfigured) {
394 $confirm = scalar %suppress_cc ?
'compose' : 'auto';
396 die "Unknown --confirm setting: '$confirm'\n"
397 unless $confirm =~ /^(?:auto|cc|compose|always|never)/;
399 # Debugging, print out the suppressions.
401 print "suppressions:\n";
402 foreach my $entry (keys %suppress_cc) {
403 printf " %-5s -> $suppress_cc{$entry}\n", $entry;
407 my ($repoauthor, $repocommitter);
408 ($repoauthor) = Git
::ident_person
(@repo, 'author');
409 ($repocommitter) = Git
::ident_person
(@repo, 'committer');
411 # Verify the user input
413 foreach my $entry (@to) {
414 die "Comma in --to entry: $entry'\n" unless $entry !~ m/,/;
417 foreach my $entry (@initial_cc) {
418 die "Comma in --cc entry: $entry'\n" unless $entry !~ m/,/;
421 foreach my $entry (@bcclist) {
422 die "Comma in --bcclist entry: $entry'\n" unless $entry !~ m/,/;
425 sub parse_address_line
{
426 if ($have_mail_address) {
427 return map { $_->format } Mail
::Address
->parse($_[0]);
429 return split_addrs
($_[0]);
434 return quotewords
('\s*,\s*', 1, @_);
439 # multiline formats can be supported in the future
440 mutt
=> sub { my $fh = shift; while (<$fh>) {
441 if (/^\s*alias\s+(?:-group\s+\S+\s+)*(\S+)\s+(.*)$/) {
442 my ($alias, $addr) = ($1, $2);
443 $addr =~ s/#.*$//; # mutt allows # comments
444 # commas delimit multiple addresses
445 $aliases{$alias} = [ split_addrs
($addr) ];
447 mailrc
=> sub { my $fh = shift; while (<$fh>) {
448 if (/^alias\s+(\S+)\s+(.*)$/) {
449 # spaces delimit multiple addresses
450 $aliases{$1} = [ quotewords
('\s+', 0, $2) ];
452 pine
=> sub { my $fh = shift; my $f='\t[^\t]*';
453 for (my $x = ''; defined($x); $x = $_) {
455 $x .= $1 while(defined($_ = <$fh>) && /^ +(.*)$/);
456 $x =~ /^(\S+)$f\t\(?([^\t]+?)\)?(:?$f){0,2}$/ or next;
457 $aliases{$1} = [ split_addrs
($2) ];
459 elm
=> sub { my $fh = shift;
461 if (/^(\S+)\s+=\s+[^=]+=\s(\S+)/) {
462 my ($alias, $addr) = ($1, $2);
463 $aliases{$alias} = [ split_addrs
($addr) ];
467 gnus
=> sub { my $fh = shift; while (<$fh>) {
468 if (/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) {
469 $aliases{$1} = [ $2 ];
473 if (@alias_files and $aliasfiletype and defined $parse_alias{$aliasfiletype}) {
474 foreach my $file (@alias_files) {
475 open my $fh, '<', $file or die "opening $file: $!\n";
476 $parse_alias{$aliasfiletype}->($fh);
481 ($sender) = expand_aliases
($sender) if defined $sender;
483 # returns 1 if the conflict must be solved using it as a format-patch argument
484 sub check_file_rev_conflict
($) {
488 $repo->command('rev-parse', '--verify', '--quiet', $f);
489 if (defined($format_patch)) {
490 return $format_patch;
493 File '$f' exists but it could also be the range of commits
494 to produce patches for. Please disambiguate by...
496 * Saying "./$f" if you mean a file; or
497 * Giving --format-patch option if you mean a range.
499 } catch Git
::Error
::Command with
{
504 # Now that all the defaults are set, process the rest of the command line
505 # arguments and collect up the files that need to be processed.
507 while (defined(my $f = shift @ARGV)) {
509 push @rev_list_opts, "--", @ARGV;
511 } elsif (-d
$f and !check_file_rev_conflict
($f)) {
513 or die "Failed to opendir $f: $!";
515 push @files, grep { -f
$_ } map { catfile
($f, $_) }
518 } elsif ((-f
$f or -p
$f) and !check_file_rev_conflict
($f)) {
521 push @rev_list_opts, $f;
525 if (@rev_list_opts) {
526 die "Cannot run git format-patch from outside a repository\n"
528 push @files, $repo->command('format-patch', '-o', tempdir
(CLEANUP
=> 1), @rev_list_opts);
532 foreach my $f (@files) {
534 my $error = validate_patch
($f);
535 $error and die "fatal: $f: $error\nwarning: no patches were sent\n";
542 print $_,"\n" for (@files);
545 print STDERR
"\nNo patch files specified!\n\n";
549 sub get_patch_subject
{
551 open (my $fh, '<', $fn);
552 while (my $line = <$fh>) {
553 next unless ($line =~ /^Subject: (.*)$/);
558 die "No subject line in $fn ?";
562 # Note that this does not need to be secure, but we will make a small
563 # effort to have it be unique
564 $compose_filename = ($repo ?
565 tempfile
(".gitsendemail.msg.XXXXXX", DIR
=> $repo->repo_path()) :
566 tempfile
(".gitsendemail.msg.XXXXXX", DIR
=> "."))[1];
567 open my $c, ">", $compose_filename
568 or die "Failed to open for writing $compose_filename: $!";
571 my $tpl_sender = $sender || $repoauthor || $repocommitter || '';
572 my $tpl_subject = $initial_subject || '';
573 my $tpl_reply_to = $initial_reply_to || '';
576 From $tpl_sender # This line is ignored.
577 GIT: Lines beginning in "GIT:" will be removed.
578 GIT: Consider including an overall diffstat or table of contents
579 GIT: for the patch you are writing.
581 GIT: Clear the body content if you don't wish to send a summary.
583 Subject: $tpl_subject
584 In-Reply-To: $tpl_reply_to
588 print $c get_patch_subject
($f);
593 do_edit
($compose_filename, @files);
595 do_edit
($compose_filename);
598 open my $c2, ">", $compose_filename . ".final"
599 or die "Failed to open $compose_filename.final : " . $!;
601 open $c, "<", $compose_filename
602 or die "Failed to open $compose_filename : " . $!;
604 my $need_8bit_cte = file_has_nonascii
($compose_filename);
606 my $summary_empty = 1;
610 $summary_empty = 0 unless (/^\n$/);
613 if ($need_8bit_cte) {
614 print $c2 "MIME-Version: 1.0\n",
615 "Content-Type: text/plain; ",
617 "Content-Transfer-Encoding: 8bit\n";
619 } elsif (/^MIME-Version:/i) {
621 } elsif (/^Subject:\s*(.+)\s*$/i) {
622 $initial_subject = $1;
623 my $subject = $initial_subject;
625 ($subject =~ /[^[:ascii:]]/ ?
626 quote_rfc2047
($subject) :
629 } elsif (/^In-Reply-To:\s*(.+)\s*$/i) {
630 $initial_reply_to = $1;
632 } elsif (/^From:\s*(.+)\s*$/i) {
635 } elsif (/^(?:To|Cc|Bcc):/i) {
636 print "To/Cc/Bcc fields are not interpreted yet, they have been ignored\n";
644 if ($summary_empty) {
645 print "Summary email is empty, skipping it\n";
648 } elsif ($annotate) {
653 my ($prompt, %arg) = @_;
654 my $valid_re = $arg{valid_re
};
655 my $default = $arg{default};
658 return defined $default ?
$default : undef
659 unless defined $term->IN and defined fileno($term->IN) and
660 defined $term->OUT and defined fileno($term->OUT);
662 $resp = $term->readline($prompt);
663 if (!defined $resp) { # EOF
665 return defined $default ?
$default : undef;
667 if ($resp eq '' and defined $default) {
670 if (!defined $valid_re or $resp =~ /$valid_re/) {
679 sub file_declares_8bit_cte
{
681 open (my $fh, '<', $fn);
682 while (my $line = <$fh>) {
683 last if ($line =~ /^$/);
684 return 1 if ($line =~ /^Content-Transfer-Encoding: .*8bit.*$/);
690 foreach my $f (@files) {
691 next unless (body_or_subject_has_nonascii
($f)
692 && !file_declares_8bit_cte
($f));
693 $broken_encoding{$f} = 1;
696 if (!defined $auto_8bit_encoding && scalar %broken_encoding) {
697 print "The following files are 8bit, but do not declare " .
698 "a Content-Transfer-Encoding.\n";
699 foreach my $f (sort keys %broken_encoding) {
702 $auto_8bit_encoding = ask
("Which 8bit encoding should I declare [UTF-8]? ",
708 if (get_patch_subject
($f) =~ /\Q*** SUBJECT HERE ***\E/) {
709 die "Refusing to send because the patch\n\t$f\n"
710 . "has the template subject '*** SUBJECT HERE ***'. "
711 . "Pass --force if you really want to send.\n";
717 if (!defined $sender) {
718 $sender = $repoauthor || $repocommitter || '';
719 $sender = ask
("Who should the emails appear to be from? [$sender] ",
721 print "Emails will be sent from: ", $sender, "\n";
726 my $to = ask
("Who should the emails be sent to? ");
727 push @to, parse_address_line
($to) if defined $to; # sanitized/validated later
732 return map { expand_one_alias
($_) } @_;
735 my %EXPANDED_ALIASES;
736 sub expand_one_alias
{
738 if ($EXPANDED_ALIASES{$alias}) {
739 die "fatal: alias '$alias' expands to itself\n";
741 local $EXPANDED_ALIASES{$alias} = 1;
742 return $aliases{$alias} ? expand_aliases
(@
{$aliases{$alias}}) : $alias;
745 @to = expand_aliases
(@to);
746 @to = (map { sanitize_address
($_) } @to);
747 @initial_cc = expand_aliases
(@initial_cc);
748 @bcclist = expand_aliases
(@bcclist);
750 if ($thread && !defined $initial_reply_to && $prompting) {
751 $initial_reply_to = ask
(
752 "Message-ID to be used as In-Reply-To for the first email? ");
754 if (defined $initial_reply_to) {
755 $initial_reply_to =~ s/^\s*<?//;
756 $initial_reply_to =~ s/>?\s*$//;
757 $initial_reply_to = "<$initial_reply_to>" if $initial_reply_to ne '';
760 if (!defined $smtp_server) {
761 foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
767 $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
770 if ($compose && $compose > 0) {
771 @files = ($compose_filename . ".final", @files);
774 # Variables we set as part of the loop over files
775 our ($message_id, %mail, $subject, $reply_to, $references, $message,
776 $needs_confirm, $message_num, $ask_default);
778 sub extract_valid_address
{
780 my $local_part_regexp = '[^<>"\s@]+';
781 my $domain_regexp = '[^.<>"\s@]+(?:\.[^.<>"\s@]+)+';
783 # check for a local address:
784 return $address if ($address =~ /^($local_part_regexp)$/);
786 $address =~ s/^\s*<(.*)>\s*$/$1/;
787 if ($have_email_valid) {
788 return scalar Email
::Valid
->address($address);
790 # less robust/correct than the monster regexp in Email::Valid,
791 # but still does a 99% job, and one less dependency
792 $address =~ /($local_part_regexp\@$domain_regexp)/;
797 # Usually don't need to change anything below here.
799 # we make a "fake" message id by taking the current number
800 # of seconds since the beginning of Unix time and tacking on
801 # a random number to the end, in case we are called quicker than
802 # 1 second since the last time we were called.
804 # We'll setup a template for the message id, using the "from" address:
806 my ($message_id_stamp, $message_id_serial);
807 sub make_message_id
{
809 if (!defined $message_id_stamp) {
810 $message_id_stamp = sprintf("%s-%s", time, $$);
811 $message_id_serial = 0;
813 $message_id_serial++;
814 $uniq = "$message_id_stamp-$message_id_serial";
817 for ($sender, $repocommitter, $repoauthor) {
818 $du_part = extract_valid_address
(sanitize_address
($_));
819 last if (defined $du_part and $du_part ne '');
821 if (not defined $du_part or $du_part eq '') {
822 use Sys
::Hostname
qw();
823 $du_part = 'user@' . Sys
::Hostname
::hostname
();
825 my $message_id_template = "<%s-git-send-email-%s>";
826 $message_id = sprintf($message_id_template, $uniq, $du_part);
827 #print "new message id = $message_id\n"; # Was useful for debugging
832 $time = time - scalar $#files;
834 sub unquote_rfc2047
{
837 if (s/=\?([^?]+)\?q\?(.*)\?=/$2/g) {
840 s/=([0-9A-F]{2})/chr(hex($1))/eg;
842 return wantarray ?
($_, $encoding) : $_;
847 my $encoding = shift || 'UTF-8';
848 s/([^-a-zA-Z0-9!*+\/])/sprintf
("=%02X", ord($1))/eg
;
849 s/(.*)/=\?$encoding\?q\?$1\?=/;
853 sub is_rfc2047_quoted
{
855 my $token = '[^][()<>@,;:"\/?.= \000-\037\177-\377]+';
856 my $encoded_text = '[!->@-~]+';
858 $s =~ m/^(?:"[[:ascii:]]*"|=\?$token\?$token\?$encoded_text\?=)$/o;
861 # use the simplest quoting being able to handle the recipient
862 sub sanitize_address
{
863 my ($recipient) = @_;
864 my ($recipient_name, $recipient_addr) = ($recipient =~ /^(.*?)\s*(<.*)/);
866 if (not $recipient_name) {
870 # if recipient_name is already quoted, do nothing
871 if (is_rfc2047_quoted
($recipient_name)) {
875 # rfc2047 is needed if a non-ascii char is included
876 if ($recipient_name =~ /[^[:ascii:]]/) {
877 $recipient_name =~ s/^"(.*)"$/$1/;
878 $recipient_name = quote_rfc2047
($recipient_name);
881 # double quotes are needed if specials or CTLs are included
882 elsif ($recipient_name =~ /[][()<>@,;:\\".\000-\037\177]/) {
883 $recipient_name =~ s/(["\\\r])/\\$1/g;
884 $recipient_name = qq["$recipient_name"];
887 return "$recipient_name $recipient_addr";
891 # Returns the local Fully Qualified Domain Name (FQDN) if available.
893 # Tightly configured MTAa require that a caller sends a real DNS
894 # domain name that corresponds the IP address in the HELO/EHLO
895 # handshake. This is used to verify the connection and prevent
896 # spammers from trying to hide their identity. If the DNS and IP don't
897 # match, the receiveing MTA may deny the connection.
899 # Here is a deny example of Net::SMTP with the default "localhost.localdomain"
901 # Net::SMTP=GLOB(0x267ec28)>>> EHLO localhost.localdomain
902 # Net::SMTP=GLOB(0x267ec28)<<< 550 EHLO argument does not match calling host
904 # This maildomain*() code is based on ideas in Perl library Test::Reporter
905 # /usr/share/perl5/Test/Reporter/Mail/Util.pm ==> sub _maildomain ()
909 return defined $domain && !($^O
eq 'darwin' && $domain =~ /\.local$/) && $domain =~ /\./;
915 if (eval { require Net
::Domain
; 1 }) {
916 my $domain = Net
::Domain
::domainname
();
917 $maildomain = $domain if valid_fqdn
($domain);
926 if (eval { require Net
::SMTP
; 1 }) {
927 for my $host (qw(mailhost localhost)) {
928 my $smtp = Net
::SMTP
->new($host);
930 my $domain = $smtp->domain;
933 $maildomain = $domain if valid_fqdn
($domain);
944 return maildomain_net
() || maildomain_mta
() || 'localhost.localdomain';
947 # Returns 1 if the message was sent, and 0 otherwise.
948 # In actuality, the whole program dies when there
949 # is an error sending a message.
952 my @recipients = unique_email_list
(@to);
953 @cc = (grep { my $cc = extract_valid_address
($_);
954 not grep { $cc eq $_ } @recipients
956 map { sanitize_address
($_) }
958 my $to = join (",\n\t", @recipients);
959 @recipients = unique_email_list
(@recipients,@cc,@bcclist);
960 @recipients = (map { extract_valid_address
($_) } @recipients);
961 my $date = format_2822_time
($time++);
962 my $gitversion = '@@GIT_VERSION@@';
963 if ($gitversion =~ m/..GIT_VERSION../) {
964 $gitversion = Git
::version
();
967 my $cc = join(",\n\t", unique_email_list
(@cc));
970 $ccline = "\nCc: $cc";
972 my $sanitized_sender = sanitize_address
($sender);
973 make_message_id
() unless defined($message_id);
975 my $header = "From: $sanitized_sender
979 Message-Id: $message_id
980 X-Mailer: git-send-email $gitversion
984 $header .= "In-Reply-To: $reply_to\n";
985 $header .= "References: $references\n";
988 $header .= join("\n", @xh) . "\n";
991 my @sendmail_parameters = ('-i', @recipients);
992 my $raw_from = $sanitized_sender;
993 if (defined $envelope_sender && $envelope_sender ne "auto") {
994 $raw_from = $envelope_sender;
996 $raw_from = extract_valid_address
($raw_from);
997 unshift (@sendmail_parameters,
998 '-f', $raw_from) if(defined $envelope_sender);
1000 if ($needs_confirm && !$dry_run) {
1001 print "\n$header\n";
1002 if ($needs_confirm eq "inform") {
1003 $confirm_unconfigured = 0; # squelch this message for the rest of this run
1004 $ask_default = "y"; # assume yes on EOF since user hasn't explicitly asked for confirmation
1005 print " The Cc list above has been expanded by additional\n";
1006 print " addresses found in the patch commit message. By default\n";
1007 print " send-email prompts before sending whenever this occurs.\n";
1008 print " This behavior is controlled by the sendemail.confirm\n";
1009 print " configuration setting.\n";
1011 print " For additional information, run 'git send-email --help'.\n";
1012 print " To retain the current behavior, but squelch this message,\n";
1013 print " run 'git config --global sendemail.confirm auto'.\n\n";
1015 $_ = ask
("Send this email? ([y]es|[n]o|[q]uit|[a]ll): ",
1016 valid_re
=> qr/^(?:yes|y|no|n|quit|q|all|a)/i,
1017 default => $ask_default);
1018 die "Send this email reply required" unless defined $_;
1022 cleanup_compose_files
();
1030 # We don't want to send the email.
1031 } elsif ($smtp_server =~ m
#^/#) {
1032 my $pid = open my $sm, '|-';
1033 defined $pid or die $!;
1035 exec($smtp_server, @sendmail_parameters) or die $!;
1037 print $sm "$header\n$message";
1038 close $sm or die $!;
1041 if (!defined $smtp_server) {
1042 die "The required SMTP server is not properly defined."
1045 if ($smtp_encryption eq 'ssl') {
1046 $smtp_server_port ||= 465; # ssmtp
1047 require Net
::SMTP
::SSL
;
1048 $smtp_domain ||= maildomain
();
1049 $smtp ||= Net
::SMTP
::SSL
->new($smtp_server,
1050 Hello
=> $smtp_domain,
1051 Port
=> $smtp_server_port);
1055 $smtp_domain ||= maildomain
();
1056 $smtp ||= Net
::SMTP
->new((defined $smtp_server_port)
1057 ?
"$smtp_server:$smtp_server_port"
1059 Hello
=> $smtp_domain,
1060 Debug
=> $debug_net_smtp);
1061 if ($smtp_encryption eq 'tls' && $smtp) {
1062 require Net
::SMTP
::SSL
;
1063 $smtp->command('STARTTLS');
1065 if ($smtp->code == 220) {
1066 $smtp = Net
::SMTP
::SSL
->start_SSL($smtp)
1067 or die "STARTTLS failed! ".$smtp->message;
1068 $smtp_encryption = '';
1069 # Send EHLO again to receive fresh
1070 # supported commands
1073 die "Server does not support STARTTLS! ".$smtp->message;
1079 die "Unable to initialize SMTP properly. Check config and use --smtp-debug. ",
1080 "VALUES: server=$smtp_server ",
1081 "encryption=$smtp_encryption ",
1082 "hello=$smtp_domain",
1083 defined $smtp_server_port ?
"port=$smtp_server_port" : "";
1086 if (defined $smtp_authuser) {
1088 if (!defined $smtp_authpass) {
1090 system "stty -echo";
1096 } while (!defined $_);
1098 chomp($smtp_authpass = $_);
1103 $auth ||= $smtp->auth( $smtp_authuser, $smtp_authpass ) or die $smtp->message;
1106 $smtp->mail( $raw_from ) or die $smtp->message;
1107 $smtp->to( @recipients ) or die $smtp->message;
1108 $smtp->data or die $smtp->message;
1109 $smtp->datasend("$header\n$message") or die $smtp->message;
1110 $smtp->dataend() or die $smtp->message;
1111 $smtp->code =~ /250|200/ or die "Failed to send $subject\n".$smtp->message;
1114 printf (($dry_run ?
"Dry-" : "")."Sent %s\n", $subject);
1116 print (($dry_run ?
"Dry-" : "")."OK. Log says:\n");
1117 if ($smtp_server !~ m
#^/#) {
1118 print "Server: $smtp_server\n";
1119 print "MAIL FROM:<$raw_from>\n";
1120 foreach my $entry (@recipients) {
1121 print "RCPT TO:<$entry>\n";
1124 print "Sendmail: $smtp_server ".join(' ',@sendmail_parameters)."\n";
1126 print $header, "\n";
1128 print "Result: ", $smtp->code, ' ',
1129 ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
1131 print "Result: OK\n";
1138 $reply_to = $initial_reply_to;
1139 $references = $initial_reply_to || '';
1140 $subject = $initial_subject;
1143 foreach my $t (@files) {
1144 open my $fh, "<", $t or die "can't open file $t";
1147 my $author_encoding;
1148 my $has_content_type;
1152 my $input_format = undef;
1156 # First unfold multiline header fields
1159 if (/^\s+\S/ and @header) {
1160 chomp($header[$#header]);
1162 $header[$#header] .= $_;
1167 # Now parse the header
1170 $input_format = 'mbox';
1174 if (!defined $input_format && /^[-A-Za-z]+:\s/) {
1175 $input_format = 'mbox';
1178 if (defined $input_format && $input_format eq 'mbox') {
1179 if (/^Subject:\s+(.*)$/) {
1182 elsif (/^From:\s+(.*)$/) {
1183 ($author, $author_encoding) = unquote_rfc2047
($1);
1184 next if $suppress_cc{'author'};
1185 next if $suppress_cc{'self'} and $author eq $sender;
1186 printf("(mbox) Adding cc: %s from line '%s'\n",
1187 $1, $_) unless $quiet;
1190 elsif (/^Cc:\s+(.*)$/) {
1191 foreach my $addr (parse_address_line
($1)) {
1192 if (unquote_rfc2047
($addr) eq $sender) {
1193 next if ($suppress_cc{'self'});
1195 next if ($suppress_cc{'cc'});
1197 printf("(mbox) Adding cc: %s from line '%s'\n",
1198 $addr, $_) unless $quiet;
1202 elsif (/^Content-type:/i) {
1203 $has_content_type = 1;
1204 if (/charset="?([^ "]+)/) {
1205 $body_encoding = $1;
1209 elsif (/^Message-Id: (.*)/i) {
1212 elsif (!/^Date:\s/ && /^[-A-Za-z]+:\s+\S/) {
1217 # In the traditional
1218 # "send lots of email" format,
1221 # So let's support that, too.
1222 $input_format = 'lots';
1223 if (@cc == 0 && !$suppress_cc{'cc'}) {
1224 printf("(non-mbox) Adding cc: %s from line '%s'\n",
1225 $_, $_) unless $quiet;
1227 } elsif (!defined $subject) {
1232 # Now parse the message body
1235 if (/^(Signed-off-by|Cc): (.*)$/i) {
1237 my ($what, $c) = ($1, $2);
1239 if ($c eq $sender) {
1240 next if ($suppress_cc{'self'});
1242 next if $suppress_cc{'sob'} and $what =~ /Signed-off-by/i;
1243 next if $suppress_cc{'bodycc'} and $what =~ /Cc/i;
1246 printf("(body) Adding cc: %s from line '%s'\n",
1247 $c, $_) unless $quiet;
1252 if (defined $cc_cmd && !$suppress_cc{'cccmd'}) {
1253 open my $fh, "$cc_cmd \Q$t\E |"
1254 or die "(cc-cmd) Could not execute '$cc_cmd'";
1259 next if ($c eq $sender and $suppress_from);
1261 printf("(cc-cmd) Adding cc: %s from: '%s'\n",
1262 $c, $cc_cmd) unless $quiet;
1265 or die "(cc-cmd) failed to close pipe to '$cc_cmd'";
1268 if ($broken_encoding{$t} && !$has_content_type) {
1269 $has_content_type = 1;
1270 push @xh, "MIME-Version: 1.0",
1271 "Content-Type: text/plain; charset=$auto_8bit_encoding",
1272 "Content-Transfer-Encoding: 8bit";
1273 $body_encoding = $auto_8bit_encoding;
1276 if ($broken_encoding{$t} && !is_rfc2047_quoted
($subject)) {
1277 $subject = quote_rfc2047
($subject, $auto_8bit_encoding);
1280 if (defined $author and $author ne $sender) {
1281 $message = "From: $author\n\n$message";
1282 if (defined $author_encoding) {
1283 if ($has_content_type) {
1284 if ($body_encoding eq $author_encoding) {
1285 # ok, we already have the right encoding
1288 # uh oh, we should re-encode
1292 $has_content_type = 1;
1294 'MIME-Version: 1.0',
1295 "Content-Type: text/plain; charset=$author_encoding",
1296 'Content-Transfer-Encoding: 8bit';
1302 $confirm eq "always" or
1303 ($confirm =~ /^(?:auto|cc)$/ && @cc) or
1304 ($confirm =~ /^(?:auto|compose)$/ && $compose && $message_num == 1));
1305 $needs_confirm = "inform" if ($needs_confirm && $confirm_unconfigured && @cc);
1307 @cc = (@initial_cc, @cc);
1309 my $message_was_sent = send_message
();
1311 # set up for the next message
1312 if ($thread && $message_was_sent &&
1313 (chain_reply_to
() || !defined $reply_to || length($reply_to) == 0)) {
1314 $reply_to = $message_id;
1315 if (length $references > 0) {
1316 $references .= "\n $message_id";
1318 $references = "$message_id";
1321 $message_id = undef;
1324 cleanup_compose_files
();
1326 sub cleanup_compose_files
{
1327 unlink($compose_filename, $compose_filename . ".final") if $compose;
1330 $smtp->quit if $smtp;
1332 sub unique_email_list
{
1336 foreach my $entry (@_) {
1337 if (my $clean = extract_valid_address
($entry)) {
1338 $seen{$clean} ||= 0;
1339 next if $seen{$clean}++;
1340 push @emails, $entry;
1342 print STDERR
"W: unable to extract a valid address",
1349 sub validate_patch
{
1351 open(my $fh, '<', $fn)
1352 or die "unable to open $fn: $!\n";
1353 while (my $line = <$fh>) {
1354 if (length($line) > 998) {
1355 return "$.: patch contains a line longer than 998 characters";
1361 sub file_has_nonascii
{
1363 open(my $fh, '<', $fn)
1364 or die "unable to open $fn: $!\n";
1365 while (my $line = <$fh>) {
1366 return 1 if $line =~ /[^[:ascii:]]/;
1371 sub body_or_subject_has_nonascii
{
1373 open(my $fh, '<', $fn)
1374 or die "unable to open $fn: $!\n";
1375 while (my $line = <$fh>) {
1376 last if $line =~ /^$/;
1377 return 1 if $line =~ /^Subject.*[^[:ascii:]]/;
1379 while (my $line = <$fh>) {
1380 return 1 if $line =~ /[^[:ascii:]]/;