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 \$EDITOR to edit an introductory message for the
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 --no-signed-off-cc Suppress the automatic addition of email addresses
68 that appear in Signed-off-by: or Cc: lines to the cc:
69 list. Note: Using this option is not recommended.
71 --smtp-server If set, specifies the outgoing SMTP server to use.
72 Defaults to localhost.
74 --suppress-from Suppress sending emails to yourself if your address
75 appears in a From: line.
77 --quiet Make git-send-email less verbose. One line per email
78 should be all that is output.
80 --dry-run Do everything except actually send the emails.
82 --envelope-sender Specify the envelope sender used to send the emails.
88 # most mail servers generate the Date: header, but not all...
89 sub format_2822_time {
91 my @localtm = localtime($time);
92 my @gmttm = gmtime($time);
93 my $localmin = $localtm[1] + $localtm[2] * 60;
94 my $gmtmin = $gmttm[1] + $gmttm[2] * 60;
95 if ($localtm[0] != $gmttm[0]) {
96 die "local zone differs from GMT by a non-minute interval\n";
98 if ((($gmttm[6] + 1) % 7) == $localtm[6]) {
100 } elsif ((($gmttm[6] - 1) % 7) == $localtm[6]) {
102 } elsif ($gmttm[6] != $localtm[6]) {
103 die "local time offset greater than or equal to 24 hours\n";
105 my $offset = $localmin - $gmtmin;
106 my $offhour = $offset / 60;
107 my $offmin = abs($offset % 60);
108 if (abs($offhour) >= 24) {
109 die ("local time offset greater than or equal to 24 hours\n");
112 return sprintf("%s, %2d %s %d %02d:%02d:%02d %s%02d%02d",
113 qw(Sun Mon Tue Wed Thu Fri Sat)[$localtm[6]],
115 qw(Jan Feb Mar Apr May Jun
116 Jul Aug Sep Oct Nov Dec)[$localtm[4]],
121 ($offset >= 0) ? '+' : '-',
127 my $have_email_valid = eval { require Email::Valid; 1 };
130 sub unique_email_list(@);
131 sub cleanup_compose_files();
133 # Constants (essentially)
134 my $compose_filename = ".msg.$$";
136 # Variables we fill in automatically, or via prompting:
137 my (@to,@cc,@initial_cc,@bcclist,@xh,
138 $initial_reply_to,$initial_subject,@files,$from,$compose,$time);
140 # Behavior modification variables
141 my ($chain_reply_to, $quiet, $suppress_from, $no_signed_off_cc,
142 $dry_run) = (1, 0, 0, 0, 0);
147 #$initial_reply_to = ''; #<20050203173208.GA23964@foobar.com>';
149 my $repo = Git->repository();
151 new Term::ReadLine 'git-send-email';
154 $term = new FakeTerm "$@: going non-interactive";
157 my $def_chain = $repo->config_boolean('sendemail.chainreplyto');
158 if ($def_chain and $def_chain eq 'false') {
162 @bcclist = $repo->config('sendemail.bcc');
163 if (!@bcclist or !$bcclist[0]) {
167 # Begin by accumulating all the variables (defined above), that we will end up
168 # needing, first, from the command line:
170 my $rc = GetOptions("from=s" => \$from,
171 "in-reply-to=s" => \$initial_reply_to,
172 "subject=s" => \$initial_subject,
174 "cc=s" => \@initial_cc,
175 "bcc=s" => \@bcclist,
176 "chain-reply-to!" => \$chain_reply_to,
177 "smtp-server=s" => \$smtp_server,
178 "compose" => \$compose,
180 "suppress-from" => \$suppress_from,
181 "no-signed-off-cc|no-signed-off-by-cc" => \$no_signed_off_cc,
182 "dry-run" => \$dry_run,
183 "envelope-sender=s" => \$envelope_sender,
190 # Verify the user input
192 foreach my $entry (@to) {
193 die "Comma in --to entry: $entry'\n" unless $entry !~ m/,/;
196 foreach my $entry (@initial_cc) {
197 die "Comma in --cc entry: $entry'\n" unless $entry !~ m/,/;
200 foreach my $entry (@bcclist) {
201 die "Comma in --bcclist entry: $entry'\n" unless $entry !~ m/,/;
204 # Now, let's fill any that aren't set in with defaults:
206 my ($author) = $repo->ident_person('author');
207 my ($committer) = $repo->ident_person('committer');
210 my @alias_files = $repo->config('sendemail.aliasesfile');
211 my $aliasfiletype = $repo->config('sendemail.aliasfiletype');
213 # multiline formats can be supported in the future
214 mutt => sub { my $fh = shift; while (<$fh>) {
215 if (/^alias\s+(\S+)\s+(.*)$/) {
216 my ($alias, $addr) = ($1, $2);
217 $addr =~ s/#.*$//; # mutt allows # comments
218 # commas delimit multiple addresses
219 $aliases{$alias} = [ split(/\s*,\s*/, $addr) ];
221 mailrc => sub { my $fh = shift; while (<$fh>) {
222 if (/^alias\s+(\S+)\s+(.*)$/) {
223 # spaces delimit multiple addresses
224 $aliases{$1} = [ split(/\s+/, $2) ];
226 pine => sub { my $fh = shift; while (<$fh>) {
227 if (/^(\S+)\s+(.*)$/) {
228 $aliases{$1} = [ split(/\s*,\s*/, $2) ];
230 gnus => sub { my $fh = shift; while (<$fh>) {
231 if (/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) {
232 $aliases{$1} = [ $2 ];
236 if (@alias_files and $aliasfiletype and defined $parse_alias{$aliasfiletype}) {
237 foreach my $file (@alias_files) {
238 open my $fh, '<', $file or die "opening $file: $!\n";
239 $parse_alias{$aliasfiletype}->($fh);
245 if (!defined $from) {
246 $from = $author || $committer;
248 $_ = $term->readline("Who should the emails appear to be from? [$from] ");
249 } while (!defined $_);
252 print "Emails will be sent from: ", $from, "\n";
258 $_ = $term->readline("Who should the emails be sent to? ",
260 } while (!defined $_);
262 push @to, split /,/, $to;
271 @cur = map { $aliases{$_} ? @{$aliases{$_}} : $_ } @last;
272 } while (join(',',@cur) ne join(',',@last));
276 @to = expand_aliases(@to);
277 @initial_cc = expand_aliases(@initial_cc);
278 @bcclist = expand_aliases(@bcclist);
280 if (!defined $initial_subject && $compose) {
282 $_ = $term->readline("What subject should the emails start with? ",
284 } while (!defined $_);
285 $initial_subject = $_;
289 if (!defined $initial_reply_to && $prompting) {
291 $_= $term->readline("Message-ID to be used as In-Reply-To for the first email? ",
293 } while (!defined $_);
295 $initial_reply_to = $_;
296 $initial_reply_to =~ s/(^\s+|\s+$)//g;
300 $smtp_server = $repo->config('sendemail.smtpserver');
303 foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
309 $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
313 # Note that this does not need to be secure, but we will make a small
314 # effort to have it be unique
315 open(C,">",$compose_filename)
316 or die "Failed to open for writing $compose_filename: $!";
317 print C "From $from # This line is ignored.\n";
318 printf C "Subject: %s\n\n", $initial_subject;
320 GIT: Please enter your email below.
321 GIT: Lines beginning in "GIT: " will be removed.
322 GIT: Consider including an overall diffstat or table of contents
323 GIT: for the patch you are writing.
328 my $editor = $ENV{EDITOR};
329 $editor = 'vi' unless defined $editor;
330 system($editor, $compose_filename);
332 open(C2,">",$compose_filename . ".final")
333 or die "Failed to open $compose_filename.final : " . $!;
335 open(C,"<",$compose_filename)
336 or die "Failed to open $compose_filename : " . $!;
346 $_ = $term->readline("Send this email? (y|n) ");
347 } while (!defined $_);
349 if (uc substr($_,0,1) ne 'Y') {
350 cleanup_compose_files();
354 @files = ($compose_filename . ".final");
358 # Now that all the defaults are set, process the rest of the command line
359 # arguments and collect up the files that need to be processed.
363 or die "Failed to opendir $f: $!";
365 push @files, grep { -f $_ } map { +$f . "/" . $_ }
372 print STDERR "Skipping $f - not found.\n";
378 print $_,"\n" for (@files);
381 print STDERR "\nNo patch files specified!\n\n";
385 # Variables we set as part of the loop over files
386 our ($message_id, %mail, $subject, $reply_to, $references, $message);
388 sub extract_valid_address {
390 my $local_part_regexp = '[^<>"\s@]+';
391 my $domain_regexp = '[^.<>"\s@]+(?:\.[^.<>"\s@]+)+';
393 # check for a local address:
394 return $address if ($address =~ /^($local_part_regexp)$/);
396 if ($have_email_valid) {
397 return scalar Email::Valid->address($address);
399 # less robust/correct than the monster regexp in Email::Valid,
400 # but still does a 99% job, and one less dependency
401 $address =~ /($local_part_regexp\@$domain_regexp)/;
406 # Usually don't need to change anything below here.
408 # we make a "fake" message id by taking the current number
409 # of seconds since the beginning of Unix time and tacking on
410 # a random number to the end, in case we are called quicker than
411 # 1 second since the last time we were called.
413 # We'll setup a template for the message id, using the "from" address:
414 my $message_id_from = extract_valid_address($from);
415 my $message_id_template = "<%s-git-send-email-$message_id_from>";
420 my $pseudo_rand = int (rand(4200));
421 $message_id = sprintf $message_id_template, "$date$pseudo_rand";
422 #print "new message id = $message_id\n"; # Was useful for debugging
427 $time = time - scalar $#files;
429 sub unquote_rfc2047 {
431 if (s/=\?utf-8\?q\?(.*)\?=/$1/g) {
433 s/=([0-9A-F]{2})/chr(hex($1))/eg;
438 # If an address contains a . in the name portion, the name must be quoted.
439 sub sanitize_address_rfc822
441 my ($recipient) = @_;
442 my ($recipient_name) = ($recipient =~ /^(.*?)\s+</);
443 if ($recipient_name && $recipient_name =~ /\./ && $recipient_name !~ /^".*"$/) {
444 my ($name, $addr) = ($recipient =~ /^(.*?)(\s+<.*)/);
445 $recipient = "\"$name\"$addr";
452 my @recipients = unique_email_list(@to);
453 @cc = (map { sanitize_address_rfc822($_) } @cc);
454 my $to = join (",\n\t", @recipients);
455 @recipients = unique_email_list(@recipients,@cc,@bcclist);
456 @recipients = (map { extract_valid_address($_) } @recipients);
457 my $date = format_2822_time($time++);
458 my $gitversion = '@@GIT_VERSION@@';
459 if ($gitversion =~ m/..GIT_VERSION../) {
460 $gitversion = Git::version();
463 my $cc = join(", ", unique_email_list(@cc));
464 $from = sanitize_address_rfc822($from);
465 my $header = "From: $from
470 Message-Id: $message_id
471 X-Mailer: git-send-email $gitversion
475 $header .= "In-Reply-To: $reply_to\n";
476 $header .= "References: $references\n";
479 $header .= join("\n", @xh) . "\n";
482 my @sendmail_parameters = ('-i', @recipients);
483 my $raw_from = $from;
484 $raw_from = $envelope_sender if (defined $envelope_sender);
485 $raw_from = extract_valid_address($raw_from);
486 unshift (@sendmail_parameters,
487 '-f', $raw_from) if(defined $envelope_sender);
490 # We don't want to send the email.
491 } elsif ($smtp_server =~ m#^/#) {
492 my $pid = open my $sm, '|-';
493 defined $pid or die $!;
495 exec($smtp_server, @sendmail_parameters) or die $!;
497 print $sm "$header\n$message";
501 $smtp ||= Net::SMTP->new( $smtp_server );
502 $smtp->mail( $raw_from ) or die $smtp->message;
503 $smtp->to( @recipients ) or die $smtp->message;
504 $smtp->data or die $smtp->message;
505 $smtp->datasend("$header\n$message") or die $smtp->message;
506 $smtp->dataend() or die $smtp->message;
507 $smtp->ok or die "Failed to send $subject\n".$smtp->message;
510 printf (($dry_run ? "Dry-" : "")."Sent %s\n", $subject);
512 print (($dry_run ? "Dry-" : "")."OK. Log says:\nDate: $date\n");
513 if ($smtp_server !~ m#^/#) {
514 print "Server: $smtp_server\n";
515 print "MAIL FROM:<$raw_from>\n";
516 print "RCPT TO:".join(',',(map { "<$_>" } @recipients))."\n";
518 print "Sendmail: $smtp_server ".join(' ',@sendmail_parameters)."\n";
520 print "From: $from\nSubject: $subject\nCc: $cc\nTo: $to\n\n";
522 print "Result: ", $smtp->code, ' ',
523 ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
525 print "Result: OK\n";
530 $reply_to = $initial_reply_to;
531 $references = $initial_reply_to || '';
533 $subject = $initial_subject;
535 foreach my $t (@files) {
536 open(F,"<",$t) or die "can't open file $t";
538 my $author_not_sender = undef;
541 my $input_format = undef;
547 $input_format = 'mbox';
551 if (!defined $input_format && /^[-A-Za-z]+:\s/) {
552 $input_format = 'mbox';
555 if (defined $input_format && $input_format eq 'mbox') {
556 if (/^Subject:\s+(.*)$/) {
559 } elsif (/^(Cc|From):\s+(.*)$/) {
561 next if ($suppress_from);
563 elsif ($1 eq 'From') {
564 $author_not_sender = $2;
566 printf("(mbox) Adding cc: %s from line '%s'\n",
567 $2, $_) unless $quiet;
570 elsif (!/^Date:\s/ && /^[-A-Za-z]+:\s+\S/) {
576 # "send lots of email" format,
579 # So let's support that, too.
580 $input_format = 'lots';
582 printf("(non-mbox) Adding cc: %s from line '%s'\n",
583 $_, $_) unless $quiet;
587 } elsif (!defined $subject) {
592 # A whitespace line will terminate the headers
598 if (/^(Signed-off-by|Cc): (.*)$/i && !$no_signed_off_cc) {
602 printf("(sob) Adding cc: %s from line '%s'\n",
603 $c, $_) unless $quiet;
608 if (defined $author_not_sender) {
609 $author_not_sender = unquote_rfc2047($author_not_sender);
610 $message = "From: $author_not_sender\n\n$message";
616 # set up for the next message
617 if ($chain_reply_to || !defined $reply_to || length($reply_to) == 0) {
618 $reply_to = $message_id;
619 if (length $references > 0) {
620 $references .= "\n $message_id";
622 $references = "$message_id";
629 cleanup_compose_files();
632 sub cleanup_compose_files() {
633 unlink($compose_filename, $compose_filename . ".final");
637 $smtp->quit if $smtp;
639 sub unique_email_list(@) {
643 foreach my $entry (@_) {
644 if (my $clean = extract_valid_address($entry)) {
646 next if $seen{$clean}++;
647 push @emails, $entry;
649 print STDERR "W: unable to extract a valid address",