git-send-email: Generalize auto-cc recipient mechanism.
[git/gitweb.git] / git-send-email.perl
blob8de5789f669aeefa1d5eba938e8b41442ede9ffa
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 Git;
27 $SIG{INT} = sub { print color("reset"), "\n"; exit };
29 package FakeTerm;
30 sub new {
31 my ($class, $reason) = @_;
32 return bless \$reason, shift;
34 sub readline {
35 my $self = shift;
36 die "Cannot use readline on FakeTerm: $$self";
38 package main;
41 sub usage {
42 print <<EOT;
43 git-send-email [options] <file | directory>...
44 Options:
45 --from Specify the "From:" line of the email to be sent.
47 --to Specify the primary "To:" line of the email.
49 --cc Specify an initial "Cc:" list for the entire series
50 of emails.
52 --cc-cmd Specify a command to execute per file which adds
53 per file specific cc address entries
55 --bcc Specify a list of email addresses that should be Bcc:
56 on all the emails.
58 --compose Use \$GIT_EDITOR, core.editor, \$EDITOR, or \$VISUAL to edit
59 an introductory message for the patch series.
61 --subject Specify the initial "Subject:" line.
62 Only necessary if --compose is also set. If --compose
63 is not set, this will be prompted for.
65 --in-reply-to Specify the first "In-Reply-To:" header line.
66 Only used if --compose is also set. If --compose is not
67 set, this will be prompted for.
69 --chain-reply-to If set, the replies will all be to the previous
70 email sent, rather than to the first email sent.
71 Defaults to on.
73 --signed-off-cc Automatically add email addresses that appear in
74 Signed-off-by: or Cc: lines to the cc: list. Defaults to on.
76 --identity The configuration identity, a subsection to prioritise over
77 the default section.
79 --smtp-server If set, specifies the outgoing SMTP server to use.
80 Defaults to localhost. Port number can be specified here with
81 hostname:port format or by using --smtp-server-port option.
83 --smtp-server-port Specify a port on the outgoing SMTP server to connect to.
85 --smtp-user The username for SMTP-AUTH.
87 --smtp-pass The password for SMTP-AUTH.
89 --smtp-ssl If set, connects to the SMTP server using SSL.
91 --suppress-cc Suppress the specified category of auto-CC. The category
92 can be one of 'author' for the patch author, 'self' to
93 avoid copying yourself, 'sob' for Signed-off-by lines,
94 'cccmd' for the output of the cccmd, or 'all' to suppress
95 all of these.
97 --suppress-from Suppress sending emails to yourself. Defaults to off.
99 --thread Specify that the "In-Reply-To:" header should be set on all
100 emails. Defaults to on.
102 --quiet Make git-send-email less verbose. One line per email
103 should be all that is output.
105 --dry-run Do everything except actually send the emails.
107 --envelope-sender Specify the envelope sender used to send the emails.
109 --no-validate Don't perform any sanity checks on patches.
112 exit(1);
115 # most mail servers generate the Date: header, but not all...
116 sub format_2822_time {
117 my ($time) = @_;
118 my @localtm = localtime($time);
119 my @gmttm = gmtime($time);
120 my $localmin = $localtm[1] + $localtm[2] * 60;
121 my $gmtmin = $gmttm[1] + $gmttm[2] * 60;
122 if ($localtm[0] != $gmttm[0]) {
123 die "local zone differs from GMT by a non-minute interval\n";
125 if ((($gmttm[6] + 1) % 7) == $localtm[6]) {
126 $localmin += 1440;
127 } elsif ((($gmttm[6] - 1) % 7) == $localtm[6]) {
128 $localmin -= 1440;
129 } elsif ($gmttm[6] != $localtm[6]) {
130 die "local time offset greater than or equal to 24 hours\n";
132 my $offset = $localmin - $gmtmin;
133 my $offhour = $offset / 60;
134 my $offmin = abs($offset % 60);
135 if (abs($offhour) >= 24) {
136 die ("local time offset greater than or equal to 24 hours\n");
139 return sprintf("%s, %2d %s %d %02d:%02d:%02d %s%02d%02d",
140 qw(Sun Mon Tue Wed Thu Fri Sat)[$localtm[6]],
141 $localtm[3],
142 qw(Jan Feb Mar Apr May Jun
143 Jul Aug Sep Oct Nov Dec)[$localtm[4]],
144 $localtm[5]+1900,
145 $localtm[2],
146 $localtm[1],
147 $localtm[0],
148 ($offset >= 0) ? '+' : '-',
149 abs($offhour),
150 $offmin,
154 my $have_email_valid = eval { require Email::Valid; 1 };
155 my $smtp;
156 my $auth;
158 sub unique_email_list(@);
159 sub cleanup_compose_files();
161 # Constants (essentially)
162 my $compose_filename = ".msg.$$";
164 # Variables we fill in automatically, or via prompting:
165 my (@to,@cc,@initial_cc,@bcclist,@xh,
166 $initial_reply_to,$initial_subject,@files,$author,$sender,$compose,$time);
168 my $envelope_sender;
170 # Example reply to:
171 #$initial_reply_to = ''; #<20050203173208.GA23964@foobar.com>';
173 my $repo = Git->repository();
174 my $term = eval {
175 new Term::ReadLine 'git-send-email';
177 if ($@) {
178 $term = new FakeTerm "$@: going non-interactive";
181 # Behavior modification variables
182 my ($quiet, $dry_run) = (0, 0);
184 # Variables with corresponding config settings
185 my ($thread, $chain_reply_to, $suppress_from, $signed_off_cc, $cc_cmd);
186 my ($smtp_server, $smtp_server_port, $smtp_authuser, $smtp_authpass, $smtp_ssl);
187 my ($identity, $aliasfiletype, @alias_files, @smtp_host_parts);
188 my ($no_validate);
189 my (@suppress_cc);
191 my %config_bool_settings = (
192 "thread" => [\$thread, 1],
193 "chainreplyto" => [\$chain_reply_to, 1],
194 "suppressfrom" => [\$suppress_from, undef],
195 "signedoffcc" => [\$signed_off_cc, undef],
196 "smtpssl" => [\$smtp_ssl, 0],
199 my %config_settings = (
200 "smtpserver" => \$smtp_server,
201 "smtpserverport" => \$smtp_server_port,
202 "smtpuser" => \$smtp_authuser,
203 "smtppass" => \$smtp_authpass,
204 "to" => \@to,
205 "cccmd" => \$cc_cmd,
206 "aliasfiletype" => \$aliasfiletype,
207 "bcc" => \@bcclist,
208 "aliasesfile" => \@alias_files,
209 "suppresscc" => \@suppress_cc,
212 # Begin by accumulating all the variables (defined above), that we will end up
213 # needing, first, from the command line:
215 my $rc = GetOptions("sender|from=s" => \$sender,
216 "in-reply-to=s" => \$initial_reply_to,
217 "subject=s" => \$initial_subject,
218 "to=s" => \@to,
219 "cc=s" => \@initial_cc,
220 "bcc=s" => \@bcclist,
221 "chain-reply-to!" => \$chain_reply_to,
222 "smtp-server=s" => \$smtp_server,
223 "smtp-server-port=s" => \$smtp_server_port,
224 "smtp-user=s" => \$smtp_authuser,
225 "smtp-pass=s" => \$smtp_authpass,
226 "smtp-ssl!" => \$smtp_ssl,
227 "identity=s" => \$identity,
228 "compose" => \$compose,
229 "quiet" => \$quiet,
230 "cc-cmd=s" => \$cc_cmd,
231 "suppress-from!" => \$suppress_from,
232 "suppress-cc=s" => \@suppress_cc,
233 "signed-off-cc|signed-off-by-cc!" => \$signed_off_cc,
234 "dry-run" => \$dry_run,
235 "envelope-sender=s" => \$envelope_sender,
236 "thread!" => \$thread,
237 "no-validate" => \$no_validate,
240 unless ($rc) {
241 usage();
244 # Now, let's fill any that aren't set in with defaults:
246 sub read_config {
247 my ($prefix) = @_;
249 foreach my $setting (keys %config_bool_settings) {
250 my $target = $config_bool_settings{$setting}->[0];
251 $$target = $repo->config_bool("$prefix.$setting") unless (defined $$target);
254 foreach my $setting (keys %config_settings) {
255 my $target = $config_settings{$setting};
256 if (ref($target) eq "ARRAY") {
257 unless (@$target) {
258 my @values = $repo->config("$prefix.$setting");
259 @$target = @values if (@values && defined $values[0]);
262 else {
263 $$target = $repo->config("$prefix.$setting") unless (defined $$target);
268 # read configuration from [sendemail "$identity"], fall back on [sendemail]
269 $identity = $repo->config("sendemail.identity") unless (defined $identity);
270 read_config("sendemail.$identity") if (defined $identity);
271 read_config("sendemail");
273 # fall back on builtin bool defaults
274 foreach my $setting (values %config_bool_settings) {
275 ${$setting->[0]} = $setting->[1] unless (defined (${$setting->[0]}));
278 # Set CC suppressions
279 my(%suppress_cc);
280 if (@suppress_cc) {
281 foreach my $entry (@suppress_cc) {
282 die "Unknown --suppress-cc field: '$entry'\n"
283 unless $entry =~ /^(all|cccmd|cc|author|self|sob)$/;
284 $suppress_cc{$entry} = 1;
288 if ($suppress_cc{'all'}) {
289 foreach my $entry (qw (ccmd cc author self sob)) {
290 $suppress_cc{$entry} = 1;
292 delete $suppress_cc{'all'};
295 # If explicit old-style ones are specified, they trump --suppress-cc.
296 $suppress_cc{'self'} = $suppress_from if defined $suppress_from;
297 $suppress_cc{'sob'} = $signed_off_cc if defined $signed_off_cc;
299 # Debugging, print out the suppressions.
300 if (0) {
301 print "suppressions:\n";
302 foreach my $entry (keys %suppress_cc) {
303 printf " %-5s -> $suppress_cc{$entry}\n", $entry;
307 my ($repoauthor) = $repo->ident_person('author');
308 my ($repocommitter) = $repo->ident_person('committer');
310 # Verify the user input
312 foreach my $entry (@to) {
313 die "Comma in --to entry: $entry'\n" unless $entry !~ m/,/;
316 foreach my $entry (@initial_cc) {
317 die "Comma in --cc entry: $entry'\n" unless $entry !~ m/,/;
320 foreach my $entry (@bcclist) {
321 die "Comma in --bcclist entry: $entry'\n" unless $entry !~ m/,/;
324 my %aliases;
325 my %parse_alias = (
326 # multiline formats can be supported in the future
327 mutt => sub { my $fh = shift; while (<$fh>) {
328 if (/^\s*alias\s+(\S+)\s+(.*)$/) {
329 my ($alias, $addr) = ($1, $2);
330 $addr =~ s/#.*$//; # mutt allows # comments
331 # commas delimit multiple addresses
332 $aliases{$alias} = [ split(/\s*,\s*/, $addr) ];
333 }}},
334 mailrc => sub { my $fh = shift; while (<$fh>) {
335 if (/^alias\s+(\S+)\s+(.*)$/) {
336 # spaces delimit multiple addresses
337 $aliases{$1} = [ split(/\s+/, $2) ];
338 }}},
339 pine => sub { my $fh = shift; while (<$fh>) {
340 if (/^(\S+)\t.*\t(.*)$/) {
341 $aliases{$1} = [ split(/\s*,\s*/, $2) ];
342 }}},
343 gnus => sub { my $fh = shift; while (<$fh>) {
344 if (/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) {
345 $aliases{$1} = [ $2 ];
349 if (@alias_files and $aliasfiletype and defined $parse_alias{$aliasfiletype}) {
350 foreach my $file (@alias_files) {
351 open my $fh, '<', $file or die "opening $file: $!\n";
352 $parse_alias{$aliasfiletype}->($fh);
353 close $fh;
357 ($sender) = expand_aliases($sender) if defined $sender;
359 # Now that all the defaults are set, process the rest of the command line
360 # arguments and collect up the files that need to be processed.
361 for my $f (@ARGV) {
362 if (-d $f) {
363 opendir(DH,$f)
364 or die "Failed to opendir $f: $!";
366 push @files, grep { -f $_ } map { +$f . "/" . $_ }
367 sort readdir(DH);
369 } elsif (-f $f) {
370 push @files, $f;
372 } else {
373 print STDERR "Skipping $f - not found.\n";
377 if (!$no_validate) {
378 foreach my $f (@files) {
379 my $error = validate_patch($f);
380 $error and die "fatal: $f: $error\nwarning: no patches were sent\n";
384 if (@files) {
385 unless ($quiet) {
386 print $_,"\n" for (@files);
388 } else {
389 print STDERR "\nNo patch files specified!\n\n";
390 usage();
393 my $prompting = 0;
394 if (!defined $sender) {
395 $sender = $repoauthor || $repocommitter;
396 do {
397 $_ = $term->readline("Who should the emails appear to be from? [$sender] ");
398 } while (!defined $_);
400 $sender = $_ if ($_);
401 print "Emails will be sent from: ", $sender, "\n";
402 $prompting++;
405 if (!@to) {
406 do {
407 $_ = $term->readline("Who should the emails be sent to? ",
408 "");
409 } while (!defined $_);
410 my $to = $_;
411 push @to, split /,/, $to;
412 $prompting++;
415 sub expand_aliases {
416 my @cur = @_;
417 my @last;
418 do {
419 @last = @cur;
420 @cur = map { $aliases{$_} ? @{$aliases{$_}} : $_ } @last;
421 } while (join(',',@cur) ne join(',',@last));
422 return @cur;
425 @to = expand_aliases(@to);
426 @to = (map { sanitize_address($_) } @to);
427 @initial_cc = expand_aliases(@initial_cc);
428 @bcclist = expand_aliases(@bcclist);
430 if (!defined $initial_subject && $compose) {
431 do {
432 $_ = $term->readline("What subject should the initial email start with? ",
433 $initial_subject);
434 } while (!defined $_);
435 $initial_subject = $_;
436 $prompting++;
439 if ($thread && !defined $initial_reply_to && $prompting) {
440 do {
441 $_= $term->readline("Message-ID to be used as In-Reply-To for the first email? ",
442 $initial_reply_to);
443 } while (!defined $_);
445 $initial_reply_to = $_;
447 if (defined $initial_reply_to && $_ ne "") {
448 $initial_reply_to =~ s/^\s*<?/</;
449 $initial_reply_to =~ s/>?\s*$/>/;
452 if (!defined $smtp_server) {
453 foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
454 if (-x $_) {
455 $smtp_server = $_;
456 last;
459 $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
462 if ($compose) {
463 # Note that this does not need to be secure, but we will make a small
464 # effort to have it be unique
465 open(C,">",$compose_filename)
466 or die "Failed to open for writing $compose_filename: $!";
467 print C "From $sender # This line is ignored.\n";
468 printf C "Subject: %s\n\n", $initial_subject;
469 printf C <<EOT;
470 GIT: Please enter your email below.
471 GIT: Lines beginning in "GIT: " will be removed.
472 GIT: Consider including an overall diffstat or table of contents
473 GIT: for the patch you are writing.
476 close(C);
478 my $editor = $ENV{GIT_EDITOR} || $repo->config("core.editor") || $ENV{VISUAL} || $ENV{EDITOR} || "vi";
479 system('sh', '-c', '$0 $@', $editor, $compose_filename);
481 open(C2,">",$compose_filename . ".final")
482 or die "Failed to open $compose_filename.final : " . $!;
484 open(C,"<",$compose_filename)
485 or die "Failed to open $compose_filename : " . $!;
487 while(<C>) {
488 next if m/^GIT: /;
489 print C2 $_;
491 close(C);
492 close(C2);
494 do {
495 $_ = $term->readline("Send this email? (y|n) ");
496 } while (!defined $_);
498 if (uc substr($_,0,1) ne 'Y') {
499 cleanup_compose_files();
500 exit(0);
503 @files = ($compose_filename . ".final", @files);
506 # Variables we set as part of the loop over files
507 our ($message_id, %mail, $subject, $reply_to, $references, $message);
509 sub extract_valid_address {
510 my $address = shift;
511 my $local_part_regexp = '[^<>"\s@]+';
512 my $domain_regexp = '[^.<>"\s@]+(?:\.[^.<>"\s@]+)+';
514 # check for a local address:
515 return $address if ($address =~ /^($local_part_regexp)$/);
517 $address =~ s/^\s*<(.*)>\s*$/$1/;
518 if ($have_email_valid) {
519 return scalar Email::Valid->address($address);
520 } else {
521 # less robust/correct than the monster regexp in Email::Valid,
522 # but still does a 99% job, and one less dependency
523 $address =~ /($local_part_regexp\@$domain_regexp)/;
524 return $1;
528 # Usually don't need to change anything below here.
530 # we make a "fake" message id by taking the current number
531 # of seconds since the beginning of Unix time and tacking on
532 # a random number to the end, in case we are called quicker than
533 # 1 second since the last time we were called.
535 # We'll setup a template for the message id, using the "from" address:
537 my ($message_id_stamp, $message_id_serial);
538 sub make_message_id
540 my $uniq;
541 if (!defined $message_id_stamp) {
542 $message_id_stamp = sprintf("%s-%s", time, $$);
543 $message_id_serial = 0;
545 $message_id_serial++;
546 $uniq = "$message_id_stamp-$message_id_serial";
548 my $du_part;
549 for ($sender, $repocommitter, $repoauthor) {
550 $du_part = extract_valid_address(sanitize_address($_));
551 last if (defined $du_part and $du_part ne '');
553 if (not defined $du_part or $du_part eq '') {
554 use Sys::Hostname qw();
555 $du_part = 'user@' . Sys::Hostname::hostname();
557 my $message_id_template = "<%s-git-send-email-%s>";
558 $message_id = sprintf($message_id_template, $uniq, $du_part);
559 #print "new message id = $message_id\n"; # Was useful for debugging
564 $time = time - scalar $#files;
566 sub unquote_rfc2047 {
567 local ($_) = @_;
568 my $encoding;
569 if (s/=\?([^?]+)\?q\?(.*)\?=/$2/g) {
570 $encoding = $1;
571 s/_/ /g;
572 s/=([0-9A-F]{2})/chr(hex($1))/eg;
574 return wantarray ? ($_, $encoding) : $_;
577 # use the simplest quoting being able to handle the recipient
578 sub sanitize_address
580 my ($recipient) = @_;
581 my ($recipient_name, $recipient_addr) = ($recipient =~ /^(.*?)\s*(<.*)/);
583 if (not $recipient_name) {
584 return "$recipient";
587 # if recipient_name is already quoted, do nothing
588 if ($recipient_name =~ /^(".*"|=\?utf-8\?q\?.*\?=)$/) {
589 return $recipient;
592 # rfc2047 is needed if a non-ascii char is included
593 if ($recipient_name =~ /[^[:ascii:]]/) {
594 $recipient_name =~ s/([^-a-zA-Z0-9!*+\/])/sprintf("=%02X", ord($1))/eg;
595 $recipient_name =~ s/(.*)/=\?utf-8\?q\?$1\?=/;
598 # double quotes are needed if specials or CTLs are included
599 elsif ($recipient_name =~ /[][()<>@,;:\\".\000-\037\177]/) {
600 $recipient_name =~ s/(["\\\r])/\\$1/;
601 $recipient_name = "\"$recipient_name\"";
604 return "$recipient_name $recipient_addr";
608 sub send_message
610 my @recipients = unique_email_list(@to);
611 @cc = (grep { my $cc = extract_valid_address($_);
612 not grep { $cc eq $_ } @recipients
614 map { sanitize_address($_) }
615 @cc);
616 my $to = join (",\n\t", @recipients);
617 @recipients = unique_email_list(@recipients,@cc,@bcclist);
618 @recipients = (map { extract_valid_address($_) } @recipients);
619 my $date = format_2822_time($time++);
620 my $gitversion = '@@GIT_VERSION@@';
621 if ($gitversion =~ m/..GIT_VERSION../) {
622 $gitversion = Git::version();
625 my $cc = join(", ", unique_email_list(@cc));
626 my $ccline = "";
627 if ($cc ne '') {
628 $ccline = "\nCc: $cc";
630 my $sanitized_sender = sanitize_address($sender);
631 make_message_id() unless defined($message_id);
633 my $header = "From: $sanitized_sender
634 To: $to${ccline}
635 Subject: $subject
636 Date: $date
637 Message-Id: $message_id
638 X-Mailer: git-send-email $gitversion
640 if ($thread && $reply_to) {
642 $header .= "In-Reply-To: $reply_to\n";
643 $header .= "References: $references\n";
645 if (@xh) {
646 $header .= join("\n", @xh) . "\n";
649 my @sendmail_parameters = ('-i', @recipients);
650 my $raw_from = $sanitized_sender;
651 $raw_from = $envelope_sender if (defined $envelope_sender);
652 $raw_from = extract_valid_address($raw_from);
653 unshift (@sendmail_parameters,
654 '-f', $raw_from) if(defined $envelope_sender);
656 if ($dry_run) {
657 # We don't want to send the email.
658 } elsif ($smtp_server =~ m#^/#) {
659 my $pid = open my $sm, '|-';
660 defined $pid or die $!;
661 if (!$pid) {
662 exec($smtp_server, @sendmail_parameters) or die $!;
664 print $sm "$header\n$message";
665 close $sm or die $?;
666 } else {
668 if (!defined $smtp_server) {
669 die "The required SMTP server is not properly defined."
672 if ($smtp_ssl) {
673 $smtp_server_port ||= 465; # ssmtp
674 require Net::SMTP::SSL;
675 $smtp ||= Net::SMTP::SSL->new($smtp_server, Port => $smtp_server_port);
677 else {
678 require Net::SMTP;
679 $smtp ||= Net::SMTP->new((defined $smtp_server_port)
680 ? "$smtp_server:$smtp_server_port"
681 : $smtp_server);
684 if (!$smtp) {
685 die "Unable to initialize SMTP properly. Is there something wrong with your config?";
688 if ((defined $smtp_authuser) && (defined $smtp_authpass)) {
689 $auth ||= $smtp->auth( $smtp_authuser, $smtp_authpass ) or die $smtp->message;
691 $smtp->mail( $raw_from ) or die $smtp->message;
692 $smtp->to( @recipients ) or die $smtp->message;
693 $smtp->data or die $smtp->message;
694 $smtp->datasend("$header\n$message") or die $smtp->message;
695 $smtp->dataend() or die $smtp->message;
696 $smtp->ok or die "Failed to send $subject\n".$smtp->message;
698 if ($quiet) {
699 printf (($dry_run ? "Dry-" : "")."Sent %s\n", $subject);
700 } else {
701 print (($dry_run ? "Dry-" : "")."OK. Log says:\n");
702 if ($smtp_server !~ m#^/#) {
703 print "Server: $smtp_server\n";
704 print "MAIL FROM:<$raw_from>\n";
705 print "RCPT TO:".join(',',(map { "<$_>" } @recipients))."\n";
706 } else {
707 print "Sendmail: $smtp_server ".join(' ',@sendmail_parameters)."\n";
709 print $header, "\n";
710 if ($smtp) {
711 print "Result: ", $smtp->code, ' ',
712 ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
713 } else {
714 print "Result: OK\n";
719 $reply_to = $initial_reply_to;
720 $references = $initial_reply_to || '';
721 $subject = $initial_subject;
723 foreach my $t (@files) {
724 open(F,"<",$t) or die "can't open file $t";
726 my $author = undef;
727 my $author_encoding;
728 my $has_content_type;
729 my $body_encoding;
730 @cc = @initial_cc;
731 @xh = ();
732 my $input_format = undef;
733 my $header_done = 0;
734 $message = "";
735 while(<F>) {
736 if (!$header_done) {
737 if (/^From /) {
738 $input_format = 'mbox';
739 next;
741 chomp;
742 if (!defined $input_format && /^[-A-Za-z]+:\s/) {
743 $input_format = 'mbox';
746 if (defined $input_format && $input_format eq 'mbox') {
747 if (/^Subject:\s+(.*)$/) {
748 $subject = $1;
750 } elsif (/^(Cc|From):\s+(.*)$/) {
751 if (unquote_rfc2047($2) eq $sender) {
752 next if ($suppress_cc{'self'});
754 elsif ($1 eq 'From') {
755 ($author, $author_encoding)
756 = unquote_rfc2047($2);
757 next if ($suppress_cc{'author'});
758 } else {
759 next if ($suppress_cc{'cc'});
761 printf("(mbox) Adding cc: %s from line '%s'\n",
762 $2, $_) unless $quiet;
763 push @cc, $2;
765 elsif (/^Content-type:/i) {
766 $has_content_type = 1;
767 if (/charset="?[^ "]+/) {
768 $body_encoding = $1;
770 push @xh, $_;
772 elsif (/^Message-Id: (.*)/i) {
773 $message_id = $1;
775 elsif (!/^Date:\s/ && /^[-A-Za-z]+:\s+\S/) {
776 push @xh, $_;
779 } else {
780 # In the traditional
781 # "send lots of email" format,
782 # line 1 = cc
783 # line 2 = subject
784 # So let's support that, too.
785 $input_format = 'lots';
786 if (@cc == 0 && !$suppress_cc{'cc'}) {
787 printf("(non-mbox) Adding cc: %s from line '%s'\n",
788 $_, $_) unless $quiet;
790 push @cc, $_;
792 } elsif (!defined $subject) {
793 $subject = $_;
797 # A whitespace line will terminate the headers
798 if (m/^\s*$/) {
799 $header_done = 1;
801 } else {
802 $message .= $_;
803 if (/^(Signed-off-by|Cc): (.*)$/i) {
804 next if ($suppress_cc{'sob'});
805 my $c = $2;
806 chomp $c;
807 next if ($c eq $sender and $suppress_cc{'self'});
808 push @cc, $c;
809 printf("(sob) Adding cc: %s from line '%s'\n",
810 $c, $_) unless $quiet;
814 close F;
816 if (defined $cc_cmd && !$suppress_cc{'cccmd'}) {
817 open(F, "$cc_cmd $t |")
818 or die "(cc-cmd) Could not execute '$cc_cmd'";
819 while(<F>) {
820 my $c = $_;
821 $c =~ s/^\s*//g;
822 $c =~ s/\n$//g;
823 next if ($c eq $sender and $suppress_from);
824 push @cc, $c;
825 printf("(cc-cmd) Adding cc: %s from: '%s'\n",
826 $c, $cc_cmd) unless $quiet;
828 close F
829 or die "(cc-cmd) failed to close pipe to '$cc_cmd'";
832 if (defined $author) {
833 $message = "From: $author\n\n$message";
834 if (defined $author_encoding) {
835 if ($has_content_type) {
836 if ($body_encoding eq $author_encoding) {
837 # ok, we already have the right encoding
839 else {
840 # uh oh, we should re-encode
843 else {
844 push @xh,
845 'MIME-Version: 1.0',
846 "Content-Type: text/plain; charset=$author_encoding",
847 'Content-Transfer-Encoding: 8bit';
852 send_message();
854 # set up for the next message
855 if ($chain_reply_to || !defined $reply_to || length($reply_to) == 0) {
856 $reply_to = $message_id;
857 if (length $references > 0) {
858 $references .= "\n $message_id";
859 } else {
860 $references = "$message_id";
863 $message_id = undef;
866 if ($compose) {
867 cleanup_compose_files();
870 sub cleanup_compose_files() {
871 unlink($compose_filename, $compose_filename . ".final");
875 $smtp->quit if $smtp;
877 sub unique_email_list(@) {
878 my %seen;
879 my @emails;
881 foreach my $entry (@_) {
882 if (my $clean = extract_valid_address($entry)) {
883 $seen{$clean} ||= 0;
884 next if $seen{$clean}++;
885 push @emails, $entry;
886 } else {
887 print STDERR "W: unable to extract a valid address",
888 " from: $entry\n";
891 return @emails;
894 sub validate_patch {
895 my $fn = shift;
896 open(my $fh, '<', $fn)
897 or die "unable to open $fn: $!\n";
898 while (my $line = <$fh>) {
899 if (length($line) > 998) {
900 return "$.: patch contains a line longer than 998 characters";
903 return undef;