git-send-email.perlon commit Merge branch 'db/send-email-omit-cc' (e935626)
   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
  19use strict;
  20use warnings;
  21use Term::ReadLine;
  22use Getopt::Long;
  23use Data::Dumper;
  24use Term::ANSIColor;
  25use Git;
  26
  27$SIG{INT} = sub { print color("reset"), "\n"; exit };
  28
  29package FakeTerm;
  30sub new {
  31        my ($class, $reason) = @_;
  32        return bless \$reason, shift;
  33}
  34sub readline {
  35        my $self = shift;
  36        die "Cannot use readline on FakeTerm: $$self";
  37}
  38package main;
  39
  40
  41sub usage {
  42        print <<EOT;
  43git-send-email [options] <file | directory>...
  44Options:
  45   --from         Specify the "From:" line of the email to be sent.
  46
  47   --to           Specify the primary "To:" line of the email.
  48
  49   --cc           Specify an initial "Cc:" list for the entire series
  50                  of emails.
  51
  52   --cc-cmd       Specify a command to execute per file which adds
  53                  per file specific cc address entries
  54
  55   --bcc          Specify a list of email addresses that should be Bcc:
  56                  on all the emails.
  57
  58   --compose      Use \$GIT_EDITOR, core.editor, \$EDITOR, or \$VISUAL to edit
  59                  an introductory message for the patch series.
  60
  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.
  64
  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.
  68
  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.
  72
  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.
  75
  76   --identity     The configuration identity, a subsection to prioritise over
  77                  the default section.
  78
  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.
  82
  83   --smtp-server-port Specify a port on the outgoing SMTP server to connect to.
  84
  85   --smtp-user    The username for SMTP-AUTH.
  86
  87   --smtp-pass    The password for SMTP-AUTH.
  88
  89   --smtp-ssl     If set, connects to the SMTP server using SSL.
  90
  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.
  96
  97   --suppress-from Suppress sending emails to yourself. Defaults to off.
  98
  99   --thread       Specify that the "In-Reply-To:" header should be set on all
 100                  emails. Defaults to on.
 101
 102   --quiet        Make git-send-email less verbose.  One line per email
 103                  should be all that is output.
 104
 105   --dry-run      Do everything except actually send the emails.
 106
 107   --envelope-sender    Specify the envelope sender used to send the emails.
 108
 109   --no-validate        Don't perform any sanity checks on patches.
 110
 111EOT
 112        exit(1);
 113}
 114
 115# most mail servers generate the Date: header, but not all...
 116sub 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";
 124        }
 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";
 131        }
 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");
 137        }
 138
 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,
 151                       );
 152}
 153
 154my $have_email_valid = eval { require Email::Valid; 1 };
 155my $smtp;
 156my $auth;
 157
 158sub unique_email_list(@);
 159sub cleanup_compose_files();
 160
 161# Constants (essentially)
 162my $compose_filename = ".msg.$$";
 163
 164# Variables we fill in automatically, or via prompting:
 165my (@to,@cc,@initial_cc,@bcclist,@xh,
 166        $initial_reply_to,$initial_subject,@files,$author,$sender,$compose,$time);
 167
 168my $envelope_sender;
 169
 170# Example reply to:
 171#$initial_reply_to = ''; #<20050203173208.GA23964@foobar.com>';
 172
 173my $repo = Git->repository();
 174my $term = eval {
 175        new Term::ReadLine 'git-send-email';
 176};
 177if ($@) {
 178        $term = new FakeTerm "$@: going non-interactive";
 179}
 180
 181# Behavior modification variables
 182my ($quiet, $dry_run) = (0, 0);
 183
 184# Variables with corresponding config settings
 185my ($thread, $chain_reply_to, $suppress_from, $signed_off_cc, $cc_cmd);
 186my ($smtp_server, $smtp_server_port, $smtp_authuser, $smtp_authpass, $smtp_ssl);
 187my ($identity, $aliasfiletype, @alias_files, @smtp_host_parts);
 188my ($no_validate);
 189my (@suppress_cc);
 190
 191my %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],
 197);
 198
 199my %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,
 210);
 211
 212# Begin by accumulating all the variables (defined above), that we will end up
 213# needing, first, from the command line:
 214
 215my $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,
 238         );
 239
 240unless ($rc) {
 241    usage();
 242}
 243
 244# Now, let's fill any that aren't set in with defaults:
 245
 246sub read_config {
 247        my ($prefix) = @_;
 248
 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);
 252        }
 253
 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]);
 260                        }
 261                }
 262                else {
 263                        $$target = $repo->config("$prefix.$setting") unless (defined $$target);
 264                }
 265        }
 266}
 267
 268# read configuration from [sendemail "$identity"], fall back on [sendemail]
 269$identity = $repo->config("sendemail.identity") unless (defined $identity);
 270read_config("sendemail.$identity") if (defined $identity);
 271read_config("sendemail");
 272
 273# fall back on builtin bool defaults
 274foreach my $setting (values %config_bool_settings) {
 275        ${$setting->[0]} = $setting->[1] unless (defined (${$setting->[0]}));
 276}
 277
 278# Set CC suppressions
 279my(%suppress_cc);
 280if (@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;
 285        }
 286}
 287
 288if ($suppress_cc{'all'}) {
 289        foreach my $entry (qw (ccmd cc author self sob)) {
 290                $suppress_cc{$entry} = 1;
 291        }
 292        delete $suppress_cc{'all'};
 293}
 294
 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;
 298
 299# Debugging, print out the suppressions.
 300if (0) {
 301        print "suppressions:\n";
 302        foreach my $entry (keys %suppress_cc) {
 303                printf "  %-5s -> $suppress_cc{$entry}\n", $entry;
 304        }
 305}
 306
 307my ($repoauthor) = $repo->ident_person('author');
 308my ($repocommitter) = $repo->ident_person('committer');
 309
 310# Verify the user input
 311
 312foreach my $entry (@to) {
 313        die "Comma in --to entry: $entry'\n" unless $entry !~ m/,/;
 314}
 315
 316foreach my $entry (@initial_cc) {
 317        die "Comma in --cc entry: $entry'\n" unless $entry !~ m/,/;
 318}
 319
 320foreach my $entry (@bcclist) {
 321        die "Comma in --bcclist entry: $entry'\n" unless $entry !~ m/,/;
 322}
 323
 324my %aliases;
 325my %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 ];
 346                }}}
 347);
 348
 349if (@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;
 354        }
 355}
 356
 357($sender) = expand_aliases($sender) if defined $sender;
 358
 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.
 361for my $f (@ARGV) {
 362        if (-d $f) {
 363                opendir(DH,$f)
 364                        or die "Failed to opendir $f: $!";
 365
 366                push @files, grep { -f $_ } map { +$f . "/" . $_ }
 367                                sort readdir(DH);
 368
 369        } elsif (-f $f) {
 370                push @files, $f;
 371
 372        } else {
 373                print STDERR "Skipping $f - not found.\n";
 374        }
 375}
 376
 377if (!$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";
 381        }
 382}
 383
 384if (@files) {
 385        unless ($quiet) {
 386                print $_,"\n" for (@files);
 387        }
 388} else {
 389        print STDERR "\nNo patch files specified!\n\n";
 390        usage();
 391}
 392
 393my $prompting = 0;
 394if (!defined $sender) {
 395        $sender = $repoauthor || $repocommitter;
 396        do {
 397                $_ = $term->readline("Who should the emails appear to be from? [$sender] ");
 398        } while (!defined $_);
 399
 400        $sender = $_ if ($_);
 401        print "Emails will be sent from: ", $sender, "\n";
 402        $prompting++;
 403}
 404
 405if (!@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++;
 413}
 414
 415sub 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;
 423}
 424
 425@to = expand_aliases(@to);
 426@to = (map { sanitize_address($_) } @to);
 427@initial_cc = expand_aliases(@initial_cc);
 428@bcclist = expand_aliases(@bcclist);
 429
 430if (!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++;
 437}
 438
 439if ($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 $_);
 444
 445        $initial_reply_to = $_;
 446}
 447if (defined $initial_reply_to && $_ ne "") {
 448        $initial_reply_to =~ s/^\s*<?/</;
 449        $initial_reply_to =~ s/>?\s*$/>/;
 450}
 451
 452if (!defined $smtp_server) {
 453        foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
 454                if (-x $_) {
 455                        $smtp_server = $_;
 456                        last;
 457                }
 458        }
 459        $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
 460}
 461
 462if ($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;
 470GIT: Please enter your email below.
 471GIT: Lines beginning in "GIT: " will be removed.
 472GIT: Consider including an overall diffstat or table of contents
 473GIT: for the patch you are writing.
 474
 475EOT
 476        close(C);
 477
 478        my $editor = $ENV{GIT_EDITOR} || $repo->config("core.editor") || $ENV{VISUAL} || $ENV{EDITOR} || "vi";
 479        system('sh', '-c', '$0 $@', $editor, $compose_filename);
 480
 481        open(C2,">",$compose_filename . ".final")
 482                or die "Failed to open $compose_filename.final : " . $!;
 483
 484        open(C,"<",$compose_filename)
 485                or die "Failed to open $compose_filename : " . $!;
 486
 487        while(<C>) {
 488                next if m/^GIT: /;
 489                print C2 $_;
 490        }
 491        close(C);
 492        close(C2);
 493
 494        do {
 495                $_ = $term->readline("Send this email? (y|n) ");
 496        } while (!defined $_);
 497
 498        if (uc substr($_,0,1) ne 'Y') {
 499                cleanup_compose_files();
 500                exit(0);
 501        }
 502
 503        @files = ($compose_filename . ".final", @files);
 504}
 505
 506# Variables we set as part of the loop over files
 507our ($message_id, %mail, $subject, $reply_to, $references, $message);
 508
 509sub extract_valid_address {
 510        my $address = shift;
 511        my $local_part_regexp = '[^<>"\s@]+';
 512        my $domain_regexp = '[^.<>"\s@]+(?:\.[^.<>"\s@]+)+';
 513
 514        # check for a local address:
 515        return $address if ($address =~ /^($local_part_regexp)$/);
 516
 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;
 525        }
 526}
 527
 528# Usually don't need to change anything below here.
 529
 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.
 534
 535# We'll setup a template for the message id, using the "from" address:
 536
 537my ($message_id_stamp, $message_id_serial);
 538sub make_message_id
 539{
 540        my $uniq;
 541        if (!defined $message_id_stamp) {
 542                $message_id_stamp = sprintf("%s-%s", time, $$);
 543                $message_id_serial = 0;
 544        }
 545        $message_id_serial++;
 546        $uniq = "$message_id_stamp-$message_id_serial";
 547
 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 '');
 552        }
 553        if (not defined $du_part or $du_part eq '') {
 554                use Sys::Hostname qw();
 555                $du_part = 'user@' . Sys::Hostname::hostname();
 556        }
 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
 560}
 561
 562
 563
 564$time = time - scalar $#files;
 565
 566sub 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;
 573        }
 574        return wantarray ? ($_, $encoding) : $_;
 575}
 576
 577# use the simplest quoting being able to handle the recipient
 578sub sanitize_address
 579{
 580        my ($recipient) = @_;
 581        my ($recipient_name, $recipient_addr) = ($recipient =~ /^(.*?)\s*(<.*)/);
 582
 583        if (not $recipient_name) {
 584                return "$recipient";
 585        }
 586
 587        # if recipient_name is already quoted, do nothing
 588        if ($recipient_name =~ /^(".*"|=\?utf-8\?q\?.*\?=)$/) {
 589                return $recipient;
 590        }
 591
 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\?=/;
 596        }
 597
 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\"";
 602        }
 603
 604        return "$recipient_name $recipient_addr";
 605
 606}
 607
 608sub send_message
 609{
 610        my @recipients = unique_email_list(@to);
 611        @cc = (grep { my $cc = extract_valid_address($_);
 612                      not grep { $cc eq $_ } @recipients
 613                    }
 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();
 623        }
 624
 625        my $cc = join(", ", unique_email_list(@cc));
 626        my $ccline = "";
 627        if ($cc ne '') {
 628                $ccline = "\nCc: $cc";
 629        }
 630        my $sanitized_sender = sanitize_address($sender);
 631        make_message_id() unless defined($message_id);
 632
 633        my $header = "From: $sanitized_sender
 634To: $to${ccline}
 635Subject: $subject
 636Date: $date
 637Message-Id: $message_id
 638X-Mailer: git-send-email $gitversion
 639";
 640        if ($thread && $reply_to) {
 641
 642                $header .= "In-Reply-To: $reply_to\n";
 643                $header .= "References: $references\n";
 644        }
 645        if (@xh) {
 646                $header .= join("\n", @xh) . "\n";
 647        }
 648
 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);
 655
 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 $!;
 663                }
 664                print $sm "$header\n$message";
 665                close $sm or die $?;
 666        } else {
 667
 668                if (!defined $smtp_server) {
 669                        die "The required SMTP server is not properly defined."
 670                }
 671
 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);
 676                }
 677                else {
 678                        require Net::SMTP;
 679                        $smtp ||= Net::SMTP->new((defined $smtp_server_port)
 680                                                 ? "$smtp_server:$smtp_server_port"
 681                                                 : $smtp_server);
 682                }
 683
 684                if (!$smtp) {
 685                        die "Unable to initialize SMTP properly.  Is there something wrong with your config?";
 686                }
 687
 688                if ((defined $smtp_authuser) && (defined $smtp_authpass)) {
 689                        $auth ||= $smtp->auth( $smtp_authuser, $smtp_authpass ) or die $smtp->message;
 690                }
 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;
 697        }
 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";
 708                }
 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";
 715                }
 716        }
 717}
 718
 719$reply_to = $initial_reply_to;
 720$references = $initial_reply_to || '';
 721$subject = $initial_subject;
 722
 723foreach my $t (@files) {
 724        open(F,"<",$t) or die "can't open file $t";
 725
 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;
 740                        }
 741                        chomp;
 742                        if (!defined $input_format && /^[-A-Za-z]+:\s/) {
 743                                $input_format = 'mbox';
 744                        }
 745
 746                        if (defined $input_format && $input_format eq 'mbox') {
 747                                if (/^Subject:\s+(.*)$/) {
 748                                        $subject = $1;
 749
 750                                } elsif (/^(Cc|From):\s+(.*)$/) {
 751                                        if (unquote_rfc2047($2) eq $sender) {
 752                                                next if ($suppress_cc{'self'});
 753                                        }
 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'});
 760                                        }
 761                                        printf("(mbox) Adding cc: %s from line '%s'\n",
 762                                                $2, $_) unless $quiet;
 763                                        push @cc, $2;
 764                                }
 765                                elsif (/^Content-type:/i) {
 766                                        $has_content_type = 1;
 767                                        if (/charset="?[^ "]+/) {
 768                                                $body_encoding = $1;
 769                                        }
 770                                        push @xh, $_;
 771                                }
 772                                elsif (/^Message-Id: (.*)/i) {
 773                                        $message_id = $1;
 774                                }
 775                                elsif (!/^Date:\s/ && /^[-A-Za-z]+:\s+\S/) {
 776                                        push @xh, $_;
 777                                }
 778
 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;
 789
 790                                        push @cc, $_;
 791
 792                                } elsif (!defined $subject) {
 793                                        $subject = $_;
 794                                }
 795                        }
 796
 797                        # A whitespace line will terminate the headers
 798                        if (m/^\s*$/) {
 799                                $header_done = 1;
 800                        }
 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;
 811                        }
 812                }
 813        }
 814        close F;
 815
 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;
 827                }
 828                close F
 829                        or die "(cc-cmd) failed to close pipe to '$cc_cmd'";
 830        }
 831
 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
 838                                }
 839                                else {
 840                                        # uh oh, we should re-encode
 841                                }
 842                        }
 843                        else {
 844                                push @xh,
 845                                  'MIME-Version: 1.0',
 846                                  "Content-Type: text/plain; charset=$author_encoding",
 847                                  'Content-Transfer-Encoding: 8bit';
 848                        }
 849                }
 850        }
 851
 852        send_message();
 853
 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";
 861                }
 862        }
 863        $message_id = undef;
 864}
 865
 866if ($compose) {
 867        cleanup_compose_files();
 868}
 869
 870sub cleanup_compose_files() {
 871        unlink($compose_filename, $compose_filename . ".final");
 872
 873}
 874
 875$smtp->quit if $smtp;
 876
 877sub unique_email_list(@) {
 878        my %seen;
 879        my @emails;
 880
 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";
 889                }
 890        }
 891        return @emails;
 892}
 893
 894sub 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";
 901                }
 902        }
 903        return undef;
 904}