GIT 1.6.1-rc1
[git/git-svn.git] / git-send-email.perl
blob3112f769cd4b86cbb87fbbb14b5a9d8c4b5fc6bd
1 #!/usr/bin/perl -w
3 # Copyright 2002,2005 Greg Kroah-Hartman <greg@kroah.com>
4 # Copyright 2005 Ryan Anderson <ryan@michonline.com>
6 # GPL v2 (See COPYING)
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.
19 use strict;
20 use warnings;
21 use Term::ReadLine;
22 use Getopt::Long;
23 use Data::Dumper;
24 use Term::ANSIColor;
25 use File::Temp qw/ tempdir /;
26 use Error qw(:try);
27 use Git;
29 Getopt::Long::Configure qw/ pass_through /;
31 package FakeTerm;
32 sub new {
33 my ($class, $reason) = @_;
34 return bless \$reason, shift;
36 sub readline {
37 my $self = shift;
38 die "Cannot use readline on FakeTerm: $$self";
40 package main;
43 sub usage {
44 print <<EOT;
45 git send-email [options] <file | directory | rev-list options >
47 Composing:
48 --from <str> * Email From:
49 --to <str> * Email To:
50 --cc <str> * Email Cc:
51 --bcc <str> * Email Bcc:
52 --subject <str> * Email "Subject:"
53 --in-reply-to <str> * Email "In-Reply-To:"
54 --annotate * Review each patch that will be sent in an editor.
55 --compose * Open an editor for introduction.
57 Sending:
58 --envelope-sender <str> * Email envelope sender.
59 --smtp-server <str:int> * Outgoing SMTP server to use. The port
60 is optional. Default 'localhost'.
61 --smtp-server-port <int> * Outgoing SMTP server port.
62 --smtp-user <str> * Username for SMTP-AUTH.
63 --smtp-pass <str> * Password for SMTP-AUTH; not necessary.
64 --smtp-encryption <str> * tls or ssl; anything else disables.
65 --smtp-ssl * Deprecated. Use '--smtp-encryption ssl'.
67 Automating:
68 --identity <str> * Use the sendemail.<id> options.
69 --cc-cmd <str> * Email Cc: via `<str> \$patch_path`
70 --suppress-cc <str> * author, self, sob, cccmd, all.
71 --[no-]signed-off-by-cc * Send to Cc: and Signed-off-by:
72 addresses. Default on.
73 --[no-]suppress-from * Send to self. Default off.
74 --[no-]chain-reply-to * Chain In-Reply-To: fields. Default on.
75 --[no-]thread * Use In-Reply-To: field. Default on.
77 Administering:
78 --quiet * Output one line of info per email.
79 --dry-run * Don't actually send the emails.
80 --[no-]validate * Perform patch sanity checks. Default on.
81 --[no-]format-patch * understand any non optional arguments as
82 `git format-patch` ones.
84 EOT
85 exit(1);
88 # most mail servers generate the Date: header, but not all...
89 sub format_2822_time {
90 my ($time) = @_;
91 my @localtm = localtime($time);
92 my @gmttm = gmtime($time);
93 my $localmin = $localtm[1] + $localtm[2] * 60;
94 my $gmtmin = $gmttm[1] + $gmttm[2] * 60;
95 if ($localtm[0] != $gmttm[0]) {
96 die "local zone differs from GMT by a non-minute interval\n";
98 if ((($gmttm[6] + 1) % 7) == $localtm[6]) {
99 $localmin += 1440;
100 } elsif ((($gmttm[6] - 1) % 7) == $localtm[6]) {
101 $localmin -= 1440;
102 } elsif ($gmttm[6] != $localtm[6]) {
103 die "local time offset greater than or equal to 24 hours\n";
105 my $offset = $localmin - $gmtmin;
106 my $offhour = $offset / 60;
107 my $offmin = abs($offset % 60);
108 if (abs($offhour) >= 24) {
109 die ("local time offset greater than or equal to 24 hours\n");
112 return sprintf("%s, %2d %s %d %02d:%02d:%02d %s%02d%02d",
113 qw(Sun Mon Tue Wed Thu Fri Sat)[$localtm[6]],
114 $localtm[3],
115 qw(Jan Feb Mar Apr May Jun
116 Jul Aug Sep Oct Nov Dec)[$localtm[4]],
117 $localtm[5]+1900,
118 $localtm[2],
119 $localtm[1],
120 $localtm[0],
121 ($offset >= 0) ? '+' : '-',
122 abs($offhour),
123 $offmin,
127 my $have_email_valid = eval { require Email::Valid; 1 };
128 my $smtp;
129 my $auth;
131 sub unique_email_list(@);
132 sub cleanup_compose_files();
134 # Variables we fill in automatically, or via prompting:
135 my (@to,@cc,@initial_cc,@bcclist,@xh,
136 $initial_reply_to,$initial_subject,@files,
137 $author,$sender,$smtp_authpass,$annotate,$compose,$time);
139 my $envelope_sender;
141 # Example reply to:
142 #$initial_reply_to = ''; #<20050203173208.GA23964@foobar.com>';
144 my $repo = eval { Git->repository() };
145 my @repo = $repo ? ($repo) : ();
146 my $term = eval {
147 $ENV{"GIT_SEND_EMAIL_NOTTY"}
148 ? new Term::ReadLine 'git-send-email', \*STDIN, \*STDOUT
149 : new Term::ReadLine 'git-send-email';
151 if ($@) {
152 $term = new FakeTerm "$@: going non-interactive";
155 # Behavior modification variables
156 my ($quiet, $dry_run) = (0, 0);
157 my $format_patch;
158 my $compose_filename = $repo->repo_path() . "/.gitsendemail.msg.$$";
160 # Handle interactive edition of files.
161 my $multiedit;
162 my $editor = $ENV{GIT_EDITOR} || Git::config(@repo, "core.editor") || $ENV{VISUAL} || $ENV{EDITOR} || "vi";
163 sub do_edit {
164 if (defined($multiedit) && !$multiedit) {
165 map {
166 system('sh', '-c', $editor.' "$@"', $editor, $_);
167 if (($? & 127) || ($? >> 8)) {
168 die("the editor exited uncleanly, aborting everything");
170 } @_;
171 } else {
172 system('sh', '-c', $editor.' "$@"', $editor, @_);
173 if (($? & 127) || ($? >> 8)) {
174 die("the editor exited uncleanly, aborting everything");
179 # Variables with corresponding config settings
180 my ($thread, $chain_reply_to, $suppress_from, $signed_off_by_cc, $cc_cmd);
181 my ($smtp_server, $smtp_server_port, $smtp_authuser, $smtp_encryption);
182 my ($identity, $aliasfiletype, @alias_files, @smtp_host_parts);
183 my ($validate);
184 my (@suppress_cc);
186 my %config_bool_settings = (
187 "thread" => [\$thread, 1],
188 "chainreplyto" => [\$chain_reply_to, 1],
189 "suppressfrom" => [\$suppress_from, undef],
190 "signedoffbycc" => [\$signed_off_by_cc, undef],
191 "signedoffcc" => [\$signed_off_by_cc, undef], # Deprecated
192 "validate" => [\$validate, 1],
195 my %config_settings = (
196 "smtpserver" => \$smtp_server,
197 "smtpserverport" => \$smtp_server_port,
198 "smtpuser" => \$smtp_authuser,
199 "smtppass" => \$smtp_authpass,
200 "to" => \@to,
201 "cc" => \@initial_cc,
202 "cccmd" => \$cc_cmd,
203 "aliasfiletype" => \$aliasfiletype,
204 "bcc" => \@bcclist,
205 "aliasesfile" => \@alias_files,
206 "suppresscc" => \@suppress_cc,
207 "envelopesender" => \$envelope_sender,
208 "multiedit" => \$multiedit,
211 # Handle Uncouth Termination
212 sub signal_handler {
214 # Make text normal
215 print color("reset"), "\n";
217 # SMTP password masked
218 system "stty echo";
220 # tmp files from --compose
221 if (-e $compose_filename) {
222 print "'$compose_filename' contains an intermediate version of the email you were composing.\n";
224 if (-e ($compose_filename . ".final")) {
225 print "'$compose_filename.final' contains the composed email.\n"
228 exit;
231 $SIG{TERM} = \&signal_handler;
232 $SIG{INT} = \&signal_handler;
234 # Begin by accumulating all the variables (defined above), that we will end up
235 # needing, first, from the command line:
237 my $rc = GetOptions("sender|from=s" => \$sender,
238 "in-reply-to=s" => \$initial_reply_to,
239 "subject=s" => \$initial_subject,
240 "to=s" => \@to,
241 "cc=s" => \@initial_cc,
242 "bcc=s" => \@bcclist,
243 "chain-reply-to!" => \$chain_reply_to,
244 "smtp-server=s" => \$smtp_server,
245 "smtp-server-port=s" => \$smtp_server_port,
246 "smtp-user=s" => \$smtp_authuser,
247 "smtp-pass:s" => \$smtp_authpass,
248 "smtp-ssl" => sub { $smtp_encryption = 'ssl' },
249 "smtp-encryption=s" => \$smtp_encryption,
250 "identity=s" => \$identity,
251 "annotate" => \$annotate,
252 "compose" => \$compose,
253 "quiet" => \$quiet,
254 "cc-cmd=s" => \$cc_cmd,
255 "suppress-from!" => \$suppress_from,
256 "suppress-cc=s" => \@suppress_cc,
257 "signed-off-cc|signed-off-by-cc!" => \$signed_off_by_cc,
258 "dry-run" => \$dry_run,
259 "envelope-sender=s" => \$envelope_sender,
260 "thread!" => \$thread,
261 "validate!" => \$validate,
262 "format-patch!" => \$format_patch,
265 unless ($rc) {
266 usage();
269 # Now, let's fill any that aren't set in with defaults:
271 sub read_config {
272 my ($prefix) = @_;
274 foreach my $setting (keys %config_bool_settings) {
275 my $target = $config_bool_settings{$setting}->[0];
276 $$target = Git::config_bool(@repo, "$prefix.$setting") unless (defined $$target);
279 foreach my $setting (keys %config_settings) {
280 my $target = $config_settings{$setting};
281 if (ref($target) eq "ARRAY") {
282 unless (@$target) {
283 my @values = Git::config(@repo, "$prefix.$setting");
284 @$target = @values if (@values && defined $values[0]);
287 else {
288 $$target = Git::config(@repo, "$prefix.$setting") unless (defined $$target);
292 if (!defined $smtp_encryption) {
293 my $enc = Git::config(@repo, "$prefix.smtpencryption");
294 if (defined $enc) {
295 $smtp_encryption = $enc;
296 } elsif (Git::config_bool(@repo, "$prefix.smtpssl")) {
297 $smtp_encryption = 'ssl';
302 # read configuration from [sendemail "$identity"], fall back on [sendemail]
303 $identity = Git::config(@repo, "sendemail.identity") unless (defined $identity);
304 read_config("sendemail.$identity") if (defined $identity);
305 read_config("sendemail");
307 # fall back on builtin bool defaults
308 foreach my $setting (values %config_bool_settings) {
309 ${$setting->[0]} = $setting->[1] unless (defined (${$setting->[0]}));
312 # 'default' encryption is none -- this only prevents a warning
313 $smtp_encryption = '' unless (defined $smtp_encryption);
315 # Set CC suppressions
316 my(%suppress_cc);
317 if (@suppress_cc) {
318 foreach my $entry (@suppress_cc) {
319 die "Unknown --suppress-cc field: '$entry'\n"
320 unless $entry =~ /^(all|cccmd|cc|author|self|sob)$/;
321 $suppress_cc{$entry} = 1;
325 if ($suppress_cc{'all'}) {
326 foreach my $entry (qw (ccmd cc author self sob)) {
327 $suppress_cc{$entry} = 1;
329 delete $suppress_cc{'all'};
332 # If explicit old-style ones are specified, they trump --suppress-cc.
333 $suppress_cc{'self'} = $suppress_from if defined $suppress_from;
334 $suppress_cc{'sob'} = !$signed_off_by_cc if defined $signed_off_by_cc;
336 # Debugging, print out the suppressions.
337 if (0) {
338 print "suppressions:\n";
339 foreach my $entry (keys %suppress_cc) {
340 printf " %-5s -> $suppress_cc{$entry}\n", $entry;
344 my ($repoauthor, $repocommitter);
345 ($repoauthor) = Git::ident_person(@repo, 'author');
346 ($repocommitter) = Git::ident_person(@repo, 'committer');
348 # Verify the user input
350 foreach my $entry (@to) {
351 die "Comma in --to entry: $entry'\n" unless $entry !~ m/,/;
354 foreach my $entry (@initial_cc) {
355 die "Comma in --cc entry: $entry'\n" unless $entry !~ m/,/;
358 foreach my $entry (@bcclist) {
359 die "Comma in --bcclist entry: $entry'\n" unless $entry !~ m/,/;
362 my %aliases;
363 my %parse_alias = (
364 # multiline formats can be supported in the future
365 mutt => sub { my $fh = shift; while (<$fh>) {
366 if (/^\s*alias\s+(\S+)\s+(.*)$/) {
367 my ($alias, $addr) = ($1, $2);
368 $addr =~ s/#.*$//; # mutt allows # comments
369 # commas delimit multiple addresses
370 $aliases{$alias} = [ split(/\s*,\s*/, $addr) ];
371 }}},
372 mailrc => sub { my $fh = shift; while (<$fh>) {
373 if (/^alias\s+(\S+)\s+(.*)$/) {
374 # spaces delimit multiple addresses
375 $aliases{$1} = [ split(/\s+/, $2) ];
376 }}},
377 pine => sub { my $fh = shift; my $f='\t[^\t]*';
378 for (my $x = ''; defined($x); $x = $_) {
379 chomp $x;
380 $x .= $1 while(defined($_ = <$fh>) && /^ +(.*)$/);
381 $x =~ /^(\S+)$f\t\(?([^\t]+?)\)?(:?$f){0,2}$/ or next;
382 $aliases{$1} = [ split(/\s*,\s*/, $2) ];
384 gnus => sub { my $fh = shift; while (<$fh>) {
385 if (/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) {
386 $aliases{$1} = [ $2 ];
390 if (@alias_files and $aliasfiletype and defined $parse_alias{$aliasfiletype}) {
391 foreach my $file (@alias_files) {
392 open my $fh, '<', $file or die "opening $file: $!\n";
393 $parse_alias{$aliasfiletype}->($fh);
394 close $fh;
398 ($sender) = expand_aliases($sender) if defined $sender;
400 # returns 1 if the conflict must be solved using it as a format-patch argument
401 sub check_file_rev_conflict($) {
402 my $f = shift;
403 try {
404 $repo->command('rev-parse', '--verify', '--quiet', $f);
405 if (defined($format_patch)) {
406 print "foo\n";
407 return $format_patch;
409 die(<<EOF);
410 File '$f' exists but it could also be the range of commits
411 to produce patches for. Please disambiguate by...
413 * Saying "./$f" if you mean a file; or
414 * Giving --format-patch option if you mean a range.
416 } catch Git::Error::Command with {
417 return 0;
421 # Now that all the defaults are set, process the rest of the command line
422 # arguments and collect up the files that need to be processed.
423 my @rev_list_opts;
424 while (defined(my $f = shift @ARGV)) {
425 if ($f eq "--") {
426 push @rev_list_opts, "--", @ARGV;
427 @ARGV = ();
428 } elsif (-d $f and !check_file_rev_conflict($f)) {
429 opendir(DH,$f)
430 or die "Failed to opendir $f: $!";
432 push @files, grep { -f $_ } map { +$f . "/" . $_ }
433 sort readdir(DH);
434 closedir(DH);
435 } elsif ((-f $f or -p $f) and !check_file_rev_conflict($f)) {
436 push @files, $f;
437 } else {
438 push @rev_list_opts, $f;
442 if (@rev_list_opts) {
443 push @files, $repo->command('format-patch', '-o', tempdir(CLEANUP => 1), @rev_list_opts);
446 if ($validate) {
447 foreach my $f (@files) {
448 unless (-p $f) {
449 my $error = validate_patch($f);
450 $error and die "fatal: $f: $error\nwarning: no patches were sent\n";
455 if (@files) {
456 unless ($quiet) {
457 print $_,"\n" for (@files);
459 } else {
460 print STDERR "\nNo patch files specified!\n\n";
461 usage();
464 sub get_patch_subject($) {
465 my $fn = shift;
466 open (my $fh, '<', $fn);
467 while (my $line = <$fh>) {
468 next unless ($line =~ /^Subject: (.*)$/);
469 close $fh;
470 return "GIT: $1\n";
472 close $fh;
473 die "No subject line in $fn ?";
476 if ($compose) {
477 # Note that this does not need to be secure, but we will make a small
478 # effort to have it be unique
479 open(C,">",$compose_filename)
480 or die "Failed to open for writing $compose_filename: $!";
483 my $tpl_sender = $sender || $repoauthor || $repocommitter || '';
484 my $tpl_subject = $initial_subject || '';
485 my $tpl_reply_to = $initial_reply_to || '';
487 print C <<EOT;
488 From $tpl_sender # This line is ignored.
489 GIT: Lines beginning in "GIT: " will be removed.
490 GIT: Consider including an overall diffstat or table of contents
491 GIT: for the patch you are writing.
492 GIT:
493 GIT: Clear the body content if you don't wish to send a summary.
494 From: $tpl_sender
495 Subject: $tpl_subject
496 In-Reply-To: $tpl_reply_to
499 for my $f (@files) {
500 print C get_patch_subject($f);
502 close(C);
504 my $editor = $ENV{GIT_EDITOR} || Git::config(@repo, "core.editor") || $ENV{VISUAL} || $ENV{EDITOR} || "vi";
506 if ($annotate) {
507 do_edit($compose_filename, @files);
508 } else {
509 do_edit($compose_filename);
512 open(C2,">",$compose_filename . ".final")
513 or die "Failed to open $compose_filename.final : " . $!;
515 open(C,"<",$compose_filename)
516 or die "Failed to open $compose_filename : " . $!;
518 my $need_8bit_cte = file_has_nonascii($compose_filename);
519 my $in_body = 0;
520 my $summary_empty = 1;
521 while(<C>) {
522 next if m/^GIT: /;
523 if ($in_body) {
524 $summary_empty = 0 unless (/^\n$/);
525 } elsif (/^\n$/) {
526 $in_body = 1;
527 if ($need_8bit_cte) {
528 print C2 "MIME-Version: 1.0\n",
529 "Content-Type: text/plain; ",
530 "charset=utf-8\n",
531 "Content-Transfer-Encoding: 8bit\n";
533 } elsif (/^MIME-Version:/i) {
534 $need_8bit_cte = 0;
535 } elsif (/^Subject:\s*(.+)\s*$/i) {
536 $initial_subject = $1;
537 my $subject = $initial_subject;
538 $_ = "Subject: " .
539 ($subject =~ /[^[:ascii:]]/ ?
540 quote_rfc2047($subject) :
541 $subject) .
542 "\n";
543 } elsif (/^In-Reply-To:\s*(.+)\s*$/i) {
544 $initial_reply_to = $1;
545 next;
546 } elsif (/^From:\s*(.+)\s*$/i) {
547 $sender = $1;
548 next;
549 } elsif (/^(?:To|Cc|Bcc):/i) {
550 print "To/Cc/Bcc fields are not interpreted yet, they have been ignored\n";
551 next;
553 print C2 $_;
555 close(C);
556 close(C2);
558 if ($summary_empty) {
559 print "Summary email is empty, skipping it\n";
560 $compose = -1;
562 } elsif ($annotate) {
563 do_edit(@files);
566 my $prompting = 0;
567 if (!defined $sender) {
568 $sender = $repoauthor || $repocommitter || '';
570 while (1) {
571 $_ = $term->readline("Who should the emails appear to be from? [$sender] ");
572 last if defined $_;
573 print "\n";
576 $sender = $_ if ($_);
577 print "Emails will be sent from: ", $sender, "\n";
578 $prompting++;
581 if (!@to) {
584 while (1) {
585 $_ = $term->readline("Who should the emails be sent to? ", "");
586 last if defined $_;
587 print "\n";
590 my $to = $_;
591 push @to, split /,\s*/, $to;
592 $prompting++;
595 sub expand_aliases {
596 my @cur = @_;
597 my @last;
598 do {
599 @last = @cur;
600 @cur = map { $aliases{$_} ? @{$aliases{$_}} : $_ } @last;
601 } while (join(',',@cur) ne join(',',@last));
602 return @cur;
605 @to = expand_aliases(@to);
606 @to = (map { sanitize_address($_) } @to);
607 @initial_cc = expand_aliases(@initial_cc);
608 @bcclist = expand_aliases(@bcclist);
610 if ($thread && !defined $initial_reply_to && $prompting) {
611 while (1) {
612 $_= $term->readline("Message-ID to be used as In-Reply-To for the first email? ", $initial_reply_to);
613 last if defined $_;
614 print "\n";
617 $initial_reply_to = $_;
619 if (defined $initial_reply_to) {
620 $initial_reply_to =~ s/^\s*<?//;
621 $initial_reply_to =~ s/>?\s*$//;
622 $initial_reply_to = "<$initial_reply_to>" if $initial_reply_to ne '';
625 if (!defined $smtp_server) {
626 foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
627 if (-x $_) {
628 $smtp_server = $_;
629 last;
632 $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
635 if ($compose) {
636 while (1) {
637 $_ = $term->readline("Send this email? (y|n) ");
638 last if defined $_;
639 print "\n";
642 if (uc substr($_,0,1) ne 'Y') {
643 cleanup_compose_files();
644 exit(0);
647 if ($compose > 0) {
648 @files = ($compose_filename . ".final", @files);
652 # Variables we set as part of the loop over files
653 our ($message_id, %mail, $subject, $reply_to, $references, $message);
655 sub extract_valid_address {
656 my $address = shift;
657 my $local_part_regexp = '[^<>"\s@]+';
658 my $domain_regexp = '[^.<>"\s@]+(?:\.[^.<>"\s@]+)+';
660 # check for a local address:
661 return $address if ($address =~ /^($local_part_regexp)$/);
663 $address =~ s/^\s*<(.*)>\s*$/$1/;
664 if ($have_email_valid) {
665 return scalar Email::Valid->address($address);
666 } else {
667 # less robust/correct than the monster regexp in Email::Valid,
668 # but still does a 99% job, and one less dependency
669 $address =~ /($local_part_regexp\@$domain_regexp)/;
670 return $1;
674 # Usually don't need to change anything below here.
676 # we make a "fake" message id by taking the current number
677 # of seconds since the beginning of Unix time and tacking on
678 # a random number to the end, in case we are called quicker than
679 # 1 second since the last time we were called.
681 # We'll setup a template for the message id, using the "from" address:
683 my ($message_id_stamp, $message_id_serial);
684 sub make_message_id
686 my $uniq;
687 if (!defined $message_id_stamp) {
688 $message_id_stamp = sprintf("%s-%s", time, $$);
689 $message_id_serial = 0;
691 $message_id_serial++;
692 $uniq = "$message_id_stamp-$message_id_serial";
694 my $du_part;
695 for ($sender, $repocommitter, $repoauthor) {
696 $du_part = extract_valid_address(sanitize_address($_));
697 last if (defined $du_part and $du_part ne '');
699 if (not defined $du_part or $du_part eq '') {
700 use Sys::Hostname qw();
701 $du_part = 'user@' . Sys::Hostname::hostname();
703 my $message_id_template = "<%s-git-send-email-%s>";
704 $message_id = sprintf($message_id_template, $uniq, $du_part);
705 #print "new message id = $message_id\n"; # Was useful for debugging
710 $time = time - scalar $#files;
712 sub unquote_rfc2047 {
713 local ($_) = @_;
714 my $encoding;
715 if (s/=\?([^?]+)\?q\?(.*)\?=/$2/g) {
716 $encoding = $1;
717 s/_/ /g;
718 s/=([0-9A-F]{2})/chr(hex($1))/eg;
720 return wantarray ? ($_, $encoding) : $_;
723 sub quote_rfc2047 {
724 local $_ = shift;
725 my $encoding = shift || 'utf-8';
726 s/([^-a-zA-Z0-9!*+\/])/sprintf("=%02X", ord($1))/eg;
727 s/(.*)/=\?$encoding\?q\?$1\?=/;
728 return $_;
731 # use the simplest quoting being able to handle the recipient
732 sub sanitize_address
734 my ($recipient) = @_;
735 my ($recipient_name, $recipient_addr) = ($recipient =~ /^(.*?)\s*(<.*)/);
737 if (not $recipient_name) {
738 return "$recipient";
741 # if recipient_name is already quoted, do nothing
742 if ($recipient_name =~ /^(".*"|=\?utf-8\?q\?.*\?=)$/) {
743 return $recipient;
746 # rfc2047 is needed if a non-ascii char is included
747 if ($recipient_name =~ /[^[:ascii:]]/) {
748 $recipient_name = quote_rfc2047($recipient_name);
751 # double quotes are needed if specials or CTLs are included
752 elsif ($recipient_name =~ /[][()<>@,;:\\".\000-\037\177]/) {
753 $recipient_name =~ s/(["\\\r])/\\$1/g;
754 $recipient_name = "\"$recipient_name\"";
757 return "$recipient_name $recipient_addr";
761 sub send_message
763 my @recipients = unique_email_list(@to);
764 @cc = (grep { my $cc = extract_valid_address($_);
765 not grep { $cc eq $_ } @recipients
767 map { sanitize_address($_) }
768 @cc);
769 my $to = join (",\n\t", @recipients);
770 @recipients = unique_email_list(@recipients,@cc,@bcclist);
771 @recipients = (map { extract_valid_address($_) } @recipients);
772 my $date = format_2822_time($time++);
773 my $gitversion = '@@GIT_VERSION@@';
774 if ($gitversion =~ m/..GIT_VERSION../) {
775 $gitversion = Git::version();
778 my $cc = join(", ", unique_email_list(@cc));
779 my $ccline = "";
780 if ($cc ne '') {
781 $ccline = "\nCc: $cc";
783 my $sanitized_sender = sanitize_address($sender);
784 make_message_id() unless defined($message_id);
786 my $header = "From: $sanitized_sender
787 To: $to${ccline}
788 Subject: $subject
789 Date: $date
790 Message-Id: $message_id
791 X-Mailer: git-send-email $gitversion
793 if ($thread && $reply_to) {
795 $header .= "In-Reply-To: $reply_to\n";
796 $header .= "References: $references\n";
798 if (@xh) {
799 $header .= join("\n", @xh) . "\n";
802 my @sendmail_parameters = ('-i', @recipients);
803 my $raw_from = $sanitized_sender;
804 $raw_from = $envelope_sender if (defined $envelope_sender);
805 $raw_from = extract_valid_address($raw_from);
806 unshift (@sendmail_parameters,
807 '-f', $raw_from) if(defined $envelope_sender);
809 if ($dry_run) {
810 # We don't want to send the email.
811 } elsif ($smtp_server =~ m#^/#) {
812 my $pid = open my $sm, '|-';
813 defined $pid or die $!;
814 if (!$pid) {
815 exec($smtp_server, @sendmail_parameters) or die $!;
817 print $sm "$header\n$message";
818 close $sm or die $?;
819 } else {
821 if (!defined $smtp_server) {
822 die "The required SMTP server is not properly defined."
825 if ($smtp_encryption eq 'ssl') {
826 $smtp_server_port ||= 465; # ssmtp
827 require Net::SMTP::SSL;
828 $smtp ||= Net::SMTP::SSL->new($smtp_server, Port => $smtp_server_port);
830 else {
831 require Net::SMTP;
832 $smtp ||= Net::SMTP->new((defined $smtp_server_port)
833 ? "$smtp_server:$smtp_server_port"
834 : $smtp_server);
835 if ($smtp_encryption eq 'tls') {
836 require Net::SMTP::SSL;
837 $smtp->command('STARTTLS');
838 $smtp->response();
839 if ($smtp->code == 220) {
840 $smtp = Net::SMTP::SSL->start_SSL($smtp)
841 or die "STARTTLS failed! ".$smtp->message;
842 $smtp_encryption = '';
843 # Send EHLO again to receive fresh
844 # supported commands
845 $smtp->hello();
846 } else {
847 die "Server does not support STARTTLS! ".$smtp->message;
852 if (!$smtp) {
853 die "Unable to initialize SMTP properly. Is there something wrong with your config?";
856 if (defined $smtp_authuser) {
858 if (!defined $smtp_authpass) {
860 system "stty -echo";
862 do {
863 print "Password: ";
864 $_ = <STDIN>;
865 print "\n";
866 } while (!defined $_);
868 chomp($smtp_authpass = $_);
870 system "stty echo";
873 $auth ||= $smtp->auth( $smtp_authuser, $smtp_authpass ) or die $smtp->message;
876 $smtp->mail( $raw_from ) or die $smtp->message;
877 $smtp->to( @recipients ) or die $smtp->message;
878 $smtp->data or die $smtp->message;
879 $smtp->datasend("$header\n$message") or die $smtp->message;
880 $smtp->dataend() or die $smtp->message;
881 $smtp->ok or die "Failed to send $subject\n".$smtp->message;
883 if ($quiet) {
884 printf (($dry_run ? "Dry-" : "")."Sent %s\n", $subject);
885 } else {
886 print (($dry_run ? "Dry-" : "")."OK. Log says:\n");
887 if ($smtp_server !~ m#^/#) {
888 print "Server: $smtp_server\n";
889 print "MAIL FROM:<$raw_from>\n";
890 print "RCPT TO:".join(',',(map { "<$_>" } @recipients))."\n";
891 } else {
892 print "Sendmail: $smtp_server ".join(' ',@sendmail_parameters)."\n";
894 print $header, "\n";
895 if ($smtp) {
896 print "Result: ", $smtp->code, ' ',
897 ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
898 } else {
899 print "Result: OK\n";
904 $reply_to = $initial_reply_to;
905 $references = $initial_reply_to || '';
906 $subject = $initial_subject;
908 foreach my $t (@files) {
909 open(F,"<",$t) or die "can't open file $t";
911 my $author = undef;
912 my $author_encoding;
913 my $has_content_type;
914 my $body_encoding;
915 @cc = @initial_cc;
916 @xh = ();
917 my $input_format = undef;
918 my $header_done = 0;
919 $message = "";
920 while(<F>) {
921 if (!$header_done) {
922 if (/^From /) {
923 $input_format = 'mbox';
924 next;
926 chomp;
927 if (!defined $input_format && /^[-A-Za-z]+:\s/) {
928 $input_format = 'mbox';
931 if (defined $input_format && $input_format eq 'mbox') {
932 if (/^Subject:\s+(.*)$/) {
933 $subject = $1;
935 } elsif (/^(Cc|From):\s+(.*)$/) {
936 if (unquote_rfc2047($2) eq $sender) {
937 next if ($suppress_cc{'self'});
939 elsif ($1 eq 'From') {
940 ($author, $author_encoding)
941 = unquote_rfc2047($2);
942 next if ($suppress_cc{'author'});
943 } else {
944 next if ($suppress_cc{'cc'});
946 printf("(mbox) Adding cc: %s from line '%s'\n",
947 $2, $_) unless $quiet;
948 push @cc, $2;
950 elsif (/^Content-type:/i) {
951 $has_content_type = 1;
952 if (/charset="?([^ "]+)/) {
953 $body_encoding = $1;
955 push @xh, $_;
957 elsif (/^Message-Id: (.*)/i) {
958 $message_id = $1;
960 elsif (!/^Date:\s/ && /^[-A-Za-z]+:\s+\S/) {
961 push @xh, $_;
964 } else {
965 # In the traditional
966 # "send lots of email" format,
967 # line 1 = cc
968 # line 2 = subject
969 # So let's support that, too.
970 $input_format = 'lots';
971 if (@cc == 0 && !$suppress_cc{'cc'}) {
972 printf("(non-mbox) Adding cc: %s from line '%s'\n",
973 $_, $_) unless $quiet;
975 push @cc, $_;
977 } elsif (!defined $subject) {
978 $subject = $_;
982 # A whitespace line will terminate the headers
983 if (m/^\s*$/) {
984 $header_done = 1;
986 } else {
987 $message .= $_;
988 if (/^(Signed-off-by|Cc): (.*)$/i) {
989 next if ($suppress_cc{'sob'});
990 chomp;
991 my $c = $2;
992 chomp $c;
993 next if ($c eq $sender and $suppress_cc{'self'});
994 push @cc, $c;
995 printf("(sob) Adding cc: %s from line '%s'\n",
996 $c, $_) unless $quiet;
1000 close F;
1002 if (defined $cc_cmd && !$suppress_cc{'cccmd'}) {
1003 open(F, "$cc_cmd $t |")
1004 or die "(cc-cmd) Could not execute '$cc_cmd'";
1005 while(<F>) {
1006 my $c = $_;
1007 $c =~ s/^\s*//g;
1008 $c =~ s/\n$//g;
1009 next if ($c eq $sender and $suppress_from);
1010 push @cc, $c;
1011 printf("(cc-cmd) Adding cc: %s from: '%s'\n",
1012 $c, $cc_cmd) unless $quiet;
1014 close F
1015 or die "(cc-cmd) failed to close pipe to '$cc_cmd'";
1018 if (defined $author) {
1019 $message = "From: $author\n\n$message";
1020 if (defined $author_encoding) {
1021 if ($has_content_type) {
1022 if ($body_encoding eq $author_encoding) {
1023 # ok, we already have the right encoding
1025 else {
1026 # uh oh, we should re-encode
1029 else {
1030 push @xh,
1031 'MIME-Version: 1.0',
1032 "Content-Type: text/plain; charset=$author_encoding",
1033 'Content-Transfer-Encoding: 8bit';
1038 send_message();
1040 # set up for the next message
1041 if ($chain_reply_to || !defined $reply_to || length($reply_to) == 0) {
1042 $reply_to = $message_id;
1043 if (length $references > 0) {
1044 $references .= "\n $message_id";
1045 } else {
1046 $references = "$message_id";
1049 $message_id = undef;
1052 if ($compose) {
1053 cleanup_compose_files();
1056 sub cleanup_compose_files() {
1057 unlink($compose_filename, $compose_filename . ".final");
1061 $smtp->quit if $smtp;
1063 sub unique_email_list(@) {
1064 my %seen;
1065 my @emails;
1067 foreach my $entry (@_) {
1068 if (my $clean = extract_valid_address($entry)) {
1069 $seen{$clean} ||= 0;
1070 next if $seen{$clean}++;
1071 push @emails, $entry;
1072 } else {
1073 print STDERR "W: unable to extract a valid address",
1074 " from: $entry\n";
1077 return @emails;
1080 sub validate_patch {
1081 my $fn = shift;
1082 open(my $fh, '<', $fn)
1083 or die "unable to open $fn: $!\n";
1084 while (my $line = <$fh>) {
1085 if (length($line) > 998) {
1086 return "$.: patch contains a line longer than 998 characters";
1089 return undef;
1092 sub file_has_nonascii {
1093 my $fn = shift;
1094 open(my $fh, '<', $fn)
1095 or die "unable to open $fn: $!\n";
1096 while (my $line = <$fh>) {
1097 return 1 if $line =~ /[^[:ascii:]]/;
1099 return 0;