3 # Copyright 2002,2005 Greg Kroah-Hartman <greg@kroah.com>
4 # Copyright 2005 Ryan Anderson <ryan@michonline.com>
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.
27 $SIG{INT
} = sub { print color
("reset"), "\n"; exit };
31 my ($class, $reason) = @_;
32 return bless \
$reason, shift;
36 die "Cannot use readline on FakeTerm: $$self";
43 git-send-email [options] <file | directory>...
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
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:
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.
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
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
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.
115 # most mail servers generate the Date: header, but not all...
116 sub format_2822_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]) {
127 } elsif ((($gmttm[6] - 1) % 7) == $localtm[6]) {
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]],
142 qw(Jan Feb Mar Apr May Jun
143 Jul Aug Sep Oct Nov Dec)[$localtm[4]],
148 ($offset >= 0) ?
'+' : '-',
154 my $have_email_valid = eval { require Email
::Valid
; 1 };
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);
171 #$initial_reply_to = ''; #<20050203173208.GA23964@foobar.com>';
173 my $repo = Git
->repository();
175 new Term
::ReadLine
'git-send-email';
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);
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,
206 "aliasfiletype" => \
$aliasfiletype,
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,
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,
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,
244 # Now, let's fill any that aren't set in with defaults:
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") {
258 my @values = $repo->config("$prefix.$setting");
259 @
$target = @values if (@values && defined $values[0]);
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
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.
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/,/;
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) ];
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) ];
339 pine
=> sub { my $fh = shift; while (<$fh>) {
340 if (/^(\S+)\t.*\t(.*)$/) {
341 $aliases{$1} = [ split(/\s*,\s*/, $2) ];
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);
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.
364 or die "Failed to opendir $f: $!";
366 push @files, grep { -f
$_ } map { +$f . "/" . $_ }
373 print STDERR
"Skipping $f - not found.\n";
378 foreach my $f (@files) {
379 my $error = validate_patch
($f);
380 $error and die "fatal: $f: $error\nwarning: no patches were sent\n";
386 print $_,"\n" for (@files);
389 print STDERR
"\nNo patch files specified!\n\n";
394 if (!defined $sender) {
395 $sender = $repoauthor || $repocommitter;
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";
407 $_ = $term->readline("Who should the emails be sent to? ",
409 } while (!defined $_);
411 push @to, split /,/, $to;
420 @cur = map { $aliases{$_} ? @
{$aliases{$_}} : $_ } @last;
421 } while (join(',',@cur) ne join(',',@last));
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) {
432 $_ = $term->readline("What subject should the initial email start with? ",
434 } while (!defined $_);
435 $initial_subject = $_;
439 if ($thread && !defined $initial_reply_to && $prompting) {
441 $_= $term->readline("Message-ID to be used as In-Reply-To for the first email? ",
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 )) {
459 $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
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;
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.
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 : " . $!;
495 $_ = $term->readline("Send this email? (y|n) ");
496 } while (!defined $_);
498 if (uc substr($_,0,1) ne 'Y') {
499 cleanup_compose_files
();
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
{
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);
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)/;
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);
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";
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
{
569 if (s/=\?([^?]+)\?q\?(.*)\?=/$2/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
580 my ($recipient) = @_;
581 my ($recipient_name, $recipient_addr) = ($recipient =~ /^(.*?)\s*(<.*)/);
583 if (not $recipient_name) {
587 # if recipient_name is already quoted, do nothing
588 if ($recipient_name =~ /^(".*"|=\?utf-8\?q\?.*\?=)$/) {
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";
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
($_) }
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));
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
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";
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);
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 $!;
662 exec($smtp_server, @sendmail_parameters) or die $!;
664 print $sm "$header\n$message";
668 if (!defined $smtp_server) {
669 die "The required SMTP server is not properly defined."
673 $smtp_server_port ||= 465; # ssmtp
674 require Net
::SMTP
::SSL
;
675 $smtp ||= Net
::SMTP
::SSL
->new($smtp_server, Port
=> $smtp_server_port);
679 $smtp ||= Net
::SMTP
->new((defined $smtp_server_port)
680 ?
"$smtp_server:$smtp_server_port"
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;
699 printf (($dry_run ?
"Dry-" : "")."Sent %s\n", $subject);
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";
707 print "Sendmail: $smtp_server ".join(' ',@sendmail_parameters)."\n";
711 print "Result: ", $smtp->code, ' ',
712 ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
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";
728 my $has_content_type;
732 my $input_format = undef;
738 $input_format = 'mbox';
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+(.*)$/) {
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'});
759 next if ($suppress_cc{'cc'});
761 printf("(mbox) Adding cc: %s from line '%s'\n",
762 $2, $_) unless $quiet;
765 elsif (/^Content-type:/i) {
766 $has_content_type = 1;
767 if (/charset="?[^ "]+/) {
772 elsif (/^Message-Id: (.*)/i) {
775 elsif (!/^Date:\s/ && /^[-A-Za-z]+:\s+\S/) {
781 # "send lots of email" format,
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;
792 } elsif (!defined $subject) {
797 # A whitespace line will terminate the headers
803 if (/^(Signed-off-by|Cc): (.*)$/i) {
804 next if ($suppress_cc{'sob'});
807 next if ($c eq $sender and $suppress_cc{'self'});
809 printf("(sob) Adding cc: %s from line '%s'\n",
810 $c, $_) unless $quiet;
816 if (defined $cc_cmd && !$suppress_cc{'cccmd'}) {
817 open(F
, "$cc_cmd $t |")
818 or die "(cc-cmd) Could not execute '$cc_cmd'";
823 next if ($c eq $sender and $suppress_from);
825 printf("(cc-cmd) Adding cc: %s from: '%s'\n",
826 $c, $cc_cmd) unless $quiet;
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
840 # uh oh, we should re-encode
846 "Content-Type: text/plain; charset=$author_encoding",
847 'Content-Transfer-Encoding: 8bit';
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";
860 $references = "$message_id";
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
(@
) {
881 foreach my $entry (@_) {
882 if (my $clean = extract_valid_address
($entry)) {
884 next if $seen{$clean}++;
885 push @emails, $entry;
887 print STDERR
"W: unable to extract a valid address",
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";