]> Pileus Git - ~andy/git/blob - git-send-email.perl
git-send-email: Accept fifos as well as files
[~andy/git] / git-send-email.perl
1 #!/usr/bin/perl -w
2 #
3 # Copyright 2002,2005 Greg Kroah-Hartman <greg@kroah.com>
4 # Copyright 2005 Ryan Anderson <ryan@michonline.com>
5 #
6 # GPL v2 (See COPYING)
7 #
8 # Ported to support git "mbox" format files by Ryan Anderson <ryan@michonline.com>
9 #
10 # Sends a collection of emails to the given email addresses, disturbingly fast.
11 #
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.
17 #
18
19 use strict;
20 use warnings;
21 use Term::ReadLine;
22 use Getopt::Long;
23 use Data::Dumper;
24 use Term::ANSIColor;
25 use Git;
26
27 package FakeTerm;
28 sub new {
29         my ($class, $reason) = @_;
30         return bless \$reason, shift;
31 }
32 sub readline {
33         my $self = shift;
34         die "Cannot use readline on FakeTerm: $$self";
35 }
36 package main;
37
38
39 sub usage {
40         print <<EOT;
41 git-send-email [options] <file | directory>...
42 Options:
43    --from         Specify the "From:" line of the email to be sent.
44
45    --to           Specify the primary "To:" line of the email.
46
47    --cc           Specify an initial "Cc:" list for the entire series
48                   of emails.
49
50    --cc-cmd       Specify a command to execute per file which adds
51                   per file specific cc address entries
52
53    --bcc          Specify a list of email addresses that should be Bcc:
54                   on all the emails.
55
56    --compose      Use \$GIT_EDITOR, core.editor, \$EDITOR, or \$VISUAL to edit
57                   an introductory message for the patch series.
58
59    --subject      Specify the initial "Subject:" line.
60                   Only necessary if --compose is also set.  If --compose
61                   is not set, this will be prompted for.
62
63    --in-reply-to  Specify the first "In-Reply-To:" header line.
64                   Only used if --compose is also set.  If --compose is not
65                   set, this will be prompted for.
66
67    --chain-reply-to If set, the replies will all be to the previous
68                   email sent, rather than to the first email sent.
69                   Defaults to on.
70
71    --signed-off-cc Automatically add email addresses that appear in
72                  Signed-off-by: or Cc: lines to the cc: list. Defaults to on.
73
74    --identity     The configuration identity, a subsection to prioritise over
75                   the default section.
76
77    --smtp-server  If set, specifies the outgoing SMTP server to use.
78                   Defaults to localhost.  Port number can be specified here with
79                   hostname:port format or by using --smtp-server-port option.
80
81    --smtp-server-port Specify a port on the outgoing SMTP server to connect to.
82
83    --smtp-user    The username for SMTP-AUTH.
84
85    --smtp-pass    The password for SMTP-AUTH.
86
87    --smtp-ssl     If set, connects to the SMTP server using SSL.
88
89    --suppress-cc  Suppress the specified category of auto-CC.  The category
90                   can be one of 'author' for the patch author, 'self' to
91                   avoid copying yourself, 'sob' for Signed-off-by lines,
92                   'cccmd' for the output of the cccmd, or 'all' to suppress
93                   all of these.
94
95    --suppress-from Suppress sending emails to yourself. Defaults to off.
96
97    --thread       Specify that the "In-Reply-To:" header should be set on all
98                   emails. Defaults to on.
99
100    --quiet        Make git-send-email less verbose.  One line per email
101                   should be all that is output.
102
103    --dry-run      Do everything except actually send the emails.
104
105    --envelope-sender    Specify the envelope sender used to send the emails.
106
107    --no-validate        Don't perform any sanity checks on patches.
108
109 EOT
110         exit(1);
111 }
112
113 # most mail servers generate the Date: header, but not all...
114 sub format_2822_time {
115         my ($time) = @_;
116         my @localtm = localtime($time);
117         my @gmttm = gmtime($time);
118         my $localmin = $localtm[1] + $localtm[2] * 60;
119         my $gmtmin = $gmttm[1] + $gmttm[2] * 60;
120         if ($localtm[0] != $gmttm[0]) {
121                 die "local zone differs from GMT by a non-minute interval\n";
122         }
123         if ((($gmttm[6] + 1) % 7) == $localtm[6]) {
124                 $localmin += 1440;
125         } elsif ((($gmttm[6] - 1) % 7) == $localtm[6]) {
126                 $localmin -= 1440;
127         } elsif ($gmttm[6] != $localtm[6]) {
128                 die "local time offset greater than or equal to 24 hours\n";
129         }
130         my $offset = $localmin - $gmtmin;
131         my $offhour = $offset / 60;
132         my $offmin = abs($offset % 60);
133         if (abs($offhour) >= 24) {
134                 die ("local time offset greater than or equal to 24 hours\n");
135         }
136
137         return sprintf("%s, %2d %s %d %02d:%02d:%02d %s%02d%02d",
138                        qw(Sun Mon Tue Wed Thu Fri Sat)[$localtm[6]],
139                        $localtm[3],
140                        qw(Jan Feb Mar Apr May Jun
141                           Jul Aug Sep Oct Nov Dec)[$localtm[4]],
142                        $localtm[5]+1900,
143                        $localtm[2],
144                        $localtm[1],
145                        $localtm[0],
146                        ($offset >= 0) ? '+' : '-',
147                        abs($offhour),
148                        $offmin,
149                        );
150 }
151
152 my $have_email_valid = eval { require Email::Valid; 1 };
153 my $smtp;
154 my $auth;
155
156 sub unique_email_list(@);
157 sub cleanup_compose_files();
158
159 # Constants (essentially)
160 my $compose_filename = ".msg.$$";
161
162 # Variables we fill in automatically, or via prompting:
163 my (@to,@cc,@initial_cc,@bcclist,@xh,
164         $initial_reply_to,$initial_subject,@files,$author,$sender,$smtp_authpass,$compose,$time);
165
166 my $envelope_sender;
167
168 # Example reply to:
169 #$initial_reply_to = ''; #<20050203173208.GA23964@foobar.com>';
170
171 my $repo = eval { Git->repository() };
172 my @repo = $repo ? ($repo) : ();
173 my $term = eval {
174         $ENV{"GIT_SEND_EMAIL_NOTTY"}
175                 ? new Term::ReadLine 'git-send-email', \*STDIN, \*STDOUT
176                 : new Term::ReadLine 'git-send-email';
177 };
178 if ($@) {
179         $term = new FakeTerm "$@: going non-interactive";
180 }
181
182 # Behavior modification variables
183 my ($quiet, $dry_run) = (0, 0);
184
185 # Variables with corresponding config settings
186 my ($thread, $chain_reply_to, $suppress_from, $signed_off_cc, $cc_cmd);
187 my ($smtp_server, $smtp_server_port, $smtp_authuser, $smtp_ssl);
188 my ($identity, $aliasfiletype, @alias_files, @smtp_host_parts);
189 my ($no_validate);
190 my (@suppress_cc);
191
192 my %config_bool_settings = (
193     "thread" => [\$thread, 1],
194     "chainreplyto" => [\$chain_reply_to, 1],
195     "suppressfrom" => [\$suppress_from, undef],
196     "signedoffcc" => [\$signed_off_cc, undef],
197     "smtpssl" => [\$smtp_ssl, 0],
198 );
199
200 my %config_settings = (
201     "smtpserver" => \$smtp_server,
202     "smtpserverport" => \$smtp_server_port,
203     "smtpuser" => \$smtp_authuser,
204     "smtppass" => \$smtp_authpass,
205     "to" => \@to,
206     "cc" => \@initial_cc,
207     "cccmd" => \$cc_cmd,
208     "aliasfiletype" => \$aliasfiletype,
209     "bcc" => \@bcclist,
210     "aliasesfile" => \@alias_files,
211     "suppresscc" => \@suppress_cc,
212     "envelopesender" => \$envelope_sender,
213 );
214
215 # Handle Uncouth Termination
216 sub signal_handler {
217
218         # Make text normal
219         print color("reset"), "\n";
220
221         # SMTP password masked
222         system "stty echo";
223
224         # tmp files from --compose
225         if (-e $compose_filename) {
226                 print "'$compose_filename' contains an intermediate version of the email you were composing.\n";
227         }
228         if (-e ($compose_filename . ".final")) {
229                 print "'$compose_filename.final' contains the composed email.\n"
230         }
231
232         exit;
233 };
234
235 $SIG{TERM} = \&signal_handler;
236 $SIG{INT}  = \&signal_handler;
237
238 # Begin by accumulating all the variables (defined above), that we will end up
239 # needing, first, from the command line:
240
241 my $rc = GetOptions("sender|from=s" => \$sender,
242                     "in-reply-to=s" => \$initial_reply_to,
243                     "subject=s" => \$initial_subject,
244                     "to=s" => \@to,
245                     "cc=s" => \@initial_cc,
246                     "bcc=s" => \@bcclist,
247                     "chain-reply-to!" => \$chain_reply_to,
248                     "smtp-server=s" => \$smtp_server,
249                     "smtp-server-port=s" => \$smtp_server_port,
250                     "smtp-user=s" => \$smtp_authuser,
251                     "smtp-pass:s" => \$smtp_authpass,
252                     "smtp-ssl!" => \$smtp_ssl,
253                     "identity=s" => \$identity,
254                     "compose" => \$compose,
255                     "quiet" => \$quiet,
256                     "cc-cmd=s" => \$cc_cmd,
257                     "suppress-from!" => \$suppress_from,
258                     "suppress-cc=s" => \@suppress_cc,
259                     "signed-off-cc|signed-off-by-cc!" => \$signed_off_cc,
260                     "dry-run" => \$dry_run,
261                     "envelope-sender=s" => \$envelope_sender,
262                     "thread!" => \$thread,
263                     "no-validate" => \$no_validate,
264          );
265
266 unless ($rc) {
267     usage();
268 }
269
270 # Now, let's fill any that aren't set in with defaults:
271
272 sub read_config {
273         my ($prefix) = @_;
274
275         foreach my $setting (keys %config_bool_settings) {
276                 my $target = $config_bool_settings{$setting}->[0];
277                 $$target = Git::config_bool(@repo, "$prefix.$setting") unless (defined $$target);
278         }
279
280         foreach my $setting (keys %config_settings) {
281                 my $target = $config_settings{$setting};
282                 if (ref($target) eq "ARRAY") {
283                         unless (@$target) {
284                                 my @values = Git::config(@repo, "$prefix.$setting");
285                                 @$target = @values if (@values && defined $values[0]);
286                         }
287                 }
288                 else {
289                         $$target = Git::config(@repo, "$prefix.$setting") unless (defined $$target);
290                 }
291         }
292 }
293
294 # read configuration from [sendemail "$identity"], fall back on [sendemail]
295 $identity = Git::config(@repo, "sendemail.identity") unless (defined $identity);
296 read_config("sendemail.$identity") if (defined $identity);
297 read_config("sendemail");
298
299 # fall back on builtin bool defaults
300 foreach my $setting (values %config_bool_settings) {
301         ${$setting->[0]} = $setting->[1] unless (defined (${$setting->[0]}));
302 }
303
304 # Set CC suppressions
305 my(%suppress_cc);
306 if (@suppress_cc) {
307         foreach my $entry (@suppress_cc) {
308                 die "Unknown --suppress-cc field: '$entry'\n"
309                         unless $entry =~ /^(all|cccmd|cc|author|self|sob)$/;
310                 $suppress_cc{$entry} = 1;
311         }
312 }
313
314 if ($suppress_cc{'all'}) {
315         foreach my $entry (qw (ccmd cc author self sob)) {
316                 $suppress_cc{$entry} = 1;
317         }
318         delete $suppress_cc{'all'};
319 }
320
321 # If explicit old-style ones are specified, they trump --suppress-cc.
322 $suppress_cc{'self'} = $suppress_from if defined $suppress_from;
323 $suppress_cc{'sob'} = !$signed_off_cc if defined $signed_off_cc;
324
325 # Debugging, print out the suppressions.
326 if (0) {
327         print "suppressions:\n";
328         foreach my $entry (keys %suppress_cc) {
329                 printf "  %-5s -> $suppress_cc{$entry}\n", $entry;
330         }
331 }
332
333 my ($repoauthor, $repocommitter);
334 ($repoauthor) = Git::ident_person(@repo, 'author');
335 ($repocommitter) = Git::ident_person(@repo, 'committer');
336
337 # Verify the user input
338
339 foreach my $entry (@to) {
340         die "Comma in --to entry: $entry'\n" unless $entry !~ m/,/;
341 }
342
343 foreach my $entry (@initial_cc) {
344         die "Comma in --cc entry: $entry'\n" unless $entry !~ m/,/;
345 }
346
347 foreach my $entry (@bcclist) {
348         die "Comma in --bcclist entry: $entry'\n" unless $entry !~ m/,/;
349 }
350
351 my %aliases;
352 my %parse_alias = (
353         # multiline formats can be supported in the future
354         mutt => sub { my $fh = shift; while (<$fh>) {
355                 if (/^\s*alias\s+(\S+)\s+(.*)$/) {
356                         my ($alias, $addr) = ($1, $2);
357                         $addr =~ s/#.*$//; # mutt allows # comments
358                          # commas delimit multiple addresses
359                         $aliases{$alias} = [ split(/\s*,\s*/, $addr) ];
360                 }}},
361         mailrc => sub { my $fh = shift; while (<$fh>) {
362                 if (/^alias\s+(\S+)\s+(.*)$/) {
363                         # spaces delimit multiple addresses
364                         $aliases{$1} = [ split(/\s+/, $2) ];
365                 }}},
366         pine => sub { my $fh = shift; while (<$fh>) {
367                 if (/^(\S+)\t.*\t(.*)$/) {
368                         $aliases{$1} = [ split(/\s*,\s*/, $2) ];
369                 }}},
370         gnus => sub { my $fh = shift; while (<$fh>) {
371                 if (/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) {
372                         $aliases{$1} = [ $2 ];
373                 }}}
374 );
375
376 if (@alias_files and $aliasfiletype and defined $parse_alias{$aliasfiletype}) {
377         foreach my $file (@alias_files) {
378                 open my $fh, '<', $file or die "opening $file: $!\n";
379                 $parse_alias{$aliasfiletype}->($fh);
380                 close $fh;
381         }
382 }
383
384 ($sender) = expand_aliases($sender) if defined $sender;
385
386 # Now that all the defaults are set, process the rest of the command line
387 # arguments and collect up the files that need to be processed.
388 for my $f (@ARGV) {
389         if (-d $f) {
390                 opendir(DH,$f)
391                         or die "Failed to opendir $f: $!";
392
393                 push @files, grep { -f $_ } map { +$f . "/" . $_ }
394                                 sort readdir(DH);
395
396         } elsif (-f $f or -p $f) {
397                 push @files, $f;
398
399         } else {
400                 print STDERR "Skipping $f - not found.\n";
401         }
402 }
403
404 if (!$no_validate) {
405         foreach my $f (@files) {
406                 unless (-p $f) {
407                         my $error = validate_patch($f);
408                         $error and die "fatal: $f: $error\nwarning: no patches were sent\n";
409                 }
410         }
411 }
412
413 if (@files) {
414         unless ($quiet) {
415                 print $_,"\n" for (@files);
416         }
417 } else {
418         print STDERR "\nNo patch files specified!\n\n";
419         usage();
420 }
421
422 my $prompting = 0;
423 if (!defined $sender) {
424         $sender = $repoauthor || $repocommitter || '';
425
426         while (1) {
427                 $_ = $term->readline("Who should the emails appear to be from? [$sender] ");
428                 last if defined $_;
429                 print "\n";
430         }
431
432         $sender = $_ if ($_);
433         print "Emails will be sent from: ", $sender, "\n";
434         $prompting++;
435 }
436
437 if (!@to) {
438
439
440         while (1) {
441                 $_ = $term->readline("Who should the emails be sent to? ", "");
442                 last if defined $_;
443                 print "\n";
444         }
445
446         my $to = $_;
447         push @to, split /,\s*/, $to;
448         $prompting++;
449 }
450
451 sub expand_aliases {
452         my @cur = @_;
453         my @last;
454         do {
455                 @last = @cur;
456                 @cur = map { $aliases{$_} ? @{$aliases{$_}} : $_ } @last;
457         } while (join(',',@cur) ne join(',',@last));
458         return @cur;
459 }
460
461 @to = expand_aliases(@to);
462 @to = (map { sanitize_address($_) } @to);
463 @initial_cc = expand_aliases(@initial_cc);
464 @bcclist = expand_aliases(@bcclist);
465
466 if (!defined $initial_subject && $compose) {
467         while (1) {
468                 $_ = $term->readline("What subject should the initial email start with? ", $initial_subject);
469                 last if defined $_;
470                 print "\n";
471         }
472
473         $initial_subject = $_;
474         $prompting++;
475 }
476
477 if ($thread && !defined $initial_reply_to && $prompting) {
478         while (1) {
479                 $_= $term->readline("Message-ID to be used as In-Reply-To for the first email? ", $initial_reply_to);
480                 last if defined $_;
481                 print "\n";
482         }
483
484         $initial_reply_to = $_;
485 }
486 if (defined $initial_reply_to) {
487         $initial_reply_to =~ s/^\s*<?//;
488         $initial_reply_to =~ s/>?\s*$//;
489         $initial_reply_to = "<$initial_reply_to>" if $initial_reply_to ne '';
490 }
491
492 if (!defined $smtp_server) {
493         foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
494                 if (-x $_) {
495                         $smtp_server = $_;
496                         last;
497                 }
498         }
499         $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
500 }
501
502 if ($compose) {
503         # Note that this does not need to be secure, but we will make a small
504         # effort to have it be unique
505         open(C,">",$compose_filename)
506                 or die "Failed to open for writing $compose_filename: $!";
507         print C "From $sender # This line is ignored.\n";
508         printf C "Subject: %s\n\n", $initial_subject;
509         printf C <<EOT;
510 GIT: Please enter your email below.
511 GIT: Lines beginning in "GIT: " will be removed.
512 GIT: Consider including an overall diffstat or table of contents
513 GIT: for the patch you are writing.
514
515 EOT
516         close(C);
517
518         my $editor = $ENV{GIT_EDITOR} || Git::config(@repo, "core.editor") || $ENV{VISUAL} || $ENV{EDITOR} || "vi";
519         system('sh', '-c', $editor.' "$@"', $editor, $compose_filename);
520
521         open(C2,">",$compose_filename . ".final")
522                 or die "Failed to open $compose_filename.final : " . $!;
523
524         open(C,"<",$compose_filename)
525                 or die "Failed to open $compose_filename : " . $!;
526
527         my $need_8bit_cte = file_has_nonascii($compose_filename);
528         my $in_body = 0;
529         while(<C>) {
530                 next if m/^GIT: /;
531                 if (!$in_body && /^\n$/) {
532                         $in_body = 1;
533                         if ($need_8bit_cte) {
534                                 print C2 "MIME-Version: 1.0\n",
535                                          "Content-Type: text/plain; ",
536                                            "charset=utf-8\n",
537                                          "Content-Transfer-Encoding: 8bit\n";
538                         }
539                 }
540                 if (!$in_body && /^MIME-Version:/i) {
541                         $need_8bit_cte = 0;
542                 }
543                 if (!$in_body && /^Subject: ?(.*)/i) {
544                         my $subject = $1;
545                         $_ = "Subject: " .
546                                 ($subject =~ /[^[:ascii:]]/ ?
547                                  quote_rfc2047($subject) :
548                                  $subject) .
549                                 "\n";
550                 }
551                 print C2 $_;
552         }
553         close(C);
554         close(C2);
555
556         while (1) {
557                 $_ = $term->readline("Send this email? (y|n) ");
558                 last if defined $_;
559                 print "\n";
560         }
561
562         if (uc substr($_,0,1) ne 'Y') {
563                 cleanup_compose_files();
564                 exit(0);
565         }
566
567         @files = ($compose_filename . ".final", @files);
568 }
569
570 # Variables we set as part of the loop over files
571 our ($message_id, %mail, $subject, $reply_to, $references, $message);
572
573 sub extract_valid_address {
574         my $address = shift;
575         my $local_part_regexp = '[^<>"\s@]+';
576         my $domain_regexp = '[^.<>"\s@]+(?:\.[^.<>"\s@]+)+';
577
578         # check for a local address:
579         return $address if ($address =~ /^($local_part_regexp)$/);
580
581         $address =~ s/^\s*<(.*)>\s*$/$1/;
582         if ($have_email_valid) {
583                 return scalar Email::Valid->address($address);
584         } else {
585                 # less robust/correct than the monster regexp in Email::Valid,
586                 # but still does a 99% job, and one less dependency
587                 $address =~ /($local_part_regexp\@$domain_regexp)/;
588                 return $1;
589         }
590 }
591
592 # Usually don't need to change anything below here.
593
594 # we make a "fake" message id by taking the current number
595 # of seconds since the beginning of Unix time and tacking on
596 # a random number to the end, in case we are called quicker than
597 # 1 second since the last time we were called.
598
599 # We'll setup a template for the message id, using the "from" address:
600
601 my ($message_id_stamp, $message_id_serial);
602 sub make_message_id
603 {
604         my $uniq;
605         if (!defined $message_id_stamp) {
606                 $message_id_stamp = sprintf("%s-%s", time, $$);
607                 $message_id_serial = 0;
608         }
609         $message_id_serial++;
610         $uniq = "$message_id_stamp-$message_id_serial";
611
612         my $du_part;
613         for ($sender, $repocommitter, $repoauthor) {
614                 $du_part = extract_valid_address(sanitize_address($_));
615                 last if (defined $du_part and $du_part ne '');
616         }
617         if (not defined $du_part or $du_part eq '') {
618                 use Sys::Hostname qw();
619                 $du_part = 'user@' . Sys::Hostname::hostname();
620         }
621         my $message_id_template = "<%s-git-send-email-%s>";
622         $message_id = sprintf($message_id_template, $uniq, $du_part);
623         #print "new message id = $message_id\n"; # Was useful for debugging
624 }
625
626
627
628 $time = time - scalar $#files;
629
630 sub unquote_rfc2047 {
631         local ($_) = @_;
632         my $encoding;
633         if (s/=\?([^?]+)\?q\?(.*)\?=/$2/g) {
634                 $encoding = $1;
635                 s/_/ /g;
636                 s/=([0-9A-F]{2})/chr(hex($1))/eg;
637         }
638         return wantarray ? ($_, $encoding) : $_;
639 }
640
641 sub quote_rfc2047 {
642         local $_ = shift;
643         my $encoding = shift || 'utf-8';
644         s/([^-a-zA-Z0-9!*+\/])/sprintf("=%02X", ord($1))/eg;
645         s/(.*)/=\?$encoding\?q\?$1\?=/;
646         return $_;
647 }
648
649 # use the simplest quoting being able to handle the recipient
650 sub sanitize_address
651 {
652         my ($recipient) = @_;
653         my ($recipient_name, $recipient_addr) = ($recipient =~ /^(.*?)\s*(<.*)/);
654
655         if (not $recipient_name) {
656                 return "$recipient";
657         }
658
659         # if recipient_name is already quoted, do nothing
660         if ($recipient_name =~ /^(".*"|=\?utf-8\?q\?.*\?=)$/) {
661                 return $recipient;
662         }
663
664         # rfc2047 is needed if a non-ascii char is included
665         if ($recipient_name =~ /[^[:ascii:]]/) {
666                 $recipient_name = quote_rfc2047($recipient_name);
667         }
668
669         # double quotes are needed if specials or CTLs are included
670         elsif ($recipient_name =~ /[][()<>@,;:\\".\000-\037\177]/) {
671                 $recipient_name =~ s/(["\\\r])/\\$1/g;
672                 $recipient_name = "\"$recipient_name\"";
673         }
674
675         return "$recipient_name $recipient_addr";
676
677 }
678
679 sub send_message
680 {
681         my @recipients = unique_email_list(@to);
682         @cc = (grep { my $cc = extract_valid_address($_);
683                       not grep { $cc eq $_ } @recipients
684                     }
685                map { sanitize_address($_) }
686                @cc);
687         my $to = join (",\n\t", @recipients);
688         @recipients = unique_email_list(@recipients,@cc,@bcclist);
689         @recipients = (map { extract_valid_address($_) } @recipients);
690         my $date = format_2822_time($time++);
691         my $gitversion = '@@GIT_VERSION@@';
692         if ($gitversion =~ m/..GIT_VERSION../) {
693             $gitversion = Git::version();
694         }
695
696         my $cc = join(", ", unique_email_list(@cc));
697         my $ccline = "";
698         if ($cc ne '') {
699                 $ccline = "\nCc: $cc";
700         }
701         my $sanitized_sender = sanitize_address($sender);
702         make_message_id() unless defined($message_id);
703
704         my $header = "From: $sanitized_sender
705 To: $to${ccline}
706 Subject: $subject
707 Date: $date
708 Message-Id: $message_id
709 X-Mailer: git-send-email $gitversion
710 ";
711         if ($thread && $reply_to) {
712
713                 $header .= "In-Reply-To: $reply_to\n";
714                 $header .= "References: $references\n";
715         }
716         if (@xh) {
717                 $header .= join("\n", @xh) . "\n";
718         }
719
720         my @sendmail_parameters = ('-i', @recipients);
721         my $raw_from = $sanitized_sender;
722         $raw_from = $envelope_sender if (defined $envelope_sender);
723         $raw_from = extract_valid_address($raw_from);
724         unshift (@sendmail_parameters,
725                         '-f', $raw_from) if(defined $envelope_sender);
726
727         if ($dry_run) {
728                 # We don't want to send the email.
729         } elsif ($smtp_server =~ m#^/#) {
730                 my $pid = open my $sm, '|-';
731                 defined $pid or die $!;
732                 if (!$pid) {
733                         exec($smtp_server, @sendmail_parameters) or die $!;
734                 }
735                 print $sm "$header\n$message";
736                 close $sm or die $?;
737         } else {
738
739                 if (!defined $smtp_server) {
740                         die "The required SMTP server is not properly defined."
741                 }
742
743                 if ($smtp_ssl) {
744                         $smtp_server_port ||= 465; # ssmtp
745                         require Net::SMTP::SSL;
746                         $smtp ||= Net::SMTP::SSL->new($smtp_server, Port => $smtp_server_port);
747                 }
748                 else {
749                         require Net::SMTP;
750                         $smtp ||= Net::SMTP->new((defined $smtp_server_port)
751                                                  ? "$smtp_server:$smtp_server_port"
752                                                  : $smtp_server);
753                 }
754
755                 if (!$smtp) {
756                         die "Unable to initialize SMTP properly.  Is there something wrong with your config?";
757                 }
758
759                 if (defined $smtp_authuser) {
760
761                         if (!defined $smtp_authpass) {
762
763                                 system "stty -echo";
764
765                                 do {
766                                         print "Password: ";
767                                         $_ = <STDIN>;
768                                         print "\n";
769                                 } while (!defined $_);
770
771                                 chomp($smtp_authpass = $_);
772
773                                 system "stty echo";
774                         }
775
776                         $auth ||= $smtp->auth( $smtp_authuser, $smtp_authpass ) or die $smtp->message;
777                 }
778
779                 $smtp->mail( $raw_from ) or die $smtp->message;
780                 $smtp->to( @recipients ) or die $smtp->message;
781                 $smtp->data or die $smtp->message;
782                 $smtp->datasend("$header\n$message") or die $smtp->message;
783                 $smtp->dataend() or die $smtp->message;
784                 $smtp->ok or die "Failed to send $subject\n".$smtp->message;
785         }
786         if ($quiet) {
787                 printf (($dry_run ? "Dry-" : "")."Sent %s\n", $subject);
788         } else {
789                 print (($dry_run ? "Dry-" : "")."OK. Log says:\n");
790                 if ($smtp_server !~ m#^/#) {
791                         print "Server: $smtp_server\n";
792                         print "MAIL FROM:<$raw_from>\n";
793                         print "RCPT TO:".join(',',(map { "<$_>" } @recipients))."\n";
794                 } else {
795                         print "Sendmail: $smtp_server ".join(' ',@sendmail_parameters)."\n";
796                 }
797                 print $header, "\n";
798                 if ($smtp) {
799                         print "Result: ", $smtp->code, ' ',
800                                 ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
801                 } else {
802                         print "Result: OK\n";
803                 }
804         }
805 }
806
807 $reply_to = $initial_reply_to;
808 $references = $initial_reply_to || '';
809 $subject = $initial_subject;
810
811 foreach my $t (@files) {
812         open(F,"<",$t) or die "can't open file $t";
813
814         my $author = undef;
815         my $author_encoding;
816         my $has_content_type;
817         my $body_encoding;
818         @cc = @initial_cc;
819         @xh = ();
820         my $input_format = undef;
821         my $header_done = 0;
822         $message = "";
823         while(<F>) {
824                 if (!$header_done) {
825                         if (/^From /) {
826                                 $input_format = 'mbox';
827                                 next;
828                         }
829                         chomp;
830                         if (!defined $input_format && /^[-A-Za-z]+:\s/) {
831                                 $input_format = 'mbox';
832                         }
833
834                         if (defined $input_format && $input_format eq 'mbox') {
835                                 if (/^Subject:\s+(.*)$/) {
836                                         $subject = $1;
837
838                                 } elsif (/^(Cc|From):\s+(.*)$/) {
839                                         if (unquote_rfc2047($2) eq $sender) {
840                                                 next if ($suppress_cc{'self'});
841                                         }
842                                         elsif ($1 eq 'From') {
843                                                 ($author, $author_encoding)
844                                                   = unquote_rfc2047($2);
845                                                 next if ($suppress_cc{'author'});
846                                         } else {
847                                                 next if ($suppress_cc{'cc'});
848                                         }
849                                         printf("(mbox) Adding cc: %s from line '%s'\n",
850                                                 $2, $_) unless $quiet;
851                                         push @cc, $2;
852                                 }
853                                 elsif (/^Content-type:/i) {
854                                         $has_content_type = 1;
855                                         if (/charset="?[^ "]+/) {
856                                                 $body_encoding = $1;
857                                         }
858                                         push @xh, $_;
859                                 }
860                                 elsif (/^Message-Id: (.*)/i) {
861                                         $message_id = $1;
862                                 }
863                                 elsif (!/^Date:\s/ && /^[-A-Za-z]+:\s+\S/) {
864                                         push @xh, $_;
865                                 }
866
867                         } else {
868                                 # In the traditional
869                                 # "send lots of email" format,
870                                 # line 1 = cc
871                                 # line 2 = subject
872                                 # So let's support that, too.
873                                 $input_format = 'lots';
874                                 if (@cc == 0 && !$suppress_cc{'cc'}) {
875                                         printf("(non-mbox) Adding cc: %s from line '%s'\n",
876                                                 $_, $_) unless $quiet;
877
878                                         push @cc, $_;
879
880                                 } elsif (!defined $subject) {
881                                         $subject = $_;
882                                 }
883                         }
884
885                         # A whitespace line will terminate the headers
886                         if (m/^\s*$/) {
887                                 $header_done = 1;
888                         }
889                 } else {
890                         $message .=  $_;
891                         if (/^(Signed-off-by|Cc): (.*)$/i) {
892                                 next if ($suppress_cc{'sob'});
893                                 chomp;
894                                 my $c = $2;
895                                 chomp $c;
896                                 next if ($c eq $sender and $suppress_cc{'self'});
897                                 push @cc, $c;
898                                 printf("(sob) Adding cc: %s from line '%s'\n",
899                                         $c, $_) unless $quiet;
900                         }
901                 }
902         }
903         close F;
904
905         if (defined $cc_cmd && !$suppress_cc{'cccmd'}) {
906                 open(F, "$cc_cmd $t |")
907                         or die "(cc-cmd) Could not execute '$cc_cmd'";
908                 while(<F>) {
909                         my $c = $_;
910                         $c =~ s/^\s*//g;
911                         $c =~ s/\n$//g;
912                         next if ($c eq $sender and $suppress_from);
913                         push @cc, $c;
914                         printf("(cc-cmd) Adding cc: %s from: '%s'\n",
915                                 $c, $cc_cmd) unless $quiet;
916                 }
917                 close F
918                         or die "(cc-cmd) failed to close pipe to '$cc_cmd'";
919         }
920
921         if (defined $author) {
922                 $message = "From: $author\n\n$message";
923                 if (defined $author_encoding) {
924                         if ($has_content_type) {
925                                 if ($body_encoding eq $author_encoding) {
926                                         # ok, we already have the right encoding
927                                 }
928                                 else {
929                                         # uh oh, we should re-encode
930                                 }
931                         }
932                         else {
933                                 push @xh,
934                                   'MIME-Version: 1.0',
935                                   "Content-Type: text/plain; charset=$author_encoding",
936                                   'Content-Transfer-Encoding: 8bit';
937                         }
938                 }
939         }
940
941         send_message();
942
943         # set up for the next message
944         if ($chain_reply_to || !defined $reply_to || length($reply_to) == 0) {
945                 $reply_to = $message_id;
946                 if (length $references > 0) {
947                         $references .= "\n $message_id";
948                 } else {
949                         $references = "$message_id";
950                 }
951         }
952         $message_id = undef;
953 }
954
955 if ($compose) {
956         cleanup_compose_files();
957 }
958
959 sub cleanup_compose_files() {
960         unlink($compose_filename, $compose_filename . ".final");
961
962 }
963
964 $smtp->quit if $smtp;
965
966 sub unique_email_list(@) {
967         my %seen;
968         my @emails;
969
970         foreach my $entry (@_) {
971                 if (my $clean = extract_valid_address($entry)) {
972                         $seen{$clean} ||= 0;
973                         next if $seen{$clean}++;
974                         push @emails, $entry;
975                 } else {
976                         print STDERR "W: unable to extract a valid address",
977                                         " from: $entry\n";
978                 }
979         }
980         return @emails;
981 }
982
983 sub validate_patch {
984         my $fn = shift;
985         open(my $fh, '<', $fn)
986                 or die "unable to open $fn: $!\n";
987         while (my $line = <$fh>) {
988                 if (length($line) > 998) {
989                         return "$.: patch contains a line longer than 998 characters";
990                 }
991         }
992         return undef;
993 }
994
995 sub file_has_nonascii {
996         my $fn = shift;
997         open(my $fh, '<', $fn)
998                 or die "unable to open $fn: $!\n";
999         while (my $line = <$fh>) {
1000                 return 1 if $line =~ /[^[:ascii:]]/;
1001         }
1002         return 0;
1003 }