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.
28 my ($class, $reason) = @_;
29 return bless \
$reason, shift;
33 die "Cannot use readline on FakeTerm: $$self";
40 git-send-email [options] <file | directory>...
42 --from Specify the "From:" line of the email to be sent.
44 --to Specify the primary "To:" line of the email.
46 --cc Specify an initial "Cc:" list for the entire series
49 --bcc Specify a list of email addresses that should be Bcc:
52 --compose Use \$GIT_EDITOR, core.editor, \$EDITOR, or \$VISUAL to edit
53 an introductory message for the patch series.
55 --subject Specify the initial "Subject:" line.
56 Only necessary if --compose is also set. If --compose
57 is not set, this will be prompted for.
59 --in-reply-to Specify the first "In-Reply-To:" header line.
60 Only used if --compose is also set. If --compose is not
61 set, this will be prompted for.
63 --chain-reply-to If set, the replies will all be to the previous
64 email sent, rather than to the first email sent.
67 --signed-off-cc Automatically add email addresses that appear in
68 Signed-off-by: or Cc: lines to the cc: list. Defaults to on.
70 --smtp-server If set, specifies the outgoing SMTP server to use.
71 Defaults to localhost.
73 --suppress-from Suppress sending emails to yourself if your address
74 appears in a From: line. Defaults to off.
76 --thread Specify that the "In-Reply-To:" header should be set on all
77 emails. Defaults to on.
79 --quiet Make git-send-email less verbose. One line per email
80 should be all that is output.
82 --dry-run Do everything except actually send the emails.
84 --envelope-sender Specify the envelope sender used to send the emails.
90 # most mail servers generate the Date: header, but not all...
91 sub format_2822_time
{
93 my @localtm = localtime($time);
94 my @gmttm = gmtime($time);
95 my $localmin = $localtm[1] + $localtm[2] * 60;
96 my $gmtmin = $gmttm[1] + $gmttm[2] * 60;
97 if ($localtm[0] != $gmttm[0]) {
98 die "local zone differs from GMT by a non-minute interval\n";
100 if ((($gmttm[6] + 1) % 7) == $localtm[6]) {
102 } elsif ((($gmttm[6] - 1) % 7) == $localtm[6]) {
104 } elsif ($gmttm[6] != $localtm[6]) {
105 die "local time offset greater than or equal to 24 hours\n";
107 my $offset = $localmin - $gmtmin;
108 my $offhour = $offset / 60;
109 my $offmin = abs($offset % 60);
110 if (abs($offhour) >= 24) {
111 die ("local time offset greater than or equal to 24 hours\n");
114 return sprintf("%s, %2d %s %d %02d:%02d:%02d %s%02d%02d",
115 qw(Sun Mon Tue Wed Thu Fri Sat)[$localtm[6]],
117 qw(Jan Feb Mar Apr May Jun
118 Jul Aug Sep Oct Nov Dec)[$localtm[4]],
123 ($offset >= 0) ?
'+' : '-',
129 my $have_email_valid = eval { require Email
::Valid
; 1 };
132 sub unique_email_list
(@
);
133 sub cleanup_compose_files
();
135 # Constants (essentially)
136 my $compose_filename = ".msg.$$";
138 # Variables we fill in automatically, or via prompting:
139 my (@to,@cc,@initial_cc,@bcclist,@xh,
140 $initial_reply_to,$initial_subject,@files,$from,$compose,$time);
146 #$initial_reply_to = ''; #<20050203173208.GA23964@foobar.com>';
148 my $repo = Git
->repository();
150 new Term
::ReadLine
'git-send-email';
153 $term = new FakeTerm
"$@: going non-interactive";
156 # Behavior modification variables
157 my ($quiet, $dry_run) = (0, 0);
159 # Variables with corresponding config settings
160 my ($thread, $chain_reply_to, $suppress_from, $signed_off_cc);
162 my %config_settings = (
163 "thread" => [\
$thread, 1],
164 "chainreplyto" => [\
$chain_reply_to, 1],
165 "suppressfrom" => [\
$suppress_from, 0],
166 "signedoffcc" => [\
$signed_off_cc, 1],
169 foreach my $setting (keys %config_settings) {
170 my $config = $repo->config_bool("sendemail.$setting");
171 ${$config_settings{$setting}->[0]} = (defined $config) ?
$config : $config_settings{$setting}->[1];
174 @bcclist = $repo->config('sendemail.bcc');
175 if (!@bcclist or !$bcclist[0]) {
179 # Begin by accumulating all the variables (defined above), that we will end up
180 # needing, first, from the command line:
182 my $rc = GetOptions
("from=s" => \
$from,
183 "in-reply-to=s" => \
$initial_reply_to,
184 "subject=s" => \
$initial_subject,
186 "cc=s" => \
@initial_cc,
187 "bcc=s" => \
@bcclist,
188 "chain-reply-to!" => \
$chain_reply_to,
189 "smtp-server=s" => \
$smtp_server,
190 "compose" => \
$compose,
192 "suppress-from!" => \
$suppress_from,
193 "signed-off-cc|signed-off-by-cc!" => \
$signed_off_cc,
194 "dry-run" => \
$dry_run,
195 "envelope-sender=s" => \
$envelope_sender,
196 "thread!" => \
$thread,
203 # Verify the user input
205 foreach my $entry (@to) {
206 die "Comma in --to entry: $entry'\n" unless $entry !~ m/,/;
209 foreach my $entry (@initial_cc) {
210 die "Comma in --cc entry: $entry'\n" unless $entry !~ m/,/;
213 foreach my $entry (@bcclist) {
214 die "Comma in --bcclist entry: $entry'\n" unless $entry !~ m/,/;
217 # Now, let's fill any that aren't set in with defaults:
219 my ($author) = $repo->ident_person('author');
220 my ($committer) = $repo->ident_person('committer');
223 my @alias_files = $repo->config('sendemail.aliasesfile');
224 my $aliasfiletype = $repo->config('sendemail.aliasfiletype');
226 # multiline formats can be supported in the future
227 mutt
=> sub { my $fh = shift; while (<$fh>) {
228 if (/^\s*alias\s+(\S+)\s+(.*)$/) {
229 my ($alias, $addr) = ($1, $2);
230 $addr =~ s/#.*$//; # mutt allows # comments
231 # commas delimit multiple addresses
232 $aliases{$alias} = [ split(/\s*,\s*/, $addr) ];
234 mailrc
=> sub { my $fh = shift; while (<$fh>) {
235 if (/^alias\s+(\S+)\s+(.*)$/) {
236 # spaces delimit multiple addresses
237 $aliases{$1} = [ split(/\s+/, $2) ];
239 pine
=> sub { my $fh = shift; while (<$fh>) {
240 if (/^(\S+)\t.*\t(.*)$/) {
241 $aliases{$1} = [ split(/\s*,\s*/, $2) ];
243 gnus
=> sub { my $fh = shift; while (<$fh>) {
244 if (/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) {
245 $aliases{$1} = [ $2 ];
249 if (@alias_files and $aliasfiletype and defined $parse_alias{$aliasfiletype}) {
250 foreach my $file (@alias_files) {
251 open my $fh, '<', $file or die "opening $file: $!\n";
252 $parse_alias{$aliasfiletype}->($fh);
257 ($from) = expand_aliases
($from) if defined $from;
260 if (!defined $from) {
261 $from = $author || $committer;
263 $_ = $term->readline("Who should the emails appear to be from? [$from] ");
264 } while (!defined $_);
267 print "Emails will be sent from: ", $from, "\n";
273 $_ = $term->readline("Who should the emails be sent to? ",
275 } while (!defined $_);
277 push @to, split /,/, $to;
286 @cur = map { $aliases{$_} ? @
{$aliases{$_}} : $_ } @last;
287 } while (join(',',@cur) ne join(',',@last));
291 @to = expand_aliases
(@to);
292 @to = (map { sanitize_address
($_) } @to);
293 @initial_cc = expand_aliases
(@initial_cc);
294 @bcclist = expand_aliases
(@bcclist);
296 if (!defined $initial_subject && $compose) {
298 $_ = $term->readline("What subject should the emails start with? ",
300 } while (!defined $_);
301 $initial_subject = $_;
305 if ($thread && !defined $initial_reply_to && $prompting) {
307 $_= $term->readline("Message-ID to be used as In-Reply-To for the first email? ",
309 } while (!defined $_);
311 $initial_reply_to = $_;
312 $initial_reply_to =~ s/(^\s+|\s+$)//g;
316 $smtp_server = $repo->config('sendemail.smtpserver');
319 foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
325 $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
329 # Note that this does not need to be secure, but we will make a small
330 # effort to have it be unique
331 open(C
,">",$compose_filename)
332 or die "Failed to open for writing $compose_filename: $!";
333 print C
"From $from # This line is ignored.\n";
334 printf C
"Subject: %s\n\n", $initial_subject;
336 GIT: Please enter your email below.
337 GIT: Lines beginning in "GIT: " will be removed.
338 GIT: Consider including an overall diffstat or table of contents
339 GIT: for the patch you are writing.
344 my $editor = $ENV{GIT_EDITOR
} || $repo->config("core.editor") || $ENV{VISUAL
} || $ENV{EDITOR
} || "vi";
345 system($editor, $compose_filename);
347 open(C2
,">",$compose_filename . ".final")
348 or die "Failed to open $compose_filename.final : " . $!;
350 open(C
,"<",$compose_filename)
351 or die "Failed to open $compose_filename : " . $!;
361 $_ = $term->readline("Send this email? (y|n) ");
362 } while (!defined $_);
364 if (uc substr($_,0,1) ne 'Y') {
365 cleanup_compose_files
();
369 @files = ($compose_filename . ".final");
373 # Now that all the defaults are set, process the rest of the command line
374 # arguments and collect up the files that need to be processed.
378 or die "Failed to opendir $f: $!";
380 push @files, grep { -f
$_ } map { +$f . "/" . $_ }
387 print STDERR
"Skipping $f - not found.\n";
393 print $_,"\n" for (@files);
396 print STDERR
"\nNo patch files specified!\n\n";
400 # Variables we set as part of the loop over files
401 our ($message_id, %mail, $subject, $reply_to, $references, $message);
403 sub extract_valid_address
{
405 my $local_part_regexp = '[^<>"\s@]+';
406 my $domain_regexp = '[^.<>"\s@]+(?:\.[^.<>"\s@]+)+';
408 # check for a local address:
409 return $address if ($address =~ /^($local_part_regexp)$/);
411 if ($have_email_valid) {
412 $address =~ s/^\s*<(.*)>\s*$/$1/;
413 return scalar Email
::Valid
->address($address);
415 # less robust/correct than the monster regexp in Email::Valid,
416 # but still does a 99% job, and one less dependency
417 $address =~ /($local_part_regexp\@$domain_regexp)/;
422 # Usually don't need to change anything below here.
424 # we make a "fake" message id by taking the current number
425 # of seconds since the beginning of Unix time and tacking on
426 # a random number to the end, in case we are called quicker than
427 # 1 second since the last time we were called.
429 # We'll setup a template for the message id, using the "from" address:
434 my $pseudo_rand = int (rand(4200));
436 for ($from, $committer, $author) {
437 $du_part = extract_valid_address
($_);
438 last if ($du_part ne '');
440 if ($du_part eq '') {
441 use Sys
::Hostname
qw();
442 $du_part = 'user@' . Sys
::Hostname
::hostname
();
444 my $message_id_template = "<%s-git-send-email-$du_part>";
445 $message_id = sprintf $message_id_template, "$date$pseudo_rand";
446 #print "new message id = $message_id\n"; # Was useful for debugging
451 $time = time - scalar $#files;
453 sub unquote_rfc2047
{
455 if (s/=\?utf-8\?q\?(.*)\?=/$1/g) {
457 s/=([0-9A-F]{2})/chr(hex($1))/eg;
462 # use the simplest quoting being able to handle the recipient
465 my ($recipient) = @_;
466 my ($recipient_name, $recipient_addr) = ($recipient =~ /^(.*?)\s*(<.*)/);
468 if (not $recipient_name) {
472 # if recipient_name is already quoted, do nothing
473 if ($recipient_name =~ /^(".*"|=\?utf-8\?q\?.*\?=)$/) {
477 # rfc2047 is needed if a non-ascii char is included
478 if ($recipient_name =~ /[^[:ascii:]]/) {
479 $recipient_name =~ s/([^-a-zA-Z0-9!*+\/])/sprintf
("=%02X", ord($1))/eg
;
480 $recipient_name =~ s/(.*)/=\?utf-8\?q\?$1\?=/;
483 # double quotes are needed if specials or CTLs are included
484 elsif ($recipient_name =~ /[][()<>@,;:\\".\000-\037\177]/) {
485 $recipient_name =~ s/(["\\\r])/\\$1/;
486 $recipient_name = "\"$recipient_name\"";
489 return "$recipient_name $recipient_addr";
495 my @recipients = unique_email_list
(@to);
496 @cc = (map { sanitize_address
($_) } @cc);
497 my $to = join (",\n\t", @recipients);
498 @recipients = unique_email_list
(@recipients,@cc,@bcclist);
499 @recipients = (map { extract_valid_address
($_) } @recipients);
500 my $date = format_2822_time
($time++);
501 my $gitversion = '@@GIT_VERSION@@';
502 if ($gitversion =~ m/..GIT_VERSION../) {
503 $gitversion = Git
::version
();
506 my $cc = join(", ", unique_email_list
(@cc));
509 $ccline = "\nCc: $cc";
511 $from = sanitize_address
($from);
514 my $header = "From: $from
518 Message-Id: $message_id
519 X-Mailer: git-send-email $gitversion
521 if ($thread && $reply_to) {
523 $header .= "In-Reply-To: $reply_to\n";
524 $header .= "References: $references\n";
527 $header .= join("\n", @xh) . "\n";
530 my @sendmail_parameters = ('-i', @recipients);
531 my $raw_from = $from;
532 $raw_from = $envelope_sender if (defined $envelope_sender);
533 $raw_from = extract_valid_address
($raw_from);
534 unshift (@sendmail_parameters,
535 '-f', $raw_from) if(defined $envelope_sender);
538 # We don't want to send the email.
539 } elsif ($smtp_server =~ m
#^/#) {
540 my $pid = open my $sm, '|-';
541 defined $pid or die $!;
543 exec($smtp_server, @sendmail_parameters) or die $!;
545 print $sm "$header\n$message";
549 $smtp ||= Net
::SMTP
->new( $smtp_server );
550 $smtp->mail( $raw_from ) or die $smtp->message;
551 $smtp->to( @recipients ) or die $smtp->message;
552 $smtp->data or die $smtp->message;
553 $smtp->datasend("$header\n$message") or die $smtp->message;
554 $smtp->dataend() or die $smtp->message;
555 $smtp->ok or die "Failed to send $subject\n".$smtp->message;
558 printf (($dry_run ?
"Dry-" : "")."Sent %s\n", $subject);
560 print (($dry_run ?
"Dry-" : "")."OK. Log says:\nDate: $date\n");
561 if ($smtp_server !~ m
#^/#) {
562 print "Server: $smtp_server\n";
563 print "MAIL FROM:<$raw_from>\n";
564 print "RCPT TO:".join(',',(map { "<$_>" } @recipients))."\n";
566 print "Sendmail: $smtp_server ".join(' ',@sendmail_parameters)."\n";
568 print "From: $from\nSubject: $subject\nCc: $cc\nTo: $to\n\n";
570 print "Result: ", $smtp->code, ' ',
571 ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
573 print "Result: OK\n";
578 $reply_to = $initial_reply_to;
579 $references = $initial_reply_to || '';
580 $subject = $initial_subject;
582 foreach my $t (@files) {
583 open(F
,"<",$t) or die "can't open file $t";
585 my $author_not_sender = undef;
588 my $input_format = undef;
594 $input_format = 'mbox';
598 if (!defined $input_format && /^[-A-Za-z]+:\s/) {
599 $input_format = 'mbox';
602 if (defined $input_format && $input_format eq 'mbox') {
603 if (/^Subject:\s+(.*)$/) {
606 } elsif (/^(Cc|From):\s+(.*)$/) {
607 if (unquote_rfc2047
($2) eq $from) {
609 next if ($suppress_from);
611 elsif ($1 eq 'From') {
612 $author_not_sender = $2;
614 printf("(mbox) Adding cc: %s from line '%s'\n",
615 $2, $_) unless $quiet;
618 elsif (!/^Date:\s/ && /^[-A-Za-z]+:\s+\S/) {
624 # "send lots of email" format,
627 # So let's support that, too.
628 $input_format = 'lots';
630 printf("(non-mbox) Adding cc: %s from line '%s'\n",
631 $_, $_) unless $quiet;
635 } elsif (!defined $subject) {
640 # A whitespace line will terminate the headers
646 if (/^(Signed-off-by|Cc): (.*)$/i && $signed_off_cc) {
650 printf("(sob) Adding cc: %s from line '%s'\n",
651 $c, $_) unless $quiet;
656 if (defined $author_not_sender) {
657 $author_not_sender = unquote_rfc2047
($author_not_sender);
658 $message = "From: $author_not_sender\n\n$message";
664 # set up for the next message
665 if ($chain_reply_to || !defined $reply_to || length($reply_to) == 0) {
666 $reply_to = $message_id;
667 if (length $references > 0) {
668 $references .= "\n $message_id";
670 $references = "$message_id";
676 cleanup_compose_files
();
679 sub cleanup_compose_files
() {
680 unlink($compose_filename, $compose_filename . ".final");
684 $smtp->quit if $smtp;
686 sub unique_email_list
(@
) {
690 foreach my $entry (@_) {
691 if (my $clean = extract_valid_address
($entry)) {
693 next if $seen{$clean}++;
694 push @emails, $entry;
696 print STDERR
"W: unable to extract a valid address",