]> git.ipfire.org Git - thirdparty/git.git/blame - git-send-email.perl
Document send-email --smtp-domain
[thirdparty/git.git] / git-send-email.perl
CommitLineData
83b24437 1#!/usr/bin/perl -w
83b24437 2#
f3d9f354
RA
3# Copyright 2002,2005 Greg Kroah-Hartman <greg@kroah.com>
4# Copyright 2005 Ryan Anderson <ryan@michonline.com>
83b24437
RA
5#
6# GPL v2 (See COPYING)
5825e5b2 7#
83b24437
RA
8# Ported to support git "mbox" format files by Ryan Anderson <ryan@michonline.com>
9#
f3d9f354 10# Sends a collection of emails to the given email addresses, disturbingly fast.
5825e5b2 11#
f3d9f354
RA
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:
5825e5b2 15# first line of the message is who to CC,
f3d9f354 16# and second line is the subject of the message.
5825e5b2 17#
83b24437
RA
18
19use strict;
20use warnings;
21use Term::ReadLine;
83b24437 22use Getopt::Long;
0e73b3ee 23use Text::ParseWords;
83b24437 24use Data::Dumper;
412876dc 25use Term::ANSIColor;
eed6ca7c 26use File::Temp qw/ tempdir tempfile /;
5df9fcf6 27use Error qw(:try);
3cb8caf7 28use Git;
83b24437 29
5df9fcf6
PH
30Getopt::Long::Configure qw/ pass_through /;
31
280242d1
JH
32package FakeTerm;
33sub new {
34 my ($class, $reason) = @_;
35 return bless \$reason, shift;
36}
37sub readline {
38 my $self = shift;
39 die "Cannot use readline on FakeTerm: $$self";
40}
41package main;
42
1b0baf14
MC
43
44sub usage {
45 print <<EOT;
5df9fcf6 46git send-email [options] <file | directory | rev-list options >
4ed62b03
MW
47
48 Composing:
49 --from <str> * Email From:
50 --to <str> * Email To:
51 --cc <str> * Email Cc:
52 --bcc <str> * Email Bcc:
53 --subject <str> * Email "Subject:"
54 --in-reply-to <str> * Email "In-Reply-To:"
8fd5bb7f 55 --annotate * Review each patch that will be sent in an editor.
4ed62b03
MW
56 --compose * Open an editor for introduction.
57
58 Sending:
59 --envelope-sender <str> * Email envelope sender.
60 --smtp-server <str:int> * Outgoing SMTP server to use. The port
61 is optional. Default 'localhost'.
62 --smtp-server-port <int> * Outgoing SMTP server port.
63 --smtp-user <str> * Username for SMTP-AUTH.
64 --smtp-pass <str> * Password for SMTP-AUTH; not necessary.
65 --smtp-encryption <str> * tls or ssl; anything else disables.
66 --smtp-ssl * Deprecated. Use '--smtp-encryption ssl'.
134550fe 67 --smtp-domain <str> * The domain name sent to HELO/EHLO handshake
f60812ef 68 --smtp-debug <0|1> * Disable, enable Net::SMTP debug.
4ed62b03
MW
69
70 Automating:
71 --identity <str> * Use the sendemail.<id> options.
72 --cc-cmd <str> * Email Cc: via `<str> \$patch_path`
3531e270
JS
73 --suppress-cc <str> * author, self, sob, cc, cccmd, body, bodycc, all.
74 --[no-]signed-off-by-cc * Send to Signed-off-by: addresses. Default on.
4ed62b03 75 --[no-]suppress-from * Send to self. Default off.
41fe87fa 76 --[no-]chain-reply-to * Chain In-Reply-To: fields. Default off.
4ed62b03
MW
77 --[no-]thread * Use In-Reply-To: field. Default on.
78
79 Administering:
c1f2aa45
JS
80 --confirm <str> * Confirm recipients before sending;
81 auto, cc, compose, always, or never.
4ed62b03
MW
82 --quiet * Output one line of info per email.
83 --dry-run * Don't actually send the emails.
84 --[no-]validate * Perform patch sanity checks. Default on.
5df9fcf6
PH
85 --[no-]format-patch * understand any non optional arguments as
86 `git format-patch` ones.
c764a0c2 87
1b0baf14
MC
88EOT
89 exit(1);
90}
91
4bc87a28 92# most mail servers generate the Date: header, but not all...
6bdca890
JN
93sub format_2822_time {
94 my ($time) = @_;
95 my @localtm = localtime($time);
96 my @gmttm = gmtime($time);
97 my $localmin = $localtm[1] + $localtm[2] * 60;
98 my $gmtmin = $gmttm[1] + $gmttm[2] * 60;
99 if ($localtm[0] != $gmttm[0]) {
100 die "local zone differs from GMT by a non-minute interval\n";
101 }
102 if ((($gmttm[6] + 1) % 7) == $localtm[6]) {
103 $localmin += 1440;
104 } elsif ((($gmttm[6] - 1) % 7) == $localtm[6]) {
105 $localmin -= 1440;
106 } elsif ($gmttm[6] != $localtm[6]) {
107 die "local time offset greater than or equal to 24 hours\n";
108 }
109 my $offset = $localmin - $gmtmin;
110 my $offhour = $offset / 60;
111 my $offmin = abs($offset % 60);
112 if (abs($offhour) >= 24) {
113 die ("local time offset greater than or equal to 24 hours\n");
114 }
115
116 return sprintf("%s, %2d %s %d %02d:%02d:%02d %s%02d%02d",
117 qw(Sun Mon Tue Wed Thu Fri Sat)[$localtm[6]],
118 $localtm[3],
119 qw(Jan Feb Mar Apr May Jun
120 Jul Aug Sep Oct Nov Dec)[$localtm[4]],
121 $localtm[5]+1900,
122 $localtm[2],
123 $localtm[1],
124 $localtm[0],
125 ($offset >= 0) ? '+' : '-',
126 abs($offhour),
127 $offmin,
128 );
129}
4bc87a28 130
567ffeb7 131my $have_email_valid = eval { require Email::Valid; 1 };
5012699d 132my $have_mail_address = eval { require Mail::Address; 1 };
4bc87a28 133my $smtp;
5f5b6118 134my $auth;
134550fe
JA
135my $mail_domain_default = "localhost.localdomain";
136my $mail_domain;
4bc87a28 137
e205735d 138sub unique_email_list(@);
1f038a0c
RA
139sub cleanup_compose_files();
140
83b24437 141# Variables we fill in automatically, or via prompting:
ce91c2f6 142my (@to,@cc,@initial_cc,@bcclist,@xh,
8fd5bb7f
PH
143 $initial_reply_to,$initial_subject,@files,
144 $author,$sender,$smtp_authpass,$annotate,$compose,$time);
83b24437 145
f073a592 146my $envelope_sender;
78488b2c 147
9133261f 148# Example reply to:
83b24437 149#$initial_reply_to = ''; #<20050203173208.GA23964@foobar.com>';
83b24437 150
ad79c024
FL
151my $repo = eval { Git->repository() };
152my @repo = $repo ? ($repo) : ();
280242d1 153my $term = eval {
0fb7fc75
JS
154 $ENV{"GIT_SEND_EMAIL_NOTTY"}
155 ? new Term::ReadLine 'git-send-email', \*STDIN, \*STDOUT
156 : new Term::ReadLine 'git-send-email';
280242d1
JH
157};
158if ($@) {
159 $term = new FakeTerm "$@: going non-interactive";
160}
83b24437 161
5483c71d
AR
162# Behavior modification variables
163my ($quiet, $dry_run) = (0, 0);
5df9fcf6 164my $format_patch;
afe756c9 165my $compose_filename;
5483c71d 166
8fd5bb7f
PH
167# Handle interactive edition of files.
168my $multiedit;
b4479f07
JN
169my $editor = Git::command_oneline('var', 'GIT_EDITOR');
170
8fd5bb7f
PH
171sub do_edit {
172 if (defined($multiedit) && !$multiedit) {
beece9da
PH
173 map {
174 system('sh', '-c', $editor.' "$@"', $editor, $_);
175 if (($? & 127) || ($? >> 8)) {
176 die("the editor exited uncleanly, aborting everything");
177 }
178 } @_;
8fd5bb7f
PH
179 } else {
180 system('sh', '-c', $editor.' "$@"', $editor, @_);
beece9da
PH
181 if (($? & 127) || ($? >> 8)) {
182 die("the editor exited uncleanly, aborting everything");
183 }
8fd5bb7f
PH
184 }
185}
5483c71d
AR
186
187# Variables with corresponding config settings
ddc3d4fe 188my ($thread, $chain_reply_to, $suppress_from, $signed_off_by_cc, $cc_cmd);
f6bebd12 189my ($smtp_server, $smtp_server_port, $smtp_authuser, $smtp_encryption);
44b2476a 190my ($identity, $aliasfiletype, @alias_files, @smtp_host_parts);
c1f2aa45 191my ($validate, $confirm);
65648283 192my (@suppress_cc);
5483c71d 193
f60812ef
JA
194my ($debug_net_smtp) = 0; # Net::SMTP, see send_message()
195
528fb087
NS
196my $not_set_by_user = "true but not set by the user";
197
34cc60ce 198my %config_bool_settings = (
5483c71d 199 "thread" => [\$thread, 1],
528fb087 200 "chainreplyto" => [\$chain_reply_to, $not_set_by_user],
65648283 201 "suppressfrom" => [\$suppress_from, undef],
ddc3d4fe
MW
202 "signedoffbycc" => [\$signed_off_by_cc, undef],
203 "signedoffcc" => [\$signed_off_by_cc, undef], # Deprecated
dbf5e1e9 204 "validate" => [\$validate, 1],
e46f7a0e
AR
205);
206
34cc60ce
DS
207my %config_settings = (
208 "smtpserver" => \$smtp_server,
44b2476a 209 "smtpserverport" => \$smtp_server_port,
34cc60ce
DS
210 "smtpuser" => \$smtp_authuser,
211 "smtppass" => \$smtp_authpass,
2db9b49c 212 "to" => \@to,
5f8b9fcd 213 "cc" => \@initial_cc,
34cc60ce
DS
214 "cccmd" => \$cc_cmd,
215 "aliasfiletype" => \$aliasfiletype,
216 "bcc" => \@bcclist,
217 "aliasesfile" => \@alias_files,
65648283 218 "suppresscc" => \@suppress_cc,
9f7820ae 219 "envelopesender" => \$envelope_sender,
8fd5bb7f 220 "multiedit" => \$multiedit,
c1f2aa45 221 "confirm" => \$confirm,
09caa24f 222 "from" => \$sender,
34cc60ce 223);
4a62d3f5 224
528fb087
NS
225# Help users prepare for 1.7.0
226sub chain_reply_to {
227 if (defined $chain_reply_to &&
228 $chain_reply_to eq $not_set_by_user) {
229 print STDERR
a19f101e 230 "In git 1.7.0, the default has changed to --no-chain-reply-to\n" .
528fb087
NS
231 "Set sendemail.chainreplyto configuration variable to true if\n" .
232 "you want to keep --chain-reply-to as your default.\n";
a19f101e 233 $chain_reply_to = 0;
528fb087
NS
234 }
235 return $chain_reply_to;
236}
237
87429976
MW
238# Handle Uncouth Termination
239sub signal_handler {
240
241 # Make text normal
242 print color("reset"), "\n";
243
244 # SMTP password masked
245 system "stty echo";
246
247 # tmp files from --compose
afe756c9
JS
248 if (defined $compose_filename) {
249 if (-e $compose_filename) {
250 print "'$compose_filename' contains an intermediate version of the email you were composing.\n";
251 }
252 if (-e ($compose_filename . ".final")) {
253 print "'$compose_filename.final' contains the composed email.\n"
254 }
87429976
MW
255 }
256
257 exit;
258};
259
260$SIG{TERM} = \&signal_handler;
261$SIG{INT} = \&signal_handler;
262
83b24437
RA
263# Begin by accumulating all the variables (defined above), that we will end up
264# needing, first, from the command line:
265
94638f89 266my $rc = GetOptions("sender|from=s" => \$sender,
83b24437
RA
267 "in-reply-to=s" => \$initial_reply_to,
268 "subject=s" => \$initial_subject,
269 "to=s" => \@to,
da140f8b 270 "cc=s" => \@initial_cc,
58063245 271 "bcc=s" => \@bcclist,
78488b2c 272 "chain-reply-to!" => \$chain_reply_to,
3342d850 273 "smtp-server=s" => \$smtp_server,
44b2476a 274 "smtp-server-port=s" => \$smtp_server_port,
34cc60ce 275 "smtp-user=s" => \$smtp_authuser,
2363d746 276 "smtp-pass:s" => \$smtp_authpass,
f6bebd12
TR
277 "smtp-ssl" => sub { $smtp_encryption = 'ssl' },
278 "smtp-encryption=s" => \$smtp_encryption,
f60812ef 279 "smtp-debug:i" => \$debug_net_smtp,
134550fe 280 "smtp-domain:s" => \$mail_domain,
34cc60ce 281 "identity=s" => \$identity,
8fd5bb7f 282 "annotate" => \$annotate,
1f038a0c 283 "compose" => \$compose,
30d08b34 284 "quiet" => \$quiet,
324a8bd0 285 "cc-cmd=s" => \$cc_cmd,
5483c71d 286 "suppress-from!" => \$suppress_from,
65648283 287 "suppress-cc=s" => \@suppress_cc,
ddc3d4fe 288 "signed-off-cc|signed-off-by-cc!" => \$signed_off_by_cc,
c1f2aa45 289 "confirm=s" => \$confirm,
6130259c 290 "dry-run" => \$dry_run,
f073a592 291 "envelope-sender=s" => \$envelope_sender,
5483c71d 292 "thread!" => \$thread,
dbf5e1e9 293 "validate!" => \$validate,
5df9fcf6 294 "format-patch!" => \$format_patch,
83b24437
RA
295 );
296
1b0baf14
MC
297unless ($rc) {
298 usage();
299}
300
eed6ca7c
JS
301die "Cannot run git format-patch from outside a repository\n"
302 if $format_patch and not $repo;
303
34cc60ce
DS
304# Now, let's fill any that aren't set in with defaults:
305
306sub read_config {
307 my ($prefix) = @_;
308
309 foreach my $setting (keys %config_bool_settings) {
310 my $target = $config_bool_settings{$setting}->[0];
ad79c024 311 $$target = Git::config_bool(@repo, "$prefix.$setting") unless (defined $$target);
34cc60ce
DS
312 }
313
314 foreach my $setting (keys %config_settings) {
315 my $target = $config_settings{$setting};
316 if (ref($target) eq "ARRAY") {
317 unless (@$target) {
ad79c024 318 my @values = Git::config(@repo, "$prefix.$setting");
34cc60ce
DS
319 @$target = @values if (@values && defined $values[0]);
320 }
321 }
322 else {
ad79c024 323 $$target = Git::config(@repo, "$prefix.$setting") unless (defined $$target);
34cc60ce
DS
324 }
325 }
f6bebd12
TR
326
327 if (!defined $smtp_encryption) {
328 my $enc = Git::config(@repo, "$prefix.smtpencryption");
329 if (defined $enc) {
330 $smtp_encryption = $enc;
331 } elsif (Git::config_bool(@repo, "$prefix.smtpssl")) {
332 $smtp_encryption = 'ssl';
333 }
334 }
34cc60ce
DS
335}
336
337# read configuration from [sendemail "$identity"], fall back on [sendemail]
ad79c024 338$identity = Git::config(@repo, "sendemail.identity") unless (defined $identity);
34cc60ce
DS
339read_config("sendemail.$identity") if (defined $identity);
340read_config("sendemail");
341
342# fall back on builtin bool defaults
343foreach my $setting (values %config_bool_settings) {
344 ${$setting->[0]} = $setting->[1] unless (defined (${$setting->[0]}));
345}
346
fa835cd5
TR
347# 'default' encryption is none -- this only prevents a warning
348$smtp_encryption = '' unless (defined $smtp_encryption);
349
65648283
DB
350# Set CC suppressions
351my(%suppress_cc);
352if (@suppress_cc) {
353 foreach my $entry (@suppress_cc) {
354 die "Unknown --suppress-cc field: '$entry'\n"
3531e270 355 unless $entry =~ /^(all|cccmd|cc|author|self|sob|body|bodycc)$/;
65648283
DB
356 $suppress_cc{$entry} = 1;
357 }
358}
359
360if ($suppress_cc{'all'}) {
cb8a9bd5 361 foreach my $entry (qw (cccmd cc author self sob body bodycc)) {
65648283
DB
362 $suppress_cc{$entry} = 1;
363 }
364 delete $suppress_cc{'all'};
365}
366
367# If explicit old-style ones are specified, they trump --suppress-cc.
368$suppress_cc{'self'} = $suppress_from if defined $suppress_from;
ddc3d4fe 369$suppress_cc{'sob'} = !$signed_off_by_cc if defined $signed_off_by_cc;
65648283 370
3531e270
JS
371if ($suppress_cc{'body'}) {
372 foreach my $entry (qw (sob bodycc)) {
373 $suppress_cc{$entry} = 1;
374 }
375 delete $suppress_cc{'body'};
376}
377
c1f2aa45
JS
378# Set confirm's default value
379my $confirm_unconfigured = !defined $confirm;
380if ($confirm_unconfigured) {
381 $confirm = scalar %suppress_cc ? 'compose' : 'auto';
382};
383die "Unknown --confirm setting: '$confirm'\n"
384 unless $confirm =~ /^(?:auto|cc|compose|always|never)/;
385
65648283
DB
386# Debugging, print out the suppressions.
387if (0) {
388 print "suppressions:\n";
389 foreach my $entry (keys %suppress_cc) {
390 printf " %-5s -> $suppress_cc{$entry}\n", $entry;
391 }
392}
393
ad79c024
FL
394my ($repoauthor, $repocommitter);
395($repoauthor) = Git::ident_person(@repo, 'author');
396($repocommitter) = Git::ident_person(@repo, 'committer');
34cc60ce 397
79ee555b
EB
398# Verify the user input
399
400foreach my $entry (@to) {
401 die "Comma in --to entry: $entry'\n" unless $entry !~ m/,/;
402}
403
404foreach my $entry (@initial_cc) {
405 die "Comma in --cc entry: $entry'\n" unless $entry !~ m/,/;
406}
407
408foreach my $entry (@bcclist) {
409 die "Comma in --bcclist entry: $entry'\n" unless $entry !~ m/,/;
410}
411
5012699d
JS
412sub parse_address_line {
413 if ($have_mail_address) {
414 return map { $_->format } Mail::Address->parse($_[0]);
415 } else {
416 return split_addrs($_[0]);
417 }
418}
419
0e73b3ee 420sub split_addrs {
2f0e7cbb 421 return quotewords('\s*,\s*', 1, @_);
0e73b3ee
WF
422}
423
994d6c66 424my %aliases;
994d6c66
EW
425my %parse_alias = (
426 # multiline formats can be supported in the future
427 mutt => sub { my $fh = shift; while (<$fh>) {
ffc01f9b 428 if (/^\s*alias\s+(?:-group\s+\S+\s+)*(\S+)\s+(.*)$/) {
994d6c66
EW
429 my ($alias, $addr) = ($1, $2);
430 $addr =~ s/#.*$//; # mutt allows # comments
431 # commas delimit multiple addresses
0e73b3ee 432 $aliases{$alias} = [ split_addrs($addr) ];
994d6c66
EW
433 }}},
434 mailrc => sub { my $fh = shift; while (<$fh>) {
435 if (/^alias\s+(\S+)\s+(.*)$/) {
436 # spaces delimit multiple addresses
fe87c921 437 $aliases{$1} = [ quotewords('\s+', 0, $2) ];
994d6c66 438 }}},
73c427eb
TP
439 pine => sub { my $fh = shift; my $f='\t[^\t]*';
440 for (my $x = ''; defined($x); $x = $_) {
441 chomp $x;
442 $x .= $1 while(defined($_ = <$fh>) && /^ +(.*)$/);
443 $x =~ /^(\S+)$f\t\(?([^\t]+?)\)?(:?$f){0,2}$/ or next;
0e73b3ee 444 $aliases{$1} = [ split_addrs($2) ];
73c427eb 445 }},
7613ea35
BP
446 elm => sub { my $fh = shift;
447 while (<$fh>) {
448 if (/^(\S+)\s+=\s+[^=]+=\s(\S+)/) {
449 my ($alias, $addr) = ($1, $2);
450 $aliases{$alias} = [ split_addrs($addr) ];
451 }
452 } },
453
994d6c66
EW
454 gnus => sub { my $fh = shift; while (<$fh>) {
455 if (/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) {
456 $aliases{$1} = [ $2 ];
457 }}}
458);
459
3cb8caf7 460if (@alias_files and $aliasfiletype and defined $parse_alias{$aliasfiletype}) {
994d6c66
EW
461 foreach my $file (@alias_files) {
462 open my $fh, '<', $file or die "opening $file: $!\n";
463 $parse_alias{$aliasfiletype}->($fh);
464 close $fh;
465 }
466}
467
94638f89 468($sender) = expand_aliases($sender) if defined $sender;
ae740a58 469
5df9fcf6
PH
470# returns 1 if the conflict must be solved using it as a format-patch argument
471sub check_file_rev_conflict($) {
eed6ca7c 472 return unless $repo;
5df9fcf6
PH
473 my $f = shift;
474 try {
475 $repo->command('rev-parse', '--verify', '--quiet', $f);
476 if (defined($format_patch)) {
5df9fcf6
PH
477 return $format_patch;
478 }
479 die(<<EOF);
480File '$f' exists but it could also be the range of commits
481to produce patches for. Please disambiguate by...
482
483 * Saying "./$f" if you mean a file; or
484 * Giving --format-patch option if you mean a range.
485EOF
486 } catch Git::Error::Command with {
487 return 0;
488 }
489}
490
aa54892f
JK
491# Now that all the defaults are set, process the rest of the command line
492# arguments and collect up the files that need to be processed.
5df9fcf6 493my @rev_list_opts;
69f4ce55 494while (defined(my $f = shift @ARGV)) {
5df9fcf6
PH
495 if ($f eq "--") {
496 push @rev_list_opts, "--", @ARGV;
497 @ARGV = ();
498 } elsif (-d $f and !check_file_rev_conflict($f)) {
aa54892f
JK
499 opendir(DH,$f)
500 or die "Failed to opendir $f: $!";
501
502 push @files, grep { -f $_ } map { +$f . "/" . $_ }
503 sort readdir(DH);
8c178687 504 closedir(DH);
5df9fcf6 505 } elsif ((-f $f or -p $f) and !check_file_rev_conflict($f)) {
aa54892f 506 push @files, $f;
aa54892f 507 } else {
5df9fcf6 508 push @rev_list_opts, $f;
aa54892f
JK
509 }
510}
511
5df9fcf6 512if (@rev_list_opts) {
eed6ca7c
JS
513 die "Cannot run git format-patch from outside a repository\n"
514 unless $repo;
5df9fcf6
PH
515 push @files, $repo->command('format-patch', '-o', tempdir(CLEANUP => 1), @rev_list_opts);
516}
517
dbf5e1e9 518if ($validate) {
c764a0c2 519 foreach my $f (@files) {
300913bd
KB
520 unless (-p $f) {
521 my $error = validate_patch($f);
522 $error and die "fatal: $f: $error\nwarning: no patches were sent\n";
523 }
c764a0c2 524 }
747bbff9
JK
525}
526
aa54892f
JK
527if (@files) {
528 unless ($quiet) {
529 print $_,"\n" for (@files);
530 }
531} else {
532 print STDERR "\nNo patch files specified!\n\n";
533 usage();
534}
535
beece9da
PH
536sub get_patch_subject($) {
537 my $fn = shift;
538 open (my $fh, '<', $fn);
539 while (my $line = <$fh>) {
540 next unless ($line =~ /^Subject: (.*)$/);
541 close $fh;
542 return "GIT: $1\n";
543 }
544 close $fh;
545 die "No subject line in $fn ?";
546}
547
548if ($compose) {
549 # Note that this does not need to be secure, but we will make a small
550 # effort to have it be unique
afe756c9
JS
551 $compose_filename = ($repo ?
552 tempfile(".gitsendemail.msg.XXXXXX", DIR => $repo->repo_path()) :
553 tempfile(".gitsendemail.msg.XXXXXX", DIR => "."))[1];
beece9da
PH
554 open(C,">",$compose_filename)
555 or die "Failed to open for writing $compose_filename: $!";
556
557
558 my $tpl_sender = $sender || $repoauthor || $repocommitter || '';
559 my $tpl_subject = $initial_subject || '';
560 my $tpl_reply_to = $initial_reply_to || '';
561
562 print C <<EOT;
563From $tpl_sender # This line is ignored.
40e6e8a0 564GIT: Lines beginning in "GIT:" will be removed.
beece9da
PH
565GIT: Consider including an overall diffstat or table of contents
566GIT: for the patch you are writing.
567GIT:
568GIT: Clear the body content if you don't wish to send a summary.
569From: $tpl_sender
570Subject: $tpl_subject
571In-Reply-To: $tpl_reply_to
572
573EOT
574 for my $f (@files) {
575 print C get_patch_subject($f);
576 }
577 close(C);
578
beece9da
PH
579 if ($annotate) {
580 do_edit($compose_filename, @files);
581 } else {
582 do_edit($compose_filename);
583 }
584
585 open(C2,">",$compose_filename . ".final")
586 or die "Failed to open $compose_filename.final : " . $!;
587
588 open(C,"<",$compose_filename)
589 or die "Failed to open $compose_filename : " . $!;
590
591 my $need_8bit_cte = file_has_nonascii($compose_filename);
592 my $in_body = 0;
593 my $summary_empty = 1;
594 while(<C>) {
40e6e8a0 595 next if m/^GIT:/;
beece9da
PH
596 if ($in_body) {
597 $summary_empty = 0 unless (/^\n$/);
598 } elsif (/^\n$/) {
599 $in_body = 1;
600 if ($need_8bit_cte) {
601 print C2 "MIME-Version: 1.0\n",
602 "Content-Type: text/plain; ",
d1fff6fc 603 "charset=UTF-8\n",
beece9da
PH
604 "Content-Transfer-Encoding: 8bit\n";
605 }
606 } elsif (/^MIME-Version:/i) {
607 $need_8bit_cte = 0;
608 } elsif (/^Subject:\s*(.+)\s*$/i) {
609 $initial_subject = $1;
610 my $subject = $initial_subject;
611 $_ = "Subject: " .
612 ($subject =~ /[^[:ascii:]]/ ?
613 quote_rfc2047($subject) :
614 $subject) .
615 "\n";
616 } elsif (/^In-Reply-To:\s*(.+)\s*$/i) {
617 $initial_reply_to = $1;
618 next;
619 } elsif (/^From:\s*(.+)\s*$/i) {
620 $sender = $1;
621 next;
622 } elsif (/^(?:To|Cc|Bcc):/i) {
623 print "To/Cc/Bcc fields are not interpreted yet, they have been ignored\n";
624 next;
625 }
626 print C2 $_;
627 }
628 close(C);
629 close(C2);
630
631 if ($summary_empty) {
632 print "Summary email is empty, skipping it\n";
633 $compose = -1;
634 }
635} elsif ($annotate) {
636 do_edit(@files);
637}
638
6e182518
JS
639sub ask {
640 my ($prompt, %arg) = @_;
0da43a68 641 my $valid_re = $arg{valid_re};
6e182518
JS
642 my $default = $arg{default};
643 my $resp;
644 my $i = 0;
5906f54e
JS
645 return defined $default ? $default : undef
646 unless defined $term->IN and defined fileno($term->IN) and
647 defined $term->OUT and defined fileno($term->OUT);
6e182518
JS
648 while ($i++ < 10) {
649 $resp = $term->readline($prompt);
650 if (!defined $resp) { # EOF
651 print "\n";
652 return defined $default ? $default : undef;
653 }
654 if ($resp eq '' and defined $default) {
655 return $default;
656 }
0da43a68 657 if (!defined $valid_re or $resp =~ /$valid_re/) {
6e182518
JS
658 return $resp;
659 }
660 }
661 return undef;
662}
663
1f038a0c 664my $prompting = 0;
94638f89 665if (!defined $sender) {
ad79c024 666 $sender = $repoauthor || $repocommitter || '';
6e182518
JS
667 $sender = ask("Who should the emails appear to be from? [$sender] ",
668 default => $sender);
94638f89 669 print "Emails will be sent from: ", $sender, "\n";
1f038a0c 670 $prompting++;
83b24437
RA
671}
672
673if (!@to) {
6e182518
JS
674 my $to = ask("Who should the emails be sent to? ");
675 push @to, parse_address_line($to) if defined $to; # sanitized/validated later
1f038a0c 676 $prompting++;
83b24437
RA
677}
678
994d6c66 679sub expand_aliases {
302e04ea
JK
680 return map { expand_one_alias($_) } @_;
681}
682
683my %EXPANDED_ALIASES;
684sub expand_one_alias {
685 my $alias = shift;
686 if ($EXPANDED_ALIASES{$alias}) {
687 die "fatal: alias '$alias' expands to itself\n";
688 }
689 local $EXPANDED_ALIASES{$alias} = 1;
690 return $aliases{$alias} ? expand_aliases(@{$aliases{$alias}}) : $alias;
994d6c66
EW
691}
692
693@to = expand_aliases(@to);
5b56aaa2 694@to = (map { sanitize_address($_) } @to);
994d6c66 695@initial_cc = expand_aliases(@initial_cc);
58063245 696@bcclist = expand_aliases(@bcclist);
994d6c66 697
5483c71d 698if ($thread && !defined $initial_reply_to && $prompting) {
6e182518
JS
699 $initial_reply_to = ask(
700 "Message-ID to be used as In-Reply-To for the first email? ");
83b24437 701}
1ca3d6ed 702if (defined $initial_reply_to) {
0fb7fc75
JS
703 $initial_reply_to =~ s/^\s*<?//;
704 $initial_reply_to =~ s/>?\s*$//;
705 $initial_reply_to = "<$initial_reply_to>" if $initial_reply_to ne '';
ace9c2a9 706}
ace72086 707
34cc60ce 708if (!defined $smtp_server) {
aca7ad76
EW
709 foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
710 if (-x $_) {
711 $smtp_server = $_;
712 last;
713 }
714 }
715 $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
3342d850
RA
716}
717
c1f2aa45
JS
718if ($compose && $compose > 0) {
719 @files = ($compose_filename . ".final", @files);
1f038a0c
RA
720}
721
83b24437 722# Variables we set as part of the loop over files
c1f2aa45 723our ($message_id, %mail, $subject, $reply_to, $references, $message,
dc1460aa 724 $needs_confirm, $message_num, $ask_default);
83b24437 725
567ffeb7
EW
726sub extract_valid_address {
727 my $address = shift;
ad9c18f5 728 my $local_part_regexp = '[^<>"\s@]+';
09302e17 729 my $domain_regexp = '[^.<>"\s@]+(?:\.[^.<>"\s@]+)+';
db3106b2
EW
730
731 # check for a local address:
ad9c18f5 732 return $address if ($address =~ /^($local_part_regexp)$/);
db3106b2 733
155197e6 734 $address =~ s/^\s*<(.*)>\s*$/$1/;
567ffeb7 735 if ($have_email_valid) {
ad9c18f5 736 return scalar Email::Valid->address($address);
567ffeb7
EW
737 } else {
738 # less robust/correct than the monster regexp in Email::Valid,
739 # but still does a 99% job, and one less dependency
ad9c18f5 740 $address =~ /($local_part_regexp\@$domain_regexp)/;
e96fd305 741 return $1;
567ffeb7
EW
742 }
743}
83b24437
RA
744
745# Usually don't need to change anything below here.
746
747# we make a "fake" message id by taking the current number
748# of seconds since the beginning of Unix time and tacking on
749# a random number to the end, in case we are called quicker than
750# 1 second since the last time we were called.
8037d1a3
RA
751
752# We'll setup a template for the message id, using the "from" address:
8037d1a3 753
be510cfe 754my ($message_id_stamp, $message_id_serial);
68ce9330 755sub make_message_id {
be510cfe
JH
756 my $uniq;
757 if (!defined $message_id_stamp) {
758 $message_id_stamp = sprintf("%s-%s", time, $$);
759 $message_id_serial = 0;
760 }
761 $message_id_serial++;
762 $uniq = "$message_id_stamp-$message_id_serial";
763
aeb59328 764 my $du_part;
94638f89
UKK
765 for ($sender, $repocommitter, $repoauthor) {
766 $du_part = extract_valid_address(sanitize_address($_));
767 last if (defined $du_part and $du_part ne '');
aeb59328 768 }
94638f89 769 if (not defined $du_part or $du_part eq '') {
aeb59328
JH
770 use Sys::Hostname qw();
771 $du_part = 'user@' . Sys::Hostname::hostname();
772 }
be510cfe
JH
773 my $message_id_template = "<%s-git-send-email-%s>";
774 $message_id = sprintf($message_id_template, $uniq, $du_part);
8037d1a3 775 #print "new message id = $message_id\n"; # Was useful for debugging
83b24437
RA
776}
777
778
779
a5370b16 780$time = time - scalar $#files;
83b24437 781
374c5905
JR
782sub unquote_rfc2047 {
783 local ($_) = @_;
8291db6f
JK
784 my $encoding;
785 if (s/=\?([^?]+)\?q\?(.*)\?=/$2/g) {
786 $encoding = $1;
374c5905
JR
787 s/_/ /g;
788 s/=([0-9A-F]{2})/chr(hex($1))/eg;
789 }
8291db6f 790 return wantarray ? ($_, $encoding) : $_;
374c5905
JR
791}
792
d54eaaa2
JK
793sub quote_rfc2047 {
794 local $_ = shift;
d1fff6fc 795 my $encoding = shift || 'UTF-8';
d54eaaa2
JK
796 s/([^-a-zA-Z0-9!*+\/])/sprintf("=%02X", ord($1))/eg;
797 s/(.*)/=\?$encoding\?q\?$1\?=/;
798 return $_;
799}
800
a3a8262b
BC
801sub is_rfc2047_quoted {
802 my $s = shift;
803 my $token = '[^][()<>@,;:"\/?.= \000-\037\177-\377]+';
804 my $encoded_text = '[!->@-~]+';
805 length($s) <= 75 &&
806 $s =~ m/^(?:"[[:ascii:]]*"|=\?$token\?$token\?$encoded_text\?=)$/o;
807}
808
5b56aaa2 809# use the simplest quoting being able to handle the recipient
68ce9330 810sub sanitize_address {
732263d4 811 my ($recipient) = @_;
5b56aaa2
UKK
812 my ($recipient_name, $recipient_addr) = ($recipient =~ /^(.*?)\s*(<.*)/);
813
814 if (not $recipient_name) {
815 return "$recipient";
816 }
817
818 # if recipient_name is already quoted, do nothing
a3a8262b 819 if (is_rfc2047_quoted($recipient_name)) {
5b56aaa2
UKK
820 return $recipient;
821 }
822
823 # rfc2047 is needed if a non-ascii char is included
824 if ($recipient_name =~ /[^[:ascii:]]/) {
a61c0ffa 825 $recipient_name =~ s/^"(.*)"$/$1/;
d54eaaa2 826 $recipient_name = quote_rfc2047($recipient_name);
732263d4 827 }
5b56aaa2
UKK
828
829 # double quotes are needed if specials or CTLs are included
830 elsif ($recipient_name =~ /[][()<>@,;:\\".\000-\037\177]/) {
18023c20 831 $recipient_name =~ s/(["\\\r])/\\$1/g;
5b56aaa2
UKK
832 $recipient_name = "\"$recipient_name\"";
833 }
834
835 return "$recipient_name $recipient_addr";
836
732263d4
RJ
837}
838
134550fe
JA
839# Returns the local Fully Qualified Domain Name (FQDN) if available.
840#
841# Tightly configured MTAa require that a caller sends a real DNS
842# domain name that corresponds the IP address in the HELO/EHLO
843# handshake. This is used to verify the connection and prevent
844# spammers from trying to hide their identity. If the DNS and IP don't
845# match, the receiveing MTA may deny the connection.
846#
847# Here is a deny example of Net::SMTP with the default "localhost.localdomain"
848#
849# Net::SMTP=GLOB(0x267ec28)>>> EHLO localhost.localdomain
850# Net::SMTP=GLOB(0x267ec28)<<< 550 EHLO argument does not match calling host
851#
852# This maildomain*() code is based on ideas in Perl library Test::Reporter
853# /usr/share/perl5/Test/Reporter/Mail/Util.pm ==> sub _maildomain ()
854
59a86303
BG
855sub valid_fqdn {
856 my $domain = shift;
857 return !($^O eq 'darwin' && $domain =~ /\.local$/) && $domain =~ /\./;
858}
859
68ce9330 860sub maildomain_net {
134550fe
JA
861 my $maildomain;
862
863 if (eval { require Net::Domain; 1 }) {
864 my $domain = Net::Domain::domainname();
59a86303 865 $maildomain = $domain if valid_fqdn($domain);
134550fe
JA
866 }
867
868 return $maildomain;
869}
870
68ce9330 871sub maildomain_mta {
134550fe
JA
872 my $maildomain;
873
874 if (eval { require Net::SMTP; 1 }) {
875 for my $host (qw(mailhost localhost)) {
876 my $smtp = Net::SMTP->new($host);
877 if (defined $smtp) {
878 my $domain = $smtp->domain;
879 $smtp->quit;
880
59a86303 881 $maildomain = $domain if valid_fqdn($domain);
134550fe
JA
882
883 last if $maildomain;
884 }
885 }
886 }
887
888 return $maildomain;
889}
890
68ce9330 891sub maildomain {
134550fe
JA
892 return maildomain_net() || maildomain_mta() || $mail_domain_default;
893}
894
15da1084 895# Returns 1 if the message was sent, and 0 otherwise.
a1b5b371 896# In actuality, the whole program dies when there
15da1084
MW
897# is an error sending a message.
898
68ce9330 899sub send_message {
4bc87a28 900 my @recipients = unique_email_list(@to);
7ac17529
ABH
901 @cc = (grep { my $cc = extract_valid_address($_);
902 not grep { $cc eq $_ } @recipients
903 }
904 map { sanitize_address($_) }
905 @cc);
4bc87a28 906 my $to = join (",\n\t", @recipients);
58063245 907 @recipients = unique_email_list(@recipients,@cc,@bcclist);
c38f0247 908 @recipients = (map { extract_valid_address($_) } @recipients);
6bdca890 909 my $date = format_2822_time($time++);
e923effb
ML
910 my $gitversion = '@@GIT_VERSION@@';
911 if ($gitversion =~ m/..GIT_VERSION../) {
3cb8caf7 912 $gitversion = Git::version();
e923effb 913 }
4bc87a28 914
02461e0e 915 my $cc = join(",\n\t", unique_email_list(@cc));
f06a6a49
JH
916 my $ccline = "";
917 if ($cc ne '') {
918 $ccline = "\nCc: $cc";
919 }
94638f89 920 my $sanitized_sender = sanitize_address($sender);
4f3d3703 921 make_message_id() unless defined($message_id);
aeb59328 922
94638f89 923 my $header = "From: $sanitized_sender
f06a6a49 924To: $to${ccline}
4bc87a28 925Subject: $subject
4bc87a28
EW
926Date: $date
927Message-Id: $message_id
e923effb 928X-Mailer: git-send-email $gitversion
4bc87a28 929";
3e0c4ffd 930 if ($reply_to) {
7ccf7927
RA
931
932 $header .= "In-Reply-To: $reply_to\n";
933 $header .= "References: $references\n";
934 }
ce91c2f6
JH
935 if (@xh) {
936 $header .= join("\n", @xh) . "\n";
937 }
4bc87a28 938
c38f0247 939 my @sendmail_parameters = ('-i', @recipients);
94638f89 940 my $raw_from = $sanitized_sender;
c89e3241
FC
941 if (defined $envelope_sender && $envelope_sender ne "auto") {
942 $raw_from = $envelope_sender;
943 }
f073a592
RJ
944 $raw_from = extract_valid_address($raw_from);
945 unshift (@sendmail_parameters,
946 '-f', $raw_from) if(defined $envelope_sender);
8e3d436b 947
c1f2aa45
JS
948 if ($needs_confirm && !$dry_run) {
949 print "\n$header\n";
950 if ($needs_confirm eq "inform") {
951 $confirm_unconfigured = 0; # squelch this message for the rest of this run
6e182518 952 $ask_default = "y"; # assume yes on EOF since user hasn't explicitly asked for confirmation
c1f2aa45
JS
953 print " The Cc list above has been expanded by additional\n";
954 print " addresses found in the patch commit message. By default\n";
955 print " send-email prompts before sending whenever this occurs.\n";
956 print " This behavior is controlled by the sendemail.confirm\n";
957 print " configuration setting.\n";
958 print "\n";
959 print " For additional information, run 'git send-email --help'.\n";
960 print " To retain the current behavior, but squelch this message,\n";
961 print " run 'git config --global sendemail.confirm auto'.\n\n";
962 }
6e182518
JS
963 $_ = ask("Send this email? ([y]es|[n]o|[q]uit|[a]ll): ",
964 valid_re => qr/^(?:yes|y|no|n|quit|q|all|a)/i,
965 default => $ask_default);
966 die "Send this email reply required" unless defined $_;
c1f2aa45 967 if (/^n/i) {
15da1084 968 return 0;
c1f2aa45
JS
969 } elsif (/^q/i) {
970 cleanup_compose_files();
971 exit(0);
972 } elsif (/^a/i) {
973 $confirm = 'never';
974 }
975 }
976
6130259c
MW
977 if ($dry_run) {
978 # We don't want to send the email.
979 } elsif ($smtp_server =~ m#^/#) {
aca7ad76
EW
980 my $pid = open my $sm, '|-';
981 defined $pid or die $!;
982 if (!$pid) {
8e3d436b 983 exec($smtp_server, @sendmail_parameters) or die $!;
aca7ad76
EW
984 }
985 print $sm "$header\n$message";
986 close $sm or die $?;
987 } else {
44b2476a
JH
988
989 if (!defined $smtp_server) {
990 die "The required SMTP server is not properly defined."
991 }
992
f6bebd12 993 if ($smtp_encryption eq 'ssl') {
44b2476a 994 $smtp_server_port ||= 465; # ssmtp
34cc60ce 995 require Net::SMTP::SSL;
134550fe
JA
996 $mail_domain ||= maildomain();
997 $smtp ||= Net::SMTP::SSL->new($smtp_server,
998 Hello => $mail_domain,
999 Port => $smtp_server_port);
34cc60ce
DS
1000 }
1001 else {
1002 require Net::SMTP;
134550fe 1003 $mail_domain ||= maildomain();
44b2476a
JH
1004 $smtp ||= Net::SMTP->new((defined $smtp_server_port)
1005 ? "$smtp_server:$smtp_server_port"
f60812ef 1006 : $smtp_server,
134550fe 1007 Hello => $mail_domain,
f60812ef 1008 Debug => $debug_net_smtp);
fb3650ed 1009 if ($smtp_encryption eq 'tls' && $smtp) {
f6bebd12
TR
1010 require Net::SMTP::SSL;
1011 $smtp->command('STARTTLS');
1012 $smtp->response();
1013 if ($smtp->code == 220) {
1014 $smtp = Net::SMTP::SSL->start_SSL($smtp)
1015 or die "STARTTLS failed! ".$smtp->message;
6cbf8b00 1016 $smtp_encryption = '';
9d1ccf5e
RS
1017 # Send EHLO again to receive fresh
1018 # supported commands
1019 $smtp->hello();
f6bebd12
TR
1020 } else {
1021 die "Server does not support STARTTLS! ".$smtp->message;
1022 }
1023 }
44b2476a
JH
1024 }
1025
1026 if (!$smtp) {
f60812ef 1027 die "Unable to initialize SMTP properly. Check config and use --smtp-debug. ",
e5afb3a6
JA
1028 "VALUES: server=$smtp_server ",
1029 "encryption=$smtp_encryption ",
134550fe 1030 "maildomain=$mail_domain",
e5afb3a6 1031 defined $smtp_server_port ? "port=$smtp_server_port" : "";
44b2476a
JH
1032 }
1033
2363d746
MW
1034 if (defined $smtp_authuser) {
1035
1036 if (!defined $smtp_authpass) {
1037
1038 system "stty -echo";
1039
1040 do {
1041 print "Password: ";
1042 $_ = <STDIN>;
1043 print "\n";
1044 } while (!defined $_);
1045
1046 chomp($smtp_authpass = $_);
1047
1048 system "stty echo";
1049 }
1050
5f5b6118 1051 $auth ||= $smtp->auth( $smtp_authuser, $smtp_authpass ) or die $smtp->message;
34cc60ce 1052 }
2363d746 1053
2b69bfc2 1054 $smtp->mail( $raw_from ) or die $smtp->message;
aca7ad76
EW
1055 $smtp->to( @recipients ) or die $smtp->message;
1056 $smtp->data or die $smtp->message;
1057 $smtp->datasend("$header\n$message") or die $smtp->message;
1058 $smtp->dataend() or die $smtp->message;
15da1084 1059 $smtp->code =~ /250|200/ or die "Failed to send $subject\n".$smtp->message;
aca7ad76 1060 }
2718435b 1061 if ($quiet) {
71c7da94 1062 printf (($dry_run ? "Dry-" : "")."Sent %s\n", $subject);
2718435b 1063 } else {
b7f30e0a 1064 print (($dry_run ? "Dry-" : "")."OK. Log says:\n");
2b69bfc2 1065 if ($smtp_server !~ m#^/#) {
aca7ad76 1066 print "Server: $smtp_server\n";
2b69bfc2 1067 print "MAIL FROM:<$raw_from>\n";
02461e0e
JP
1068 foreach my $entry (@recipients) {
1069 print "RCPT TO:<$entry>\n";
1070 }
aca7ad76 1071 } else {
8e3d436b 1072 print "Sendmail: $smtp_server ".join(' ',@sendmail_parameters)."\n";
aca7ad76 1073 }
b7f30e0a 1074 print $header, "\n";
aca7ad76
EW
1075 if ($smtp) {
1076 print "Result: ", $smtp->code, ' ',
1077 ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
1078 } else {
1079 print "Result: OK\n";
1080 }
30d08b34 1081 }
15da1084
MW
1082
1083 return 1;
83b24437
RA
1084}
1085
83b24437 1086$reply_to = $initial_reply_to;
2186d566 1087$references = $initial_reply_to || '';
83b24437 1088$subject = $initial_subject;
c1f2aa45 1089$message_num = 0;
83b24437
RA
1090
1091foreach my $t (@files) {
83b24437
RA
1092 open(F,"<",$t) or die "can't open file $t";
1093
94638f89 1094 my $author = undef;
8291db6f
JK
1095 my $author_encoding;
1096 my $has_content_type;
1097 my $body_encoding;
c1f2aa45 1098 @cc = ();
ce91c2f6 1099 @xh = ();
e6b0964a 1100 my $input_format = undef;
5012699d 1101 my @header = ();
83b24437 1102 $message = "";
c1f2aa45 1103 $message_num++;
5012699d 1104 # First unfold multiline header fields
83b24437 1105 while(<F>) {
5012699d
JS
1106 last if /^\s*$/;
1107 if (/^\s+\S/ and @header) {
1108 chomp($header[$#header]);
1109 s/^\s+/ /;
1110 $header[$#header] .= $_;
1111 } else {
1112 push(@header, $_);
1113 }
1114 }
1115 # Now parse the header
1116 foreach(@header) {
1117 if (/^From /) {
1118 $input_format = 'mbox';
1119 next;
1120 }
1121 chomp;
1122 if (!defined $input_format && /^[-A-Za-z]+:\s/) {
1123 $input_format = 'mbox';
1124 }
1125
1126 if (defined $input_format && $input_format eq 'mbox') {
1127 if (/^Subject:\s+(.*)$/) {
1128 $subject = $1;
e6b0964a 1129 }
5012699d
JS
1130 elsif (/^From:\s+(.*)$/) {
1131 ($author, $author_encoding) = unquote_rfc2047($1);
1132 next if $suppress_cc{'author'};
1133 next if $suppress_cc{'self'} and $author eq $sender;
1134 printf("(mbox) Adding cc: %s from line '%s'\n",
1135 $1, $_) unless $quiet;
1136 push @cc, $1;
e6b0964a 1137 }
5012699d
JS
1138 elsif (/^Cc:\s+(.*)$/) {
1139 foreach my $addr (parse_address_line($1)) {
1140 if (unquote_rfc2047($addr) eq $sender) {
65648283 1141 next if ($suppress_cc{'self'});
65648283
DB
1142 } else {
1143 next if ($suppress_cc{'cc'});
8a8e6235 1144 }
83b24437 1145 printf("(mbox) Adding cc: %s from line '%s'\n",
5012699d
JS
1146 $addr, $_) unless $quiet;
1147 push @cc, $addr;
83b24437 1148 }
5012699d
JS
1149 }
1150 elsif (/^Content-type:/i) {
1151 $has_content_type = 1;
1152 if (/charset="?([^ "]+)/) {
1153 $body_encoding = $1;
83b24437 1154 }
5012699d 1155 push @xh, $_;
83b24437 1156 }
5012699d
JS
1157 elsif (/^Message-Id: (.*)/i) {
1158 $message_id = $1;
83b24437 1159 }
5012699d
JS
1160 elsif (!/^Date:\s/ && /^[-A-Za-z]+:\s+\S/) {
1161 push @xh, $_;
1162 }
1163
83b24437 1164 } else {
5012699d
JS
1165 # In the traditional
1166 # "send lots of email" format,
1167 # line 1 = cc
1168 # line 2 = subject
1169 # So let's support that, too.
1170 $input_format = 'lots';
1171 if (@cc == 0 && !$suppress_cc{'cc'}) {
1172 printf("(non-mbox) Adding cc: %s from line '%s'\n",
1173 $_, $_) unless $quiet;
1174 push @cc, $_;
1175 } elsif (!defined $subject) {
1176 $subject = $_;
83b24437
RA
1177 }
1178 }
1179 }
5012699d
JS
1180 # Now parse the message body
1181 while(<F>) {
1182 $message .= $_;
1183 if (/^(Signed-off-by|Cc): (.*)$/i) {
5012699d 1184 chomp;
3531e270 1185 my ($what, $c) = ($1, $2);
5012699d 1186 chomp $c;
3531e270
JS
1187 if ($c eq $sender) {
1188 next if ($suppress_cc{'self'});
1189 } else {
1190 next if $suppress_cc{'sob'} and $what =~ /Signed-off-by/i;
1191 next if $suppress_cc{'bodycc'} and $what =~ /Cc/i;
1192 }
5012699d 1193 push @cc, $c;
3531e270 1194 printf("(body) Adding cc: %s from line '%s'\n",
5012699d
JS
1195 $c, $_) unless $quiet;
1196 }
1197 }
83b24437 1198 close F;
324a8bd0 1199
65648283 1200 if (defined $cc_cmd && !$suppress_cc{'cccmd'}) {
cb8a9bd5 1201 open(F, "$cc_cmd \Q$t\E |")
324a8bd0
JP
1202 or die "(cc-cmd) Could not execute '$cc_cmd'";
1203 while(<F>) {
1204 my $c = $_;
1205 $c =~ s/^\s*//g;
1206 $c =~ s/\n$//g;
620bb245 1207 next if ($c eq $sender and $suppress_from);
324a8bd0
JP
1208 push @cc, $c;
1209 printf("(cc-cmd) Adding cc: %s from: '%s'\n",
1210 $c, $cc_cmd) unless $quiet;
1211 }
1212 close F
1213 or die "(cc-cmd) failed to close pipe to '$cc_cmd'";
1214 }
1215
5012699d 1216 if (defined $author and $author ne $sender) {
94638f89 1217 $message = "From: $author\n\n$message";
8291db6f
JK
1218 if (defined $author_encoding) {
1219 if ($has_content_type) {
1220 if ($body_encoding eq $author_encoding) {
1221 # ok, we already have the right encoding
1222 }
1223 else {
1224 # uh oh, we should re-encode
1225 }
1226 }
1227 else {
1228 push @xh,
1229 'MIME-Version: 1.0',
8641ee3d
JK
1230 "Content-Type: text/plain; charset=$author_encoding",
1231 'Content-Transfer-Encoding: 8bit';
8291db6f
JK
1232 }
1233 }
8a8e6235 1234 }
83b24437 1235
c1f2aa45
JS
1236 $needs_confirm = (
1237 $confirm eq "always" or
1238 ($confirm =~ /^(?:auto|cc)$/ && @cc) or
1239 ($confirm =~ /^(?:auto|compose)$/ && $compose && $message_num == 1));
1240 $needs_confirm = "inform" if ($needs_confirm && $confirm_unconfigured && @cc);
1241
1242 @cc = (@initial_cc, @cc);
1243
15da1084 1244 my $message_was_sent = send_message();
83b24437
RA
1245
1246 # set up for the next message
95a877a3 1247 if ($thread && $message_was_sent &&
528fb087 1248 (chain_reply_to() || !defined $reply_to || length($reply_to) == 0)) {
78488b2c 1249 $reply_to = $message_id;
7ccf7927 1250 if (length $references > 0) {
a925b89c 1251 $references .= "\n $message_id";
7ccf7927
RA
1252 } else {
1253 $references = "$message_id";
1254 }
78488b2c 1255 }
4f3d3703 1256 $message_id = undef;
83b24437 1257}
e205735d 1258
c1f2aa45 1259cleanup_compose_files();
1f038a0c
RA
1260
1261sub cleanup_compose_files() {
c1f2aa45 1262 unlink($compose_filename, $compose_filename . ".final") if $compose;
1f038a0c
RA
1263}
1264
4bc87a28 1265$smtp->quit if $smtp;
e205735d
RA
1266
1267sub unique_email_list(@) {
1268 my %seen;
1269 my @emails;
1270
1271 foreach my $entry (@_) {
db3106b2
EW
1272 if (my $clean = extract_valid_address($entry)) {
1273 $seen{$clean} ||= 0;
1274 next if $seen{$clean}++;
1275 push @emails, $entry;
1276 } else {
1277 print STDERR "W: unable to extract a valid address",
1278 " from: $entry\n";
1279 }
e205735d
RA
1280 }
1281 return @emails;
1282}
747bbff9
JK
1283
1284sub validate_patch {
1285 my $fn = shift;
1286 open(my $fh, '<', $fn)
1287 or die "unable to open $fn: $!\n";
1288 while (my $line = <$fh>) {
1289 if (length($line) > 998) {
1290 return "$.: patch contains a line longer than 998 characters";
1291 }
1292 }
1293 return undef;
1294}
0706bd19
JK
1295
1296sub file_has_nonascii {
1297 my $fn = shift;
1298 open(my $fh, '<', $fn)
1299 or die "unable to open $fn: $!\n";
1300 while (my $line = <$fh>) {
1301 return 1 if $line =~ /[^[:ascii:]]/;
1302 }
1303 return 0;
1304}