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