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 Git; 25 26package FakeTerm; 27sub new { 28my($class,$reason) =@_; 29returnbless \$reason,shift; 30} 31subreadline{ 32my$self=shift; 33die"Cannot use readline on FakeTerm:$$self"; 34} 35package main; 36 37 38sub usage { 39print<<EOT; 40git-send-email [options] <file | directory>... 41Options: 42 --from Specify the "From:" line of the email to be sent. 43 44 --to Specify the primary "To:" line of the email. 45 46 --cc Specify an initial "Cc:" list for the entire series 47 of emails. 48 49 --bcc Specify a list of email addresses that should be Bcc: 50 on all the emails. 51 52 --compose Use \$EDITORto edit an introductory message for the 53 patch series. 54 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. 58 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. 62 63 --chain-reply-to If set, the replies will all be to the previous 64 email sent, rather than to the first email sent. 65 Defaults to on. 66 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. 70 71 --smtp-server If set, specifies the outgoing SMTP server to use. 72 Defaults to localhost. 73 74 --suppress-from Suppress sending emails to yourself if your address 75 appears in a From: line. 76 77 --quiet Make git-send-email less verbose. One line per email 78 should be all that is output. 79 80 --dry-run Do everything except actually send the emails. 81 82 --envelope-sender Specify the envelope sender used to send the emails. 83 84EOT 85exit(1); 86} 87 88# most mail servers generate the Date: header, but not all... 89sub format_2822_time { 90my($time) =@_; 91my@localtm=localtime($time); 92my@gmttm=gmtime($time); 93my$localmin=$localtm[1] +$localtm[2] *60; 94my$gmtmin=$gmttm[1] +$gmttm[2] *60; 95if($localtm[0] !=$gmttm[0]) { 96die"local zone differs from GMT by a non-minute interval\n"; 97} 98if((($gmttm[6] +1) %7) ==$localtm[6]) { 99$localmin+=1440; 100}elsif((($gmttm[6] -1) %7) ==$localtm[6]) { 101$localmin-=1440; 102}elsif($gmttm[6] !=$localtm[6]) { 103die"local time offset greater than or equal to 24 hours\n"; 104} 105my$offset=$localmin-$gmtmin; 106my$offhour=$offset/60; 107my$offmin=abs($offset%60); 108if(abs($offhour) >=24) { 109die("local time offset greater than or equal to 24 hours\n"); 110} 111 112returnsprintf("%s,%2d%s%d%02d:%02d:%02d%s%02d%02d", 113qw(Sun Mon Tue Wed Thu Fri Sat)[$localtm[6]], 114$localtm[3], 115qw(Jan Feb Mar Apr May Jun 116 Jul Aug Sep Oct Nov Dec)[$localtm[4]], 117$localtm[5]+1900, 118$localtm[2], 119$localtm[1], 120$localtm[0], 121($offset>=0) ?'+':'-', 122abs($offhour), 123$offmin, 124); 125} 126 127my$have_email_valid=eval{require Email::Valid;1}; 128my$smtp; 129 130sub unique_email_list(@); 131sub cleanup_compose_files(); 132 133# Constants (essentially) 134my$compose_filename=".msg.$$"; 135 136# Variables we fill in automatically, or via prompting: 137my(@to,@cc,@initial_cc,@bcclist,@xh, 138$initial_reply_to,$initial_subject,@files,$from,$compose,$time); 139 140# Behavior modification variables 141my($chain_reply_to,$quiet,$suppress_from,$no_signed_off_cc, 142$dry_run) = (1,0,0,0,0); 143my$smtp_server; 144my$envelope_sender; 145 146# Example reply to: 147#$initial_reply_to = ''; #<20050203173208.GA23964@foobar.com>'; 148 149my$repo= Git->repository(); 150my$term=eval{ 151 new Term::ReadLine 'git-send-email'; 152}; 153if($@) { 154$term= new FakeTerm "$@: going non-interactive"; 155} 156 157my$def_chain=$repo->config_boolean('sendemail.chainreplyto'); 158if($def_chainand$def_chaineq'false') { 159$chain_reply_to=0; 160} 161 162@bcclist=$repo->config('sendemail.bcc'); 163if(!@bcclistor!$bcclist[0]) { 164@bcclist= (); 165} 166 167# Begin by accumulating all the variables (defined above), that we will end up 168# needing, first, from the command line: 169 170my$rc= GetOptions("from=s"=> \$from, 171"in-reply-to=s"=> \$initial_reply_to, 172"subject=s"=> \$initial_subject, 173"to=s"=> \@to, 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, 179"quiet"=> \$quiet, 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, 184); 185 186unless($rc) { 187 usage(); 188} 189 190# Verify the user input 191 192foreachmy$entry(@to) { 193die"Comma in --to entry:$entry'\n"unless$entry!~m/,/; 194} 195 196foreachmy$entry(@initial_cc) { 197die"Comma in --cc entry:$entry'\n"unless$entry!~m/,/; 198} 199 200foreachmy$entry(@bcclist) { 201die"Comma in --bcclist entry:$entry'\n"unless$entry!~m/,/; 202} 203 204# Now, let's fill any that aren't set in with defaults: 205 206my($author) =$repo->ident_person('author'); 207my($committer) =$repo->ident_person('committer'); 208 209my%aliases; 210my@alias_files=$repo->config('sendemail.aliasesfile'); 211my$aliasfiletype=$repo->config('sendemail.aliasfiletype'); 212my%parse_alias= ( 213# multiline formats can be supported in the future 214 mutt =>sub{my$fh=shift;while(<$fh>) { 215if(/^alias\s+(\S+)\s+(.*)$/) { 216my($alias,$addr) = ($1,$2); 217$addr=~s/#.*$//;# mutt allows # comments 218# commas delimit multiple addresses 219$aliases{$alias} = [split(/\s*,\s*/,$addr) ]; 220}}}, 221 mailrc =>sub{my$fh=shift;while(<$fh>) { 222if(/^alias\s+(\S+)\s+(.*)$/) { 223# spaces delimit multiple addresses 224$aliases{$1} = [split(/\s+/,$2) ]; 225}}}, 226 pine =>sub{my$fh=shift;while(<$fh>) { 227if(/^(\S+)\s+(.*)$/) { 228$aliases{$1} = [split(/\s*,\s*/,$2) ]; 229}}}, 230 gnus =>sub{my$fh=shift;while(<$fh>) { 231if(/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) { 232$aliases{$1} = [$2]; 233}}} 234); 235 236if(@alias_filesand$aliasfiletypeand defined$parse_alias{$aliasfiletype}) { 237foreachmy$file(@alias_files) { 238open my$fh,'<',$fileor die"opening$file:$!\n"; 239$parse_alias{$aliasfiletype}->($fh); 240close$fh; 241} 242} 243 244my$prompting=0; 245if(!defined$from) { 246$from=$author||$committer; 247do{ 248$_=$term->readline("Who should the emails appear to be from? [$from] "); 249}while(!defined$_); 250 251$from=$_if($_); 252print"Emails will be sent from: ",$from,"\n"; 253$prompting++; 254} 255 256if(!@to) { 257do{ 258$_=$term->readline("Who should the emails be sent to? ", 259""); 260}while(!defined$_); 261my$to=$_; 262push@to,split/,/,$to; 263$prompting++; 264} 265 266sub expand_aliases { 267my@cur=@_; 268my@last; 269do{ 270@last=@cur; 271@cur=map{$aliases{$_} ? @{$aliases{$_}} :$_}@last; 272}while(join(',',@cur)ne join(',',@last)); 273return@cur; 274} 275 276@to= expand_aliases(@to); 277@initial_cc= expand_aliases(@initial_cc); 278@bcclist= expand_aliases(@bcclist); 279 280if(!defined$initial_subject&&$compose) { 281do{ 282$_=$term->readline("What subject should the emails start with? ", 283$initial_subject); 284}while(!defined$_); 285$initial_subject=$_; 286$prompting++; 287} 288 289if(!defined$initial_reply_to&&$prompting) { 290do{ 291$_=$term->readline("Message-ID to be used as In-Reply-To for the first email? ", 292$initial_reply_to); 293}while(!defined$_); 294 295$initial_reply_to=$_; 296$initial_reply_to=~s/(^\s+|\s+$)//g; 297} 298 299if(!$smtp_server) { 300$smtp_server=$repo->config('sendemail.smtpserver'); 301} 302if(!$smtp_server) { 303foreach(qw( /usr/sbin/sendmail /usr/lib/sendmail )) { 304if(-x $_) { 305$smtp_server=$_; 306last; 307} 308} 309$smtp_server||='localhost';# could be 127.0.0.1, too... *shrug* 310} 311 312if($compose) { 313# Note that this does not need to be secure, but we will make a small 314# effort to have it be unique 315open(C,">",$compose_filename) 316or die"Failed to open for writing$compose_filename:$!"; 317print C "From$from# This line is ignored.\n"; 318printf C "Subject:%s\n\n",$initial_subject; 319printf C <<EOT; 320GIT: Please enter your email below. 321GIT: Lines beginning in "GIT: " will be removed. 322GIT: Consider including an overall diffstat or table of contents 323GIT: for the patch you are writing. 324 325EOT 326close(C); 327 328my$editor=$ENV{EDITOR}; 329$editor='vi'unlessdefined$editor; 330system($editor,$compose_filename); 331 332open(C2,">",$compose_filename.".final") 333or die"Failed to open$compose_filename.final : ".$!; 334 335open(C,"<",$compose_filename) 336or die"Failed to open$compose_filename: ".$!; 337 338while(<C>) { 339next ifm/^GIT: /; 340print C2 $_; 341} 342close(C); 343close(C2); 344 345do{ 346$_=$term->readline("Send this email? (y|n) "); 347}while(!defined$_); 348 349if(uc substr($_,0,1)ne'Y') { 350 cleanup_compose_files(); 351exit(0); 352} 353 354@files= ($compose_filename.".final"); 355} 356 357 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. 360formy$f(@ARGV) { 361if(-d $f) { 362opendir(DH,$f) 363or die"Failed to opendir$f:$!"; 364 365push@files,grep{ -f $_}map{ +$f."/".$_} 366sort readdir(DH); 367 368}elsif(-f $f) { 369push@files,$f; 370 371}else{ 372print STDERR "Skipping$f- not found.\n"; 373} 374} 375 376if(@files) { 377unless($quiet) { 378print$_,"\n"for(@files); 379} 380}else{ 381print STDERR "\nNo patch files specified!\n\n"; 382 usage(); 383} 384 385# Variables we set as part of the loop over files 386our($message_id,%mail,$subject,$reply_to,$references,$message); 387 388sub extract_valid_address { 389my$address=shift; 390my$local_part_regexp='[^<>"\s@]+'; 391my$domain_regexp='[^.<>"\s@]+(?:\.[^.<>"\s@]+)+'; 392 393# check for a local address: 394return$addressif($address=~/^($local_part_regexp)$/); 395 396if($have_email_valid) { 397returnscalar Email::Valid->address($address); 398}else{ 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)/; 402return$1; 403} 404} 405 406# Usually don't need to change anything below here. 407 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. 412 413# We'll setup a template for the message id, using the "from" address: 414my$message_id_from= extract_valid_address($from); 415my$message_id_template="<%s-git-send-email-$message_id_from>"; 416 417sub make_message_id 418{ 419my$date=time; 420my$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 423} 424 425 426 427$time=time-scalar$#files; 428 429sub unquote_rfc2047 { 430local($_) =@_; 431if(s/=\?utf-8\?q\?(.*)\?=/$1/g) { 432s/_/ /g; 433s/=([0-9A-F]{2})/chr(hex($1))/eg; 434} 435return"$_"; 436} 437 438# If an address contains a . in the name portion, the name must be quoted. 439sub sanitize_address_rfc822 440{ 441my($recipient) =@_; 442my($recipient_name) = ($recipient=~/^(.*?)\s+</); 443if($recipient_name&&$recipient_name=~/\./&&$recipient_name!~/^".*"$/) { 444my($name,$addr) = ($recipient=~/^(.*?)(\s+<.*)/); 445$recipient="\"$name\"$addr"; 446} 447return$recipient; 448} 449 450sub send_message 451{ 452my@recipients= unique_email_list(@to); 453@cc= (map{ sanitize_address_rfc822($_) }@cc); 454my$to=join(",\n\t",@recipients); 455@recipients= unique_email_list(@recipients,@cc,@bcclist); 456@recipients= (map{ extract_valid_address($_) }@recipients); 457my$date= format_2822_time($time++); 458my$gitversion='@@GIT_VERSION@@'; 459if($gitversion=~m/..GIT_VERSION../) { 460$gitversion= Git::version(); 461} 462 463my$cc=join(", ", unique_email_list(@cc)); 464$from= sanitize_address_rfc822($from); 465my$header="From:$from 466To:$to 467Cc:$cc 468Subject:$subject 469Date:$date 470Message-Id:$message_id 471X-Mailer: git-send-email$gitversion 472"; 473if($reply_to) { 474 475$header.="In-Reply-To:$reply_to\n"; 476$header.="References:$references\n"; 477} 478if(@xh) { 479$header.=join("\n",@xh) ."\n"; 480} 481 482my@sendmail_parameters= ('-i',@recipients); 483my$raw_from=$from; 484$raw_from=$envelope_senderif(defined$envelope_sender); 485$raw_from= extract_valid_address($raw_from); 486unshift(@sendmail_parameters, 487'-f',$raw_from)if(defined$envelope_sender); 488 489if($dry_run) { 490# We don't want to send the email. 491}elsif($smtp_server=~ m#^/#) { 492my$pid=open my$sm,'|-'; 493defined$pidor die$!; 494if(!$pid) { 495exec($smtp_server,@sendmail_parameters)or die$!; 496} 497print$sm"$header\n$message"; 498close$smor die$?; 499}else{ 500require Net::SMTP; 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->dataor die$smtp->message; 505$smtp->datasend("$header\n$message")or die$smtp->message; 506$smtp->dataend()or die$smtp->message; 507$smtp->okor die"Failed to send$subject\n".$smtp->message; 508} 509if($quiet) { 510printf(($dry_run?"Dry-":"")."Sent%s\n",$subject); 511}else{ 512print(($dry_run?"Dry-":"")."OK. Log says:\nDate:$date\n"); 513if($smtp_server!~ m#^/#) { 514print"Server:$smtp_server\n"; 515print"MAIL FROM:<$raw_from>\n"; 516print"RCPT TO:".join(',',(map{"<$_>"}@recipients))."\n"; 517}else{ 518print"Sendmail:$smtp_server".join(' ',@sendmail_parameters)."\n"; 519} 520print"From:$from\nSubject:$subject\nCc:$cc\nTo:$to\n\n"; 521if($smtp) { 522print"Result: ",$smtp->code,' ', 523($smtp->message=~/\n([^\n]+\n)$/s),"\n"; 524}else{ 525print"Result: OK\n"; 526} 527} 528} 529 530$reply_to=$initial_reply_to; 531$references=$initial_reply_to||''; 532make_message_id(); 533$subject=$initial_subject; 534 535foreachmy$t(@files) { 536open(F,"<",$t)or die"can't open file$t"; 537 538my$author_not_sender=undef; 539@cc=@initial_cc; 540@xh= (); 541my$input_format=undef; 542my$header_done=0; 543$message=""; 544while(<F>) { 545if(!$header_done) { 546if(/^From /) { 547$input_format='mbox'; 548next; 549} 550chomp; 551if(!defined$input_format&&/^[-A-Za-z]+:\s/) { 552$input_format='mbox'; 553} 554 555if(defined$input_format&&$input_formateq'mbox') { 556if(/^Subject:\s+(.*)$/) { 557$subject=$1; 558 559}elsif(/^(Cc|From):\s+(.*)$/) { 560if($2eq$from) { 561next if($suppress_from); 562} 563elsif($1eq'From') { 564$author_not_sender=$2; 565} 566printf("(mbox) Adding cc:%sfrom line '%s'\n", 567$2,$_)unless$quiet; 568push@cc,$2; 569} 570elsif(!/^Date:\s/&&/^[-A-Za-z]+:\s+\S/) { 571push@xh,$_; 572} 573 574}else{ 575# In the traditional 576# "send lots of email" format, 577# line 1 = cc 578# line 2 = subject 579# So let's support that, too. 580$input_format='lots'; 581if(@cc==0) { 582printf("(non-mbox) Adding cc:%sfrom line '%s'\n", 583$_,$_)unless$quiet; 584 585push@cc,$_; 586 587}elsif(!defined$subject) { 588$subject=$_; 589} 590} 591 592# A whitespace line will terminate the headers 593if(m/^\s*$/) { 594$header_done=1; 595} 596}else{ 597$message.=$_; 598if(/^(Signed-off-by|Cc): (.*)$/i&& !$no_signed_off_cc) { 599my$c=$2; 600chomp$c; 601push@cc,$c; 602printf("(sob) Adding cc:%sfrom line '%s'\n", 603$c,$_)unless$quiet; 604} 605} 606} 607close F; 608if(defined$author_not_sender) { 609$author_not_sender= unquote_rfc2047($author_not_sender); 610$message="From:$author_not_sender\n\n$message"; 611} 612 613 614 send_message(); 615 616# set up for the next message 617if($chain_reply_to|| !defined$reply_to||length($reply_to) ==0) { 618$reply_to=$message_id; 619if(length$references>0) { 620$references.="\n$message_id"; 621}else{ 622$references="$message_id"; 623} 624} 625 make_message_id(); 626} 627 628if($compose) { 629 cleanup_compose_files(); 630} 631 632sub cleanup_compose_files() { 633unlink($compose_filename,$compose_filename.".final"); 634 635} 636 637$smtp->quitif$smtp; 638 639sub unique_email_list(@) { 640my%seen; 641my@emails; 642 643foreachmy$entry(@_) { 644if(my$clean= extract_valid_address($entry)) { 645$seen{$clean} ||=0; 646next if$seen{$clean}++; 647push@emails,$entry; 648}else{ 649print STDERR "W: unable to extract a valid address", 650" from:$entry\n"; 651} 652} 653return@emails; 654}