PHPMailer.php 175 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126
  1. <?php
  2. /**
  3. * PHPMailer - PHP email creation and transport class.
  4. * PHP Version 5.5.
  5. *
  6. * @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
  7. *
  8. * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
  9. * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
  10. * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
  11. * @author Brent R. Matzelle (original founder)
  12. * @copyright 2012 - 2020 Marcus Bointon
  13. * @copyright 2010 - 2012 Jim Jagielski
  14. * @copyright 2004 - 2009 Andy Prevost
  15. * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
  16. * @note This program is distributed in the hope that it will be useful - WITHOUT
  17. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  18. * FITNESS FOR A PARTICULAR PURPOSE.
  19. */
  20. namespace PHPMailer\PHPMailer;
  21. /**
  22. * PHPMailer - PHP email creation and transport class.
  23. *
  24. * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
  25. * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
  26. * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
  27. * @author Brent R. Matzelle (original founder)
  28. */
  29. class PHPMailer
  30. {
  31. const CHARSET_ASCII = 'us-ascii';
  32. const CHARSET_ISO88591 = 'iso-8859-1';
  33. const CHARSET_UTF8 = 'utf-8';
  34. const CONTENT_TYPE_PLAINTEXT = 'text/plain';
  35. const CONTENT_TYPE_TEXT_CALENDAR = 'text/calendar';
  36. const CONTENT_TYPE_TEXT_HTML = 'text/html';
  37. const CONTENT_TYPE_MULTIPART_ALTERNATIVE = 'multipart/alternative';
  38. const CONTENT_TYPE_MULTIPART_MIXED = 'multipart/mixed';
  39. const CONTENT_TYPE_MULTIPART_RELATED = 'multipart/related';
  40. const ENCODING_7BIT = '7bit';
  41. const ENCODING_8BIT = '8bit';
  42. const ENCODING_BASE64 = 'base64';
  43. const ENCODING_BINARY = 'binary';
  44. const ENCODING_QUOTED_PRINTABLE = 'quoted-printable';
  45. const ENCRYPTION_STARTTLS = 'tls';
  46. const ENCRYPTION_SMTPS = 'ssl';
  47. const ICAL_METHOD_REQUEST = 'REQUEST';
  48. const ICAL_METHOD_PUBLISH = 'PUBLISH';
  49. const ICAL_METHOD_REPLY = 'REPLY';
  50. const ICAL_METHOD_ADD = 'ADD';
  51. const ICAL_METHOD_CANCEL = 'CANCEL';
  52. const ICAL_METHOD_REFRESH = 'REFRESH';
  53. const ICAL_METHOD_COUNTER = 'COUNTER';
  54. const ICAL_METHOD_DECLINECOUNTER = 'DECLINECOUNTER';
  55. /**
  56. * Email priority.
  57. * Options: null (default), 1 = High, 3 = Normal, 5 = low.
  58. * When null, the header is not set at all.
  59. *
  60. * @var int|null
  61. */
  62. public $Priority;
  63. /**
  64. * The character set of the message.
  65. *
  66. * @var string
  67. */
  68. public $CharSet = self::CHARSET_ISO88591;
  69. /**
  70. * The MIME Content-type of the message.
  71. *
  72. * @var string
  73. */
  74. public $ContentType = self::CONTENT_TYPE_PLAINTEXT;
  75. /**
  76. * The message encoding.
  77. * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable".
  78. *
  79. * @var string
  80. */
  81. public $Encoding = self::ENCODING_8BIT;
  82. /**
  83. * Holds the most recent mailer error message.
  84. *
  85. * @var string
  86. */
  87. public $ErrorInfo = '';
  88. /**
  89. * The From email address for the message.
  90. *
  91. * @var string
  92. */
  93. public $From = '';
  94. /**
  95. * The From name of the message.
  96. *
  97. * @var string
  98. */
  99. public $FromName = '';
  100. /**
  101. * The envelope sender of the message.
  102. * This will usually be turned into a Return-Path header by the receiver,
  103. * and is the address that bounces will be sent to.
  104. * If not empty, will be passed via `-f` to sendmail or as the 'MAIL FROM' value over SMTP.
  105. *
  106. * @var string
  107. */
  108. public $Sender = '';
  109. /**
  110. * The Subject of the message.
  111. *
  112. * @var string
  113. */
  114. public $Subject = '';
  115. /**
  116. * An HTML or plain text message body.
  117. * If HTML then call isHTML(true).
  118. *
  119. * @var string
  120. */
  121. public $Body = '';
  122. /**
  123. * The plain-text message body.
  124. * This body can be read by mail clients that do not have HTML email
  125. * capability such as mutt & Eudora.
  126. * Clients that can read HTML will view the normal Body.
  127. *
  128. * @var string
  129. */
  130. public $AltBody = '';
  131. /**
  132. * An iCal message part body.
  133. * Only supported in simple alt or alt_inline message types
  134. * To generate iCal event structures, use classes like EasyPeasyICS or iCalcreator.
  135. *
  136. * @see http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/
  137. * @see http://kigkonsult.se/iCalcreator/
  138. *
  139. * @var string
  140. */
  141. public $Ical = '';
  142. /**
  143. * Value-array of "method" in Contenttype header "text/calendar"
  144. *
  145. * @var string[]
  146. */
  147. protected static $IcalMethods = [
  148. self::ICAL_METHOD_REQUEST,
  149. self::ICAL_METHOD_PUBLISH,
  150. self::ICAL_METHOD_REPLY,
  151. self::ICAL_METHOD_ADD,
  152. self::ICAL_METHOD_CANCEL,
  153. self::ICAL_METHOD_REFRESH,
  154. self::ICAL_METHOD_COUNTER,
  155. self::ICAL_METHOD_DECLINECOUNTER,
  156. ];
  157. /**
  158. * The complete compiled MIME message body.
  159. *
  160. * @var string
  161. */
  162. protected $MIMEBody = '';
  163. /**
  164. * The complete compiled MIME message headers.
  165. *
  166. * @var string
  167. */
  168. protected $MIMEHeader = '';
  169. /**
  170. * Extra headers that createHeader() doesn't fold in.
  171. *
  172. * @var string
  173. */
  174. protected $mailHeader = '';
  175. /**
  176. * Word-wrap the message body to this number of chars.
  177. * Set to 0 to not wrap. A useful value here is 78, for RFC2822 section 2.1.1 compliance.
  178. *
  179. * @see static::STD_LINE_LENGTH
  180. *
  181. * @var int
  182. */
  183. public $WordWrap = 0;
  184. /**
  185. * Which method to use to send mail.
  186. * Options: "mail", "sendmail", or "smtp".
  187. *
  188. * @var string
  189. */
  190. public $Mailer = 'mail';
  191. /**
  192. * The path to the sendmail program.
  193. *
  194. * @var string
  195. */
  196. public $Sendmail = '/usr/sbin/sendmail';
  197. /**
  198. * Whether mail() uses a fully sendmail-compatible MTA.
  199. * One which supports sendmail's "-oi -f" options.
  200. *
  201. * @var bool
  202. */
  203. public $UseSendmailOptions = true;
  204. /**
  205. * The email address that a reading confirmation should be sent to, also known as read receipt.
  206. *
  207. * @var string
  208. */
  209. public $ConfirmReadingTo = '';
  210. /**
  211. * The hostname to use in the Message-ID header and as default HELO string.
  212. * If empty, PHPMailer attempts to find one with, in order,
  213. * $_SERVER['SERVER_NAME'], gethostname(), php_uname('n'), or the value
  214. * 'localhost.localdomain'.
  215. *
  216. * @see PHPMailer::$Helo
  217. *
  218. * @var string
  219. */
  220. public $Hostname = '';
  221. /**
  222. * An ID to be used in the Message-ID header.
  223. * If empty, a unique id will be generated.
  224. * You can set your own, but it must be in the format "<id@domain>",
  225. * as defined in RFC5322 section 3.6.4 or it will be ignored.
  226. *
  227. * @see https://tools.ietf.org/html/rfc5322#section-3.6.4
  228. *
  229. * @var string
  230. */
  231. public $MessageID = '';
  232. /**
  233. * The message Date to be used in the Date header.
  234. * If empty, the current date will be added.
  235. *
  236. * @var string
  237. */
  238. public $MessageDate = '';
  239. /**
  240. * SMTP hosts.
  241. * Either a single hostname or multiple semicolon-delimited hostnames.
  242. * You can also specify a different port
  243. * for each host by using this format: [hostname:port]
  244. * (e.g. "smtp1.example.com:25;smtp2.example.com").
  245. * You can also specify encryption type, for example:
  246. * (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465").
  247. * Hosts will be tried in order.
  248. *
  249. * @var string
  250. */
  251. public $Host = 'localhost';
  252. /**
  253. * The default SMTP server port.
  254. *
  255. * @var int
  256. */
  257. public $Port = 25;
  258. /**
  259. * The SMTP HELO/EHLO name used for the SMTP connection.
  260. * Default is $Hostname. If $Hostname is empty, PHPMailer attempts to find
  261. * one with the same method described above for $Hostname.
  262. *
  263. * @see PHPMailer::$Hostname
  264. *
  265. * @var string
  266. */
  267. public $Helo = '';
  268. /**
  269. * What kind of encryption to use on the SMTP connection.
  270. * Options: '', static::ENCRYPTION_STARTTLS, or static::ENCRYPTION_SMTPS.
  271. *
  272. * @var string
  273. */
  274. public $SMTPSecure = '';
  275. /**
  276. * Whether to enable TLS encryption automatically if a server supports it,
  277. * even if `SMTPSecure` is not set to 'tls'.
  278. * Be aware that in PHP >= 5.6 this requires that the server's certificates are valid.
  279. *
  280. * @var bool
  281. */
  282. public $SMTPAutoTLS = true;
  283. /**
  284. * Whether to use SMTP authentication.
  285. * Uses the Username and Password properties.
  286. *
  287. * @see PHPMailer::$Username
  288. * @see PHPMailer::$Password
  289. *
  290. * @var bool
  291. */
  292. public $SMTPAuth = false;
  293. /**
  294. * Options array passed to stream_context_create when connecting via SMTP.
  295. *
  296. * @var array
  297. */
  298. public $SMTPOptions = [];
  299. /**
  300. * SMTP username.
  301. *
  302. * @var string
  303. */
  304. public $Username = '';
  305. /**
  306. * SMTP password.
  307. *
  308. * @var string
  309. */
  310. public $Password = '';
  311. /**
  312. * SMTP authentication type. Options are CRAM-MD5, LOGIN, PLAIN, XOAUTH2.
  313. * If not specified, the first one from that list that the server supports will be selected.
  314. *
  315. * @var string
  316. */
  317. public $AuthType = '';
  318. /**
  319. * An implementation of the PHPMailer OAuthTokenProvider interface.
  320. *
  321. * @var OAuthTokenProvider
  322. */
  323. protected $oauth;
  324. /**
  325. * The SMTP server timeout in seconds.
  326. * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2.
  327. *
  328. * @var int
  329. */
  330. public $Timeout = 300;
  331. /**
  332. * Comma separated list of DSN notifications
  333. * 'NEVER' under no circumstances a DSN must be returned to the sender.
  334. * If you use NEVER all other notifications will be ignored.
  335. * 'SUCCESS' will notify you when your mail has arrived at its destination.
  336. * 'FAILURE' will arrive if an error occurred during delivery.
  337. * 'DELAY' will notify you if there is an unusual delay in delivery, but the actual
  338. * delivery's outcome (success or failure) is not yet decided.
  339. *
  340. * @see https://tools.ietf.org/html/rfc3461 See section 4.1 for more information about NOTIFY
  341. */
  342. public $dsn = '';
  343. /**
  344. * SMTP class debug output mode.
  345. * Debug output level.
  346. * Options:
  347. * @see SMTP::DEBUG_OFF: No output
  348. * @see SMTP::DEBUG_CLIENT: Client messages
  349. * @see SMTP::DEBUG_SERVER: Client and server messages
  350. * @see SMTP::DEBUG_CONNECTION: As SERVER plus connection status
  351. * @see SMTP::DEBUG_LOWLEVEL: Noisy, low-level data output, rarely needed
  352. *
  353. * @see SMTP::$do_debug
  354. *
  355. * @var int
  356. */
  357. public $SMTPDebug = 0;
  358. /**
  359. * How to handle debug output.
  360. * Options:
  361. * * `echo` Output plain-text as-is, appropriate for CLI
  362. * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output
  363. * * `error_log` Output to error log as configured in php.ini
  364. * By default PHPMailer will use `echo` if run from a `cli` or `cli-server` SAPI, `html` otherwise.
  365. * Alternatively, you can provide a callable expecting two params: a message string and the debug level:
  366. *
  367. * ```php
  368. * $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
  369. * ```
  370. *
  371. * Alternatively, you can pass in an instance of a PSR-3 compatible logger, though only `debug`
  372. * level output is used:
  373. *
  374. * ```php
  375. * $mail->Debugoutput = new myPsr3Logger;
  376. * ```
  377. *
  378. * @see SMTP::$Debugoutput
  379. *
  380. * @var string|callable|\Psr\Log\LoggerInterface
  381. */
  382. public $Debugoutput = 'echo';
  383. /**
  384. * Whether to keep the SMTP connection open after each message.
  385. * If this is set to true then the connection will remain open after a send,
  386. * and closing the connection will require an explicit call to smtpClose().
  387. * It's a good idea to use this if you are sending multiple messages as it reduces overhead.
  388. * See the mailing list example for how to use it.
  389. *
  390. * @var bool
  391. */
  392. public $SMTPKeepAlive = false;
  393. /**
  394. * Whether to split multiple to addresses into multiple messages
  395. * or send them all in one message.
  396. * Only supported in `mail` and `sendmail` transports, not in SMTP.
  397. *
  398. * @var bool
  399. *
  400. * @deprecated 6.0.0 PHPMailer isn't a mailing list manager!
  401. */
  402. public $SingleTo = false;
  403. /**
  404. * Storage for addresses when SingleTo is enabled.
  405. *
  406. * @var array
  407. */
  408. protected $SingleToArray = [];
  409. /**
  410. * Whether to generate VERP addresses on send.
  411. * Only applicable when sending via SMTP.
  412. *
  413. * @see https://en.wikipedia.org/wiki/Variable_envelope_return_path
  414. * @see http://www.postfix.org/VERP_README.html Postfix VERP info
  415. *
  416. * @var bool
  417. */
  418. public $do_verp = false;
  419. /**
  420. * Whether to allow sending messages with an empty body.
  421. *
  422. * @var bool
  423. */
  424. public $AllowEmpty = false;
  425. /**
  426. * DKIM selector.
  427. *
  428. * @var string
  429. */
  430. public $DKIM_selector = '';
  431. /**
  432. * DKIM Identity.
  433. * Usually the email address used as the source of the email.
  434. *
  435. * @var string
  436. */
  437. public $DKIM_identity = '';
  438. /**
  439. * DKIM passphrase.
  440. * Used if your key is encrypted.
  441. *
  442. * @var string
  443. */
  444. public $DKIM_passphrase = '';
  445. /**
  446. * DKIM signing domain name.
  447. *
  448. * @example 'example.com'
  449. *
  450. * @var string
  451. */
  452. public $DKIM_domain = '';
  453. /**
  454. * DKIM Copy header field values for diagnostic use.
  455. *
  456. * @var bool
  457. */
  458. public $DKIM_copyHeaderFields = true;
  459. /**
  460. * DKIM Extra signing headers.
  461. *
  462. * @example ['List-Unsubscribe', 'List-Help']
  463. *
  464. * @var array
  465. */
  466. public $DKIM_extraHeaders = [];
  467. /**
  468. * DKIM private key file path.
  469. *
  470. * @var string
  471. */
  472. public $DKIM_private = '';
  473. /**
  474. * DKIM private key string.
  475. *
  476. * If set, takes precedence over `$DKIM_private`.
  477. *
  478. * @var string
  479. */
  480. public $DKIM_private_string = '';
  481. /**
  482. * Callback Action function name.
  483. *
  484. * The function that handles the result of the send email action.
  485. * It is called out by send() for each email sent.
  486. *
  487. * Value can be any php callable: http://www.php.net/is_callable
  488. *
  489. * Parameters:
  490. * bool $result result of the send action
  491. * array $to email addresses of the recipients
  492. * array $cc cc email addresses
  493. * array $bcc bcc email addresses
  494. * string $subject the subject
  495. * string $body the email body
  496. * string $from email address of sender
  497. * string $extra extra information of possible use
  498. * "smtp_transaction_id' => last smtp transaction id
  499. *
  500. * @var string
  501. */
  502. public $action_function = '';
  503. /**
  504. * What to put in the X-Mailer header.
  505. * Options: An empty string for PHPMailer default, whitespace/null for none, or a string to use.
  506. *
  507. * @var string|null
  508. */
  509. public $XMailer = '';
  510. /**
  511. * Which validator to use by default when validating email addresses.
  512. * May be a callable to inject your own validator, but there are several built-in validators.
  513. * The default validator uses PHP's FILTER_VALIDATE_EMAIL filter_var option.
  514. *
  515. * @see PHPMailer::validateAddress()
  516. *
  517. * @var string|callable
  518. */
  519. public static $validator = 'php';
  520. /**
  521. * An instance of the SMTP sender class.
  522. *
  523. * @var SMTP
  524. */
  525. protected $smtp;
  526. /**
  527. * The array of 'to' names and addresses.
  528. *
  529. * @var array
  530. */
  531. protected $to = [];
  532. /**
  533. * The array of 'cc' names and addresses.
  534. *
  535. * @var array
  536. */
  537. protected $cc = [];
  538. /**
  539. * The array of 'bcc' names and addresses.
  540. *
  541. * @var array
  542. */
  543. protected $bcc = [];
  544. /**
  545. * The array of reply-to names and addresses.
  546. *
  547. * @var array
  548. */
  549. protected $ReplyTo = [];
  550. /**
  551. * An array of all kinds of addresses.
  552. * Includes all of $to, $cc, $bcc.
  553. *
  554. * @see PHPMailer::$to
  555. * @see PHPMailer::$cc
  556. * @see PHPMailer::$bcc
  557. *
  558. * @var array
  559. */
  560. protected $all_recipients = [];
  561. /**
  562. * An array of names and addresses queued for validation.
  563. * In send(), valid and non duplicate entries are moved to $all_recipients
  564. * and one of $to, $cc, or $bcc.
  565. * This array is used only for addresses with IDN.
  566. *
  567. * @see PHPMailer::$to
  568. * @see PHPMailer::$cc
  569. * @see PHPMailer::$bcc
  570. * @see PHPMailer::$all_recipients
  571. *
  572. * @var array
  573. */
  574. protected $RecipientsQueue = [];
  575. /**
  576. * An array of reply-to names and addresses queued for validation.
  577. * In send(), valid and non duplicate entries are moved to $ReplyTo.
  578. * This array is used only for addresses with IDN.
  579. *
  580. * @see PHPMailer::$ReplyTo
  581. *
  582. * @var array
  583. */
  584. protected $ReplyToQueue = [];
  585. /**
  586. * The array of attachments.
  587. *
  588. * @var array
  589. */
  590. protected $attachment = [];
  591. /**
  592. * The array of custom headers.
  593. *
  594. * @var array
  595. */
  596. protected $CustomHeader = [];
  597. /**
  598. * The most recent Message-ID (including angular brackets).
  599. *
  600. * @var string
  601. */
  602. protected $lastMessageID = '';
  603. /**
  604. * The message's MIME type.
  605. *
  606. * @var string
  607. */
  608. protected $message_type = '';
  609. /**
  610. * The array of MIME boundary strings.
  611. *
  612. * @var array
  613. */
  614. protected $boundary = [];
  615. /**
  616. * The array of available text strings for the current language.
  617. *
  618. * @var array
  619. */
  620. protected $language = [];
  621. /**
  622. * The number of errors encountered.
  623. *
  624. * @var int
  625. */
  626. protected $error_count = 0;
  627. /**
  628. * The S/MIME certificate file path.
  629. *
  630. * @var string
  631. */
  632. protected $sign_cert_file = '';
  633. /**
  634. * The S/MIME key file path.
  635. *
  636. * @var string
  637. */
  638. protected $sign_key_file = '';
  639. /**
  640. * The optional S/MIME extra certificates ("CA Chain") file path.
  641. *
  642. * @var string
  643. */
  644. protected $sign_extracerts_file = '';
  645. /**
  646. * The S/MIME password for the key.
  647. * Used only if the key is encrypted.
  648. *
  649. * @var string
  650. */
  651. protected $sign_key_pass = '';
  652. /**
  653. * Whether to throw exceptions for errors.
  654. *
  655. * @var bool
  656. */
  657. protected $exceptions = false;
  658. /**
  659. * Unique ID used for message ID and boundaries.
  660. *
  661. * @var string
  662. */
  663. protected $uniqueid = '';
  664. /**
  665. * The PHPMailer Version number.
  666. *
  667. * @var string
  668. */
  669. const VERSION = '6.7.1';
  670. /**
  671. * Error severity: message only, continue processing.
  672. *
  673. * @var int
  674. */
  675. const STOP_MESSAGE = 0;
  676. /**
  677. * Error severity: message, likely ok to continue processing.
  678. *
  679. * @var int
  680. */
  681. const STOP_CONTINUE = 1;
  682. /**
  683. * Error severity: message, plus full stop, critical error reached.
  684. *
  685. * @var int
  686. */
  687. const STOP_CRITICAL = 2;
  688. /**
  689. * The SMTP standard CRLF line break.
  690. * If you want to change line break format, change static::$LE, not this.
  691. */
  692. const CRLF = "\r\n";
  693. /**
  694. * "Folding White Space" a white space string used for line folding.
  695. */
  696. const FWS = ' ';
  697. /**
  698. * SMTP RFC standard line ending; Carriage Return, Line Feed.
  699. *
  700. * @var string
  701. */
  702. protected static $LE = self::CRLF;
  703. /**
  704. * The maximum line length supported by mail().
  705. *
  706. * Background: mail() will sometimes corrupt messages
  707. * with headers headers longer than 65 chars, see #818.
  708. *
  709. * @var int
  710. */
  711. const MAIL_MAX_LINE_LENGTH = 63;
  712. /**
  713. * The maximum line length allowed by RFC 2822 section 2.1.1.
  714. *
  715. * @var int
  716. */
  717. const MAX_LINE_LENGTH = 998;
  718. /**
  719. * The lower maximum line length allowed by RFC 2822 section 2.1.1.
  720. * This length does NOT include the line break
  721. * 76 means that lines will be 77 or 78 chars depending on whether
  722. * the line break format is LF or CRLF; both are valid.
  723. *
  724. * @var int
  725. */
  726. const STD_LINE_LENGTH = 76;
  727. /**
  728. * Constructor.
  729. *
  730. * @param bool $exceptions Should we throw external exceptions?
  731. */
  732. public function __construct($exceptions = null)
  733. {
  734. if (null !== $exceptions) {
  735. $this->exceptions = (bool) $exceptions;
  736. }
  737. //Pick an appropriate debug output format automatically
  738. $this->Debugoutput = (strpos(PHP_SAPI, 'cli') !== false ? 'echo' : 'html');
  739. }
  740. /**
  741. * Destructor.
  742. */
  743. public function __destruct()
  744. {
  745. //Close any open SMTP connection nicely
  746. $this->smtpClose();
  747. }
  748. /**
  749. * Call mail() in a safe_mode-aware fashion.
  750. * Also, unless sendmail_path points to sendmail (or something that
  751. * claims to be sendmail), don't pass params (not a perfect fix,
  752. * but it will do).
  753. *
  754. * @param string $to To
  755. * @param string $subject Subject
  756. * @param string $body Message Body
  757. * @param string $header Additional Header(s)
  758. * @param string|null $params Params
  759. *
  760. * @return bool
  761. */
  762. private function mailPassthru($to, $subject, $body, $header, $params)
  763. {
  764. //Check overloading of mail function to avoid double-encoding
  765. if ((int)ini_get('mbstring.func_overload') & 1) {
  766. $subject = $this->secureHeader($subject);
  767. } else {
  768. $subject = $this->encodeHeader($this->secureHeader($subject));
  769. }
  770. //Calling mail() with null params breaks
  771. $this->edebug('Sending with mail()');
  772. $this->edebug('Sendmail path: ' . ini_get('sendmail_path'));
  773. $this->edebug("Envelope sender: {$this->Sender}");
  774. $this->edebug("To: {$to}");
  775. $this->edebug("Subject: {$subject}");
  776. $this->edebug("Headers: {$header}");
  777. if (!$this->UseSendmailOptions || null === $params) {
  778. $result = @mail($to, $subject, $body, $header);
  779. } else {
  780. $this->edebug("Additional params: {$params}");
  781. $result = @mail($to, $subject, $body, $header, $params);
  782. }
  783. $this->edebug('Result: ' . ($result ? 'true' : 'false'));
  784. return $result;
  785. }
  786. /**
  787. * Output debugging info via a user-defined method.
  788. * Only generates output if debug output is enabled.
  789. *
  790. * @see PHPMailer::$Debugoutput
  791. * @see PHPMailer::$SMTPDebug
  792. *
  793. * @param string $str
  794. */
  795. protected function edebug($str)
  796. {
  797. if ($this->SMTPDebug <= 0) {
  798. return;
  799. }
  800. //Is this a PSR-3 logger?
  801. if ($this->Debugoutput instanceof \Psr\Log\LoggerInterface) {
  802. $this->Debugoutput->debug($str);
  803. return;
  804. }
  805. //Avoid clash with built-in function names
  806. if (is_callable($this->Debugoutput) && !in_array($this->Debugoutput, ['error_log', 'html', 'echo'])) {
  807. call_user_func($this->Debugoutput, $str, $this->SMTPDebug);
  808. return;
  809. }
  810. switch ($this->Debugoutput) {
  811. case 'error_log':
  812. //Don't output, just log
  813. /** @noinspection ForgottenDebugOutputInspection */
  814. error_log($str);
  815. break;
  816. case 'html':
  817. //Cleans up output a bit for a better looking, HTML-safe output
  818. echo htmlentities(
  819. preg_replace('/[\r\n]+/', '', $str),
  820. ENT_QUOTES,
  821. 'UTF-8'
  822. ), "<br>\n";
  823. break;
  824. case 'echo':
  825. default:
  826. //Normalize line breaks
  827. $str = preg_replace('/\r\n|\r/m', "\n", $str);
  828. echo gmdate('Y-m-d H:i:s'),
  829. "\t",
  830. //Trim trailing space
  831. trim(
  832. //Indent for readability, except for trailing break
  833. str_replace(
  834. "\n",
  835. "\n \t ",
  836. trim($str)
  837. )
  838. ),
  839. "\n";
  840. }
  841. }
  842. /**
  843. * Sets message type to HTML or plain.
  844. *
  845. * @param bool $isHtml True for HTML mode
  846. */
  847. public function isHTML($isHtml = true)
  848. {
  849. if ($isHtml) {
  850. $this->ContentType = static::CONTENT_TYPE_TEXT_HTML;
  851. } else {
  852. $this->ContentType = static::CONTENT_TYPE_PLAINTEXT;
  853. }
  854. }
  855. /**
  856. * Send messages using SMTP.
  857. */
  858. public function isSMTP()
  859. {
  860. $this->Mailer = 'smtp';
  861. }
  862. /**
  863. * Send messages using PHP's mail() function.
  864. */
  865. public function isMail()
  866. {
  867. $this->Mailer = 'mail';
  868. }
  869. /**
  870. * Send messages using $Sendmail.
  871. */
  872. public function isSendmail()
  873. {
  874. $ini_sendmail_path = ini_get('sendmail_path');
  875. if (false === stripos($ini_sendmail_path, 'sendmail')) {
  876. $this->Sendmail = '/usr/sbin/sendmail';
  877. } else {
  878. $this->Sendmail = $ini_sendmail_path;
  879. }
  880. $this->Mailer = 'sendmail';
  881. }
  882. /**
  883. * Send messages using qmail.
  884. */
  885. public function isQmail()
  886. {
  887. $ini_sendmail_path = ini_get('sendmail_path');
  888. if (false === stripos($ini_sendmail_path, 'qmail')) {
  889. $this->Sendmail = '/var/qmail/bin/qmail-inject';
  890. } else {
  891. $this->Sendmail = $ini_sendmail_path;
  892. }
  893. $this->Mailer = 'qmail';
  894. }
  895. /**
  896. * Add a "To" address.
  897. *
  898. * @param string $address The email address to send to
  899. * @param string $name
  900. *
  901. * @throws Exception
  902. *
  903. * @return bool true on success, false if address already used or invalid in some way
  904. */
  905. public function addAddress($address, $name = '')
  906. {
  907. return $this->addOrEnqueueAnAddress('to', $address, $name);
  908. }
  909. /**
  910. * Add a "CC" address.
  911. *
  912. * @param string $address The email address to send to
  913. * @param string $name
  914. *
  915. * @throws Exception
  916. *
  917. * @return bool true on success, false if address already used or invalid in some way
  918. */
  919. public function addCC($address, $name = '')
  920. {
  921. return $this->addOrEnqueueAnAddress('cc', $address, $name);
  922. }
  923. /**
  924. * Add a "BCC" address.
  925. *
  926. * @param string $address The email address to send to
  927. * @param string $name
  928. *
  929. * @throws Exception
  930. *
  931. * @return bool true on success, false if address already used or invalid in some way
  932. */
  933. public function addBCC($address, $name = '')
  934. {
  935. return $this->addOrEnqueueAnAddress('bcc', $address, $name);
  936. }
  937. /**
  938. * Add a "Reply-To" address.
  939. *
  940. * @param string $address The email address to reply to
  941. * @param string $name
  942. *
  943. * @throws Exception
  944. *
  945. * @return bool true on success, false if address already used or invalid in some way
  946. */
  947. public function addReplyTo($address, $name = '')
  948. {
  949. return $this->addOrEnqueueAnAddress('Reply-To', $address, $name);
  950. }
  951. /**
  952. * Add an address to one of the recipient arrays or to the ReplyTo array. Because PHPMailer
  953. * can't validate addresses with an IDN without knowing the PHPMailer::$CharSet (that can still
  954. * be modified after calling this function), addition of such addresses is delayed until send().
  955. * Addresses that have been added already return false, but do not throw exceptions.
  956. *
  957. * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo'
  958. * @param string $address The email address
  959. * @param string $name An optional username associated with the address
  960. *
  961. * @throws Exception
  962. *
  963. * @return bool true on success, false if address already used or invalid in some way
  964. */
  965. protected function addOrEnqueueAnAddress($kind, $address, $name)
  966. {
  967. $pos = false;
  968. if ($address !== null) {
  969. $address = trim($address);
  970. $pos = strrpos($address, '@');
  971. }
  972. if (false === $pos) {
  973. //At-sign is missing.
  974. $error_message = sprintf(
  975. '%s (%s): %s',
  976. $this->lang('invalid_address'),
  977. $kind,
  978. $address
  979. );
  980. $this->setError($error_message);
  981. $this->edebug($error_message);
  982. if ($this->exceptions) {
  983. throw new Exception($error_message);
  984. }
  985. return false;
  986. }
  987. if ($name !== null && is_string($name)) {
  988. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  989. } else {
  990. $name = '';
  991. }
  992. $params = [$kind, $address, $name];
  993. //Enqueue addresses with IDN until we know the PHPMailer::$CharSet.
  994. //Domain is assumed to be whatever is after the last @ symbol in the address
  995. if (static::idnSupported() && $this->has8bitChars(substr($address, ++$pos))) {
  996. if ('Reply-To' !== $kind) {
  997. if (!array_key_exists($address, $this->RecipientsQueue)) {
  998. $this->RecipientsQueue[$address] = $params;
  999. return true;
  1000. }
  1001. } elseif (!array_key_exists($address, $this->ReplyToQueue)) {
  1002. $this->ReplyToQueue[$address] = $params;
  1003. return true;
  1004. }
  1005. return false;
  1006. }
  1007. //Immediately add standard addresses without IDN.
  1008. return call_user_func_array([$this, 'addAnAddress'], $params);
  1009. }
  1010. /**
  1011. * Set the boundaries to use for delimiting MIME parts.
  1012. * If you override this, ensure you set all 3 boundaries to unique values.
  1013. * The default boundaries include a "=_" sequence which cannot occur in quoted-printable bodies,
  1014. * as suggested by https://www.rfc-editor.org/rfc/rfc2045#section-6.7
  1015. *
  1016. * @return void
  1017. */
  1018. public function setBoundaries()
  1019. {
  1020. $this->uniqueid = $this->generateId();
  1021. $this->boundary[1] = 'b1=_' . $this->uniqueid;
  1022. $this->boundary[2] = 'b2=_' . $this->uniqueid;
  1023. $this->boundary[3] = 'b3=_' . $this->uniqueid;
  1024. }
  1025. /**
  1026. * Add an address to one of the recipient arrays or to the ReplyTo array.
  1027. * Addresses that have been added already return false, but do not throw exceptions.
  1028. *
  1029. * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo'
  1030. * @param string $address The email address to send, resp. to reply to
  1031. * @param string $name
  1032. *
  1033. * @throws Exception
  1034. *
  1035. * @return bool true on success, false if address already used or invalid in some way
  1036. */
  1037. protected function addAnAddress($kind, $address, $name = '')
  1038. {
  1039. if (!in_array($kind, ['to', 'cc', 'bcc', 'Reply-To'])) {
  1040. $error_message = sprintf(
  1041. '%s: %s',
  1042. $this->lang('Invalid recipient kind'),
  1043. $kind
  1044. );
  1045. $this->setError($error_message);
  1046. $this->edebug($error_message);
  1047. if ($this->exceptions) {
  1048. throw new Exception($error_message);
  1049. }
  1050. return false;
  1051. }
  1052. if (!static::validateAddress($address)) {
  1053. $error_message = sprintf(
  1054. '%s (%s): %s',
  1055. $this->lang('invalid_address'),
  1056. $kind,
  1057. $address
  1058. );
  1059. $this->setError($error_message);
  1060. $this->edebug($error_message);
  1061. if ($this->exceptions) {
  1062. throw new Exception($error_message);
  1063. }
  1064. return false;
  1065. }
  1066. if ('Reply-To' !== $kind) {
  1067. if (!array_key_exists(strtolower($address), $this->all_recipients)) {
  1068. $this->{$kind}[] = [$address, $name];
  1069. $this->all_recipients[strtolower($address)] = true;
  1070. return true;
  1071. }
  1072. } elseif (!array_key_exists(strtolower($address), $this->ReplyTo)) {
  1073. $this->ReplyTo[strtolower($address)] = [$address, $name];
  1074. return true;
  1075. }
  1076. return false;
  1077. }
  1078. /**
  1079. * Parse and validate a string containing one or more RFC822-style comma-separated email addresses
  1080. * of the form "display name <address>" into an array of name/address pairs.
  1081. * Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available.
  1082. * Note that quotes in the name part are removed.
  1083. *
  1084. * @see http://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation
  1085. *
  1086. * @param string $addrstr The address list string
  1087. * @param bool $useimap Whether to use the IMAP extension to parse the list
  1088. * @param string $charset The charset to use when decoding the address list string.
  1089. *
  1090. * @return array
  1091. */
  1092. public static function parseAddresses($addrstr, $useimap = true, $charset = self::CHARSET_ISO88591)
  1093. {
  1094. $addresses = [];
  1095. if ($useimap && function_exists('imap_rfc822_parse_adrlist')) {
  1096. //Use this built-in parser if it's available
  1097. $list = imap_rfc822_parse_adrlist($addrstr, '');
  1098. // Clear any potential IMAP errors to get rid of notices being thrown at end of script.
  1099. imap_errors();
  1100. foreach ($list as $address) {
  1101. if (
  1102. '.SYNTAX-ERROR.' !== $address->host &&
  1103. static::validateAddress($address->mailbox . '@' . $address->host)
  1104. ) {
  1105. //Decode the name part if it's present and encoded
  1106. if (
  1107. property_exists($address, 'personal') &&
  1108. //Check for a Mbstring constant rather than using extension_loaded, which is sometimes disabled
  1109. defined('MB_CASE_UPPER') &&
  1110. preg_match('/^=\?.*\?=$/s', $address->personal)
  1111. ) {
  1112. $origCharset = mb_internal_encoding();
  1113. mb_internal_encoding($charset);
  1114. //Undo any RFC2047-encoded spaces-as-underscores
  1115. $address->personal = str_replace('_', '=20', $address->personal);
  1116. //Decode the name
  1117. $address->personal = mb_decode_mimeheader($address->personal);
  1118. mb_internal_encoding($origCharset);
  1119. }
  1120. $addresses[] = [
  1121. 'name' => (property_exists($address, 'personal') ? $address->personal : ''),
  1122. 'address' => $address->mailbox . '@' . $address->host,
  1123. ];
  1124. }
  1125. }
  1126. } else {
  1127. //Use this simpler parser
  1128. $list = explode(',', $addrstr);
  1129. foreach ($list as $address) {
  1130. $address = trim($address);
  1131. //Is there a separate name part?
  1132. if (strpos($address, '<') === false) {
  1133. //No separate name, just use the whole thing
  1134. if (static::validateAddress($address)) {
  1135. $addresses[] = [
  1136. 'name' => '',
  1137. 'address' => $address,
  1138. ];
  1139. }
  1140. } else {
  1141. list($name, $email) = explode('<', $address);
  1142. $email = trim(str_replace('>', '', $email));
  1143. $name = trim($name);
  1144. if (static::validateAddress($email)) {
  1145. //Check for a Mbstring constant rather than using extension_loaded, which is sometimes disabled
  1146. //If this name is encoded, decode it
  1147. if (defined('MB_CASE_UPPER') && preg_match('/^=\?.*\?=$/s', $name)) {
  1148. $origCharset = mb_internal_encoding();
  1149. mb_internal_encoding($charset);
  1150. //Undo any RFC2047-encoded spaces-as-underscores
  1151. $name = str_replace('_', '=20', $name);
  1152. //Decode the name
  1153. $name = mb_decode_mimeheader($name);
  1154. mb_internal_encoding($origCharset);
  1155. }
  1156. $addresses[] = [
  1157. //Remove any surrounding quotes and spaces from the name
  1158. 'name' => trim($name, '\'" '),
  1159. 'address' => $email,
  1160. ];
  1161. }
  1162. }
  1163. }
  1164. }
  1165. return $addresses;
  1166. }
  1167. /**
  1168. * Set the From and FromName properties.
  1169. *
  1170. * @param string $address
  1171. * @param string $name
  1172. * @param bool $auto Whether to also set the Sender address, defaults to true
  1173. *
  1174. * @throws Exception
  1175. *
  1176. * @return bool
  1177. */
  1178. public function setFrom($address, $name = '', $auto = true)
  1179. {
  1180. $address = trim((string)$address);
  1181. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  1182. //Don't validate now addresses with IDN. Will be done in send().
  1183. $pos = strrpos($address, '@');
  1184. if (
  1185. (false === $pos)
  1186. || ((!$this->has8bitChars(substr($address, ++$pos)) || !static::idnSupported())
  1187. && !static::validateAddress($address))
  1188. ) {
  1189. $error_message = sprintf(
  1190. '%s (From): %s',
  1191. $this->lang('invalid_address'),
  1192. $address
  1193. );
  1194. $this->setError($error_message);
  1195. $this->edebug($error_message);
  1196. if ($this->exceptions) {
  1197. throw new Exception($error_message);
  1198. }
  1199. return false;
  1200. }
  1201. $this->From = $address;
  1202. $this->FromName = $name;
  1203. if ($auto && empty($this->Sender)) {
  1204. $this->Sender = $address;
  1205. }
  1206. return true;
  1207. }
  1208. /**
  1209. * Return the Message-ID header of the last email.
  1210. * Technically this is the value from the last time the headers were created,
  1211. * but it's also the message ID of the last sent message except in
  1212. * pathological cases.
  1213. *
  1214. * @return string
  1215. */
  1216. public function getLastMessageID()
  1217. {
  1218. return $this->lastMessageID;
  1219. }
  1220. /**
  1221. * Check that a string looks like an email address.
  1222. * Validation patterns supported:
  1223. * * `auto` Pick best pattern automatically;
  1224. * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0;
  1225. * * `pcre` Use old PCRE implementation;
  1226. * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL;
  1227. * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements.
  1228. * * `noregex` Don't use a regex: super fast, really dumb.
  1229. * Alternatively you may pass in a callable to inject your own validator, for example:
  1230. *
  1231. * ```php
  1232. * PHPMailer::validateAddress('user@example.com', function($address) {
  1233. * return (strpos($address, '@') !== false);
  1234. * });
  1235. * ```
  1236. *
  1237. * You can also set the PHPMailer::$validator static to a callable, allowing built-in methods to use your validator.
  1238. *
  1239. * @param string $address The email address to check
  1240. * @param string|callable $patternselect Which pattern to use
  1241. *
  1242. * @return bool
  1243. */
  1244. public static function validateAddress($address, $patternselect = null)
  1245. {
  1246. if (null === $patternselect) {
  1247. $patternselect = static::$validator;
  1248. }
  1249. //Don't allow strings as callables, see SECURITY.md and CVE-2021-3603
  1250. if (is_callable($patternselect) && !is_string($patternselect)) {
  1251. return call_user_func($patternselect, $address);
  1252. }
  1253. //Reject line breaks in addresses; it's valid RFC5322, but not RFC5321
  1254. if (strpos($address, "\n") !== false || strpos($address, "\r") !== false) {
  1255. return false;
  1256. }
  1257. switch ($patternselect) {
  1258. case 'pcre': //Kept for BC
  1259. case 'pcre8':
  1260. /*
  1261. * A more complex and more permissive version of the RFC5322 regex on which FILTER_VALIDATE_EMAIL
  1262. * is based.
  1263. * In addition to the addresses allowed by filter_var, also permits:
  1264. * * dotless domains: `a@b`
  1265. * * comments: `1234 @ local(blah) .machine .example`
  1266. * * quoted elements: `'"test blah"@example.org'`
  1267. * * numeric TLDs: `a@b.123`
  1268. * * unbracketed IPv4 literals: `a@192.168.0.1`
  1269. * * IPv6 literals: 'first.last@[IPv6:a1::]'
  1270. * Not all of these will necessarily work for sending!
  1271. *
  1272. * @see http://squiloople.com/2009/12/20/email-address-validation/
  1273. * @copyright 2009-2010 Michael Rushton
  1274. * Feel free to use and redistribute this code. But please keep this copyright notice.
  1275. */
  1276. return (bool) preg_match(
  1277. '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' .
  1278. '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' .
  1279. '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' .
  1280. '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' .
  1281. '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' .
  1282. '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' .
  1283. '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' .
  1284. '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
  1285. '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD',
  1286. $address
  1287. );
  1288. case 'html5':
  1289. /*
  1290. * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements.
  1291. *
  1292. * @see https://html.spec.whatwg.org/#e-mail-state-(type=email)
  1293. */
  1294. return (bool) preg_match(
  1295. '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' .
  1296. '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD',
  1297. $address
  1298. );
  1299. case 'php':
  1300. default:
  1301. return filter_var($address, FILTER_VALIDATE_EMAIL) !== false;
  1302. }
  1303. }
  1304. /**
  1305. * Tells whether IDNs (Internationalized Domain Names) are supported or not. This requires the
  1306. * `intl` and `mbstring` PHP extensions.
  1307. *
  1308. * @return bool `true` if required functions for IDN support are present
  1309. */
  1310. public static function idnSupported()
  1311. {
  1312. return function_exists('idn_to_ascii') && function_exists('mb_convert_encoding');
  1313. }
  1314. /**
  1315. * Converts IDN in given email address to its ASCII form, also known as punycode, if possible.
  1316. * Important: Address must be passed in same encoding as currently set in PHPMailer::$CharSet.
  1317. * This function silently returns unmodified address if:
  1318. * - No conversion is necessary (i.e. domain name is not an IDN, or is already in ASCII form)
  1319. * - Conversion to punycode is impossible (e.g. required PHP functions are not available)
  1320. * or fails for any reason (e.g. domain contains characters not allowed in an IDN).
  1321. *
  1322. * @see PHPMailer::$CharSet
  1323. *
  1324. * @param string $address The email address to convert
  1325. *
  1326. * @return string The encoded address in ASCII form
  1327. */
  1328. public function punyencodeAddress($address)
  1329. {
  1330. //Verify we have required functions, CharSet, and at-sign.
  1331. $pos = strrpos($address, '@');
  1332. if (
  1333. !empty($this->CharSet) &&
  1334. false !== $pos &&
  1335. static::idnSupported()
  1336. ) {
  1337. $domain = substr($address, ++$pos);
  1338. //Verify CharSet string is a valid one, and domain properly encoded in this CharSet.
  1339. if ($this->has8bitChars($domain) && @mb_check_encoding($domain, $this->CharSet)) {
  1340. //Convert the domain from whatever charset it's in to UTF-8
  1341. $domain = mb_convert_encoding($domain, self::CHARSET_UTF8, $this->CharSet);
  1342. //Ignore IDE complaints about this line - method signature changed in PHP 5.4
  1343. $errorcode = 0;
  1344. if (defined('INTL_IDNA_VARIANT_UTS46')) {
  1345. //Use the current punycode standard (appeared in PHP 7.2)
  1346. $punycode = idn_to_ascii(
  1347. $domain,
  1348. \IDNA_DEFAULT | \IDNA_USE_STD3_RULES | \IDNA_CHECK_BIDI |
  1349. \IDNA_CHECK_CONTEXTJ | \IDNA_NONTRANSITIONAL_TO_ASCII,
  1350. \INTL_IDNA_VARIANT_UTS46
  1351. );
  1352. } elseif (defined('INTL_IDNA_VARIANT_2003')) {
  1353. //Fall back to this old, deprecated/removed encoding
  1354. $punycode = idn_to_ascii($domain, $errorcode, \INTL_IDNA_VARIANT_2003);
  1355. } else {
  1356. //Fall back to a default we don't know about
  1357. $punycode = idn_to_ascii($domain, $errorcode);
  1358. }
  1359. if (false !== $punycode) {
  1360. return substr($address, 0, $pos) . $punycode;
  1361. }
  1362. }
  1363. }
  1364. return $address;
  1365. }
  1366. /**
  1367. * Create a message and send it.
  1368. * Uses the sending method specified by $Mailer.
  1369. *
  1370. * @throws Exception
  1371. *
  1372. * @return bool false on error - See the ErrorInfo property for details of the error
  1373. */
  1374. public function send()
  1375. {
  1376. try {
  1377. if (!$this->preSend()) {
  1378. return false;
  1379. }
  1380. return $this->postSend();
  1381. } catch (Exception $exc) {
  1382. $this->mailHeader = '';
  1383. $this->setError($exc->getMessage());
  1384. if ($this->exceptions) {
  1385. throw $exc;
  1386. }
  1387. return false;
  1388. }
  1389. }
  1390. /**
  1391. * Prepare a message for sending.
  1392. *
  1393. * @throws Exception
  1394. *
  1395. * @return bool
  1396. */
  1397. public function preSend()
  1398. {
  1399. if (
  1400. 'smtp' === $this->Mailer
  1401. || ('mail' === $this->Mailer && (\PHP_VERSION_ID >= 80000 || stripos(PHP_OS, 'WIN') === 0))
  1402. ) {
  1403. //SMTP mandates RFC-compliant line endings
  1404. //and it's also used with mail() on Windows
  1405. static::setLE(self::CRLF);
  1406. } else {
  1407. //Maintain backward compatibility with legacy Linux command line mailers
  1408. static::setLE(PHP_EOL);
  1409. }
  1410. //Check for buggy PHP versions that add a header with an incorrect line break
  1411. if (
  1412. 'mail' === $this->Mailer
  1413. && ((\PHP_VERSION_ID >= 70000 && \PHP_VERSION_ID < 70017)
  1414. || (\PHP_VERSION_ID >= 70100 && \PHP_VERSION_ID < 70103))
  1415. && ini_get('mail.add_x_header') === '1'
  1416. && stripos(PHP_OS, 'WIN') === 0
  1417. ) {
  1418. trigger_error($this->lang('buggy_php'), E_USER_WARNING);
  1419. }
  1420. try {
  1421. $this->error_count = 0; //Reset errors
  1422. $this->mailHeader = '';
  1423. //Dequeue recipient and Reply-To addresses with IDN
  1424. foreach (array_merge($this->RecipientsQueue, $this->ReplyToQueue) as $params) {
  1425. $params[1] = $this->punyencodeAddress($params[1]);
  1426. call_user_func_array([$this, 'addAnAddress'], $params);
  1427. }
  1428. if (count($this->to) + count($this->cc) + count($this->bcc) < 1) {
  1429. throw new Exception($this->lang('provide_address'), self::STOP_CRITICAL);
  1430. }
  1431. //Validate From, Sender, and ConfirmReadingTo addresses
  1432. foreach (['From', 'Sender', 'ConfirmReadingTo'] as $address_kind) {
  1433. $this->{$address_kind} = trim($this->{$address_kind});
  1434. if (empty($this->{$address_kind})) {
  1435. continue;
  1436. }
  1437. $this->{$address_kind} = $this->punyencodeAddress($this->{$address_kind});
  1438. if (!static::validateAddress($this->{$address_kind})) {
  1439. $error_message = sprintf(
  1440. '%s (%s): %s',
  1441. $this->lang('invalid_address'),
  1442. $address_kind,
  1443. $this->{$address_kind}
  1444. );
  1445. $this->setError($error_message);
  1446. $this->edebug($error_message);
  1447. if ($this->exceptions) {
  1448. throw new Exception($error_message);
  1449. }
  1450. return false;
  1451. }
  1452. }
  1453. //Set whether the message is multipart/alternative
  1454. if ($this->alternativeExists()) {
  1455. $this->ContentType = static::CONTENT_TYPE_MULTIPART_ALTERNATIVE;
  1456. }
  1457. $this->setMessageType();
  1458. //Refuse to send an empty message unless we are specifically allowing it
  1459. if (!$this->AllowEmpty && empty($this->Body)) {
  1460. throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL);
  1461. }
  1462. //Trim subject consistently
  1463. $this->Subject = trim($this->Subject);
  1464. //Create body before headers in case body makes changes to headers (e.g. altering transfer encoding)
  1465. $this->MIMEHeader = '';
  1466. $this->MIMEBody = $this->createBody();
  1467. //createBody may have added some headers, so retain them
  1468. $tempheaders = $this->MIMEHeader;
  1469. $this->MIMEHeader = $this->createHeader();
  1470. $this->MIMEHeader .= $tempheaders;
  1471. //To capture the complete message when using mail(), create
  1472. //an extra header list which createHeader() doesn't fold in
  1473. if ('mail' === $this->Mailer) {
  1474. if (count($this->to) > 0) {
  1475. $this->mailHeader .= $this->addrAppend('To', $this->to);
  1476. } else {
  1477. $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;');
  1478. }
  1479. $this->mailHeader .= $this->headerLine(
  1480. 'Subject',
  1481. $this->encodeHeader($this->secureHeader($this->Subject))
  1482. );
  1483. }
  1484. //Sign with DKIM if enabled
  1485. if (
  1486. !empty($this->DKIM_domain)
  1487. && !empty($this->DKIM_selector)
  1488. && (!empty($this->DKIM_private_string)
  1489. || (!empty($this->DKIM_private)
  1490. && static::isPermittedPath($this->DKIM_private)
  1491. && file_exists($this->DKIM_private)
  1492. )
  1493. )
  1494. ) {
  1495. $header_dkim = $this->DKIM_Add(
  1496. $this->MIMEHeader . $this->mailHeader,
  1497. $this->encodeHeader($this->secureHeader($this->Subject)),
  1498. $this->MIMEBody
  1499. );
  1500. $this->MIMEHeader = static::stripTrailingWSP($this->MIMEHeader) . static::$LE .
  1501. static::normalizeBreaks($header_dkim) . static::$LE;
  1502. }
  1503. return true;
  1504. } catch (Exception $exc) {
  1505. $this->setError($exc->getMessage());
  1506. if ($this->exceptions) {
  1507. throw $exc;
  1508. }
  1509. return false;
  1510. }
  1511. }
  1512. /**
  1513. * Actually send a message via the selected mechanism.
  1514. *
  1515. * @throws Exception
  1516. *
  1517. * @return bool
  1518. */
  1519. public function postSend()
  1520. {
  1521. try {
  1522. //Choose the mailer and send through it
  1523. switch ($this->Mailer) {
  1524. case 'sendmail':
  1525. case 'qmail':
  1526. return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody);
  1527. case 'smtp':
  1528. return $this->smtpSend($this->MIMEHeader, $this->MIMEBody);
  1529. case 'mail':
  1530. return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
  1531. default:
  1532. $sendMethod = $this->Mailer . 'Send';
  1533. if (method_exists($this, $sendMethod)) {
  1534. return $this->{$sendMethod}($this->MIMEHeader, $this->MIMEBody);
  1535. }
  1536. return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
  1537. }
  1538. } catch (Exception $exc) {
  1539. $this->setError($exc->getMessage());
  1540. $this->edebug($exc->getMessage());
  1541. if ($this->Mailer === 'smtp' && $this->SMTPKeepAlive == true && $this->smtp->connected()) {
  1542. $this->smtp->reset();
  1543. }
  1544. if ($this->exceptions) {
  1545. throw $exc;
  1546. }
  1547. }
  1548. return false;
  1549. }
  1550. /**
  1551. * Send mail using the $Sendmail program.
  1552. *
  1553. * @see PHPMailer::$Sendmail
  1554. *
  1555. * @param string $header The message headers
  1556. * @param string $body The message body
  1557. *
  1558. * @throws Exception
  1559. *
  1560. * @return bool
  1561. */
  1562. protected function sendmailSend($header, $body)
  1563. {
  1564. if ($this->Mailer === 'qmail') {
  1565. $this->edebug('Sending with qmail');
  1566. } else {
  1567. $this->edebug('Sending with sendmail');
  1568. }
  1569. $header = static::stripTrailingWSP($header) . static::$LE . static::$LE;
  1570. //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver
  1571. //A space after `-f` is optional, but there is a long history of its presence
  1572. //causing problems, so we don't use one
  1573. //Exim docs: http://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html
  1574. //Sendmail docs: http://www.sendmail.org/~ca/email/man/sendmail.html
  1575. //Qmail docs: http://www.qmail.org/man/man8/qmail-inject.html
  1576. //Example problem: https://www.drupal.org/node/1057954
  1577. //PHP 5.6 workaround
  1578. $sendmail_from_value = ini_get('sendmail_from');
  1579. if (empty($this->Sender) && !empty($sendmail_from_value)) {
  1580. //PHP config has a sender address we can use
  1581. $this->Sender = ini_get('sendmail_from');
  1582. }
  1583. //CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
  1584. if (!empty($this->Sender) && static::validateAddress($this->Sender) && self::isShellSafe($this->Sender)) {
  1585. if ($this->Mailer === 'qmail') {
  1586. $sendmailFmt = '%s -f%s';
  1587. } else {
  1588. $sendmailFmt = '%s -oi -f%s -t';
  1589. }
  1590. } else {
  1591. //allow sendmail to choose a default envelope sender. It may
  1592. //seem preferable to force it to use the From header as with
  1593. //SMTP, but that introduces new problems (see
  1594. //<https://github.com/PHPMailer/PHPMailer/issues/2298>), and
  1595. //it has historically worked this way.
  1596. $sendmailFmt = '%s -oi -t';
  1597. }
  1598. $sendmail = sprintf($sendmailFmt, escapeshellcmd($this->Sendmail), $this->Sender);
  1599. $this->edebug('Sendmail path: ' . $this->Sendmail);
  1600. $this->edebug('Sendmail command: ' . $sendmail);
  1601. $this->edebug('Envelope sender: ' . $this->Sender);
  1602. $this->edebug("Headers: {$header}");
  1603. if ($this->SingleTo) {
  1604. foreach ($this->SingleToArray as $toAddr) {
  1605. $mail = @popen($sendmail, 'w');
  1606. if (!$mail) {
  1607. throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1608. }
  1609. $this->edebug("To: {$toAddr}");
  1610. fwrite($mail, 'To: ' . $toAddr . "\n");
  1611. fwrite($mail, $header);
  1612. fwrite($mail, $body);
  1613. $result = pclose($mail);
  1614. $addrinfo = static::parseAddresses($toAddr, true, $this->CharSet);
  1615. $this->doCallback(
  1616. ($result === 0),
  1617. [[$addrinfo['address'], $addrinfo['name']]],
  1618. $this->cc,
  1619. $this->bcc,
  1620. $this->Subject,
  1621. $body,
  1622. $this->From,
  1623. []
  1624. );
  1625. $this->edebug("Result: " . ($result === 0 ? 'true' : 'false'));
  1626. if (0 !== $result) {
  1627. throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1628. }
  1629. }
  1630. } else {
  1631. $mail = @popen($sendmail, 'w');
  1632. if (!$mail) {
  1633. throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1634. }
  1635. fwrite($mail, $header);
  1636. fwrite($mail, $body);
  1637. $result = pclose($mail);
  1638. $this->doCallback(
  1639. ($result === 0),
  1640. $this->to,
  1641. $this->cc,
  1642. $this->bcc,
  1643. $this->Subject,
  1644. $body,
  1645. $this->From,
  1646. []
  1647. );
  1648. $this->edebug("Result: " . ($result === 0 ? 'true' : 'false'));
  1649. if (0 !== $result) {
  1650. throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1651. }
  1652. }
  1653. return true;
  1654. }
  1655. /**
  1656. * Fix CVE-2016-10033 and CVE-2016-10045 by disallowing potentially unsafe shell characters.
  1657. * Note that escapeshellarg and escapeshellcmd are inadequate for our purposes, especially on Windows.
  1658. *
  1659. * @see https://github.com/PHPMailer/PHPMailer/issues/924 CVE-2016-10045 bug report
  1660. *
  1661. * @param string $string The string to be validated
  1662. *
  1663. * @return bool
  1664. */
  1665. protected static function isShellSafe($string)
  1666. {
  1667. //It's not possible to use shell commands safely (which includes the mail() function) without escapeshellarg,
  1668. //but some hosting providers disable it, creating a security problem that we don't want to have to deal with,
  1669. //so we don't.
  1670. if (!function_exists('escapeshellarg') || !function_exists('escapeshellcmd')) {
  1671. return false;
  1672. }
  1673. if (
  1674. escapeshellcmd($string) !== $string
  1675. || !in_array(escapeshellarg($string), ["'$string'", "\"$string\""])
  1676. ) {
  1677. return false;
  1678. }
  1679. $length = strlen($string);
  1680. for ($i = 0; $i < $length; ++$i) {
  1681. $c = $string[$i];
  1682. //All other characters have a special meaning in at least one common shell, including = and +.
  1683. //Full stop (.) has a special meaning in cmd.exe, but its impact should be negligible here.
  1684. //Note that this does permit non-Latin alphanumeric characters based on the current locale.
  1685. if (!ctype_alnum($c) && strpos('@_-.', $c) === false) {
  1686. return false;
  1687. }
  1688. }
  1689. return true;
  1690. }
  1691. /**
  1692. * Check whether a file path is of a permitted type.
  1693. * Used to reject URLs and phar files from functions that access local file paths,
  1694. * such as addAttachment.
  1695. *
  1696. * @param string $path A relative or absolute path to a file
  1697. *
  1698. * @return bool
  1699. */
  1700. protected static function isPermittedPath($path)
  1701. {
  1702. //Matches scheme definition from https://tools.ietf.org/html/rfc3986#section-3.1
  1703. return !preg_match('#^[a-z][a-z\d+.-]*://#i', $path);
  1704. }
  1705. /**
  1706. * Check whether a file path is safe, accessible, and readable.
  1707. *
  1708. * @param string $path A relative or absolute path to a file
  1709. *
  1710. * @return bool
  1711. */
  1712. protected static function fileIsAccessible($path)
  1713. {
  1714. if (!static::isPermittedPath($path)) {
  1715. return false;
  1716. }
  1717. $readable = is_file($path);
  1718. //If not a UNC path (expected to start with \\), check read permission, see #2069
  1719. if (strpos($path, '\\\\') !== 0) {
  1720. $readable = $readable && is_readable($path);
  1721. }
  1722. return $readable;
  1723. }
  1724. /**
  1725. * Send mail using the PHP mail() function.
  1726. *
  1727. * @see http://www.php.net/manual/en/book.mail.php
  1728. *
  1729. * @param string $header The message headers
  1730. * @param string $body The message body
  1731. *
  1732. * @throws Exception
  1733. *
  1734. * @return bool
  1735. */
  1736. protected function mailSend($header, $body)
  1737. {
  1738. $header = static::stripTrailingWSP($header) . static::$LE . static::$LE;
  1739. $toArr = [];
  1740. foreach ($this->to as $toaddr) {
  1741. $toArr[] = $this->addrFormat($toaddr);
  1742. }
  1743. $to = trim(implode(', ', $toArr));
  1744. //If there are no To-addresses (e.g. when sending only to BCC-addresses)
  1745. //the following should be added to get a correct DKIM-signature.
  1746. //Compare with $this->preSend()
  1747. if ($to === '') {
  1748. $to = 'undisclosed-recipients:;';
  1749. }
  1750. $params = null;
  1751. //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver
  1752. //A space after `-f` is optional, but there is a long history of its presence
  1753. //causing problems, so we don't use one
  1754. //Exim docs: http://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html
  1755. //Sendmail docs: http://www.sendmail.org/~ca/email/man/sendmail.html
  1756. //Qmail docs: http://www.qmail.org/man/man8/qmail-inject.html
  1757. //Example problem: https://www.drupal.org/node/1057954
  1758. //CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
  1759. //PHP 5.6 workaround
  1760. $sendmail_from_value = ini_get('sendmail_from');
  1761. if (empty($this->Sender) && !empty($sendmail_from_value)) {
  1762. //PHP config has a sender address we can use
  1763. $this->Sender = ini_get('sendmail_from');
  1764. }
  1765. if (!empty($this->Sender) && static::validateAddress($this->Sender)) {
  1766. if (self::isShellSafe($this->Sender)) {
  1767. $params = sprintf('-f%s', $this->Sender);
  1768. }
  1769. $old_from = ini_get('sendmail_from');
  1770. ini_set('sendmail_from', $this->Sender);
  1771. }
  1772. $result = false;
  1773. if ($this->SingleTo && count($toArr) > 1) {
  1774. foreach ($toArr as $toAddr) {
  1775. $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params);
  1776. $addrinfo = static::parseAddresses($toAddr, true, $this->CharSet);
  1777. $this->doCallback(
  1778. $result,
  1779. [[$addrinfo['address'], $addrinfo['name']]],
  1780. $this->cc,
  1781. $this->bcc,
  1782. $this->Subject,
  1783. $body,
  1784. $this->From,
  1785. []
  1786. );
  1787. }
  1788. } else {
  1789. $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params);
  1790. $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From, []);
  1791. }
  1792. if (isset($old_from)) {
  1793. ini_set('sendmail_from', $old_from);
  1794. }
  1795. if (!$result) {
  1796. throw new Exception($this->lang('instantiate'), self::STOP_CRITICAL);
  1797. }
  1798. return true;
  1799. }
  1800. /**
  1801. * Get an instance to use for SMTP operations.
  1802. * Override this function to load your own SMTP implementation,
  1803. * or set one with setSMTPInstance.
  1804. *
  1805. * @return SMTP
  1806. */
  1807. public function getSMTPInstance()
  1808. {
  1809. if (!is_object($this->smtp)) {
  1810. $this->smtp = new SMTP();
  1811. }
  1812. return $this->smtp;
  1813. }
  1814. /**
  1815. * Provide an instance to use for SMTP operations.
  1816. *
  1817. * @return SMTP
  1818. */
  1819. public function setSMTPInstance(SMTP $smtp)
  1820. {
  1821. $this->smtp = $smtp;
  1822. return $this->smtp;
  1823. }
  1824. /**
  1825. * Send mail via SMTP.
  1826. * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
  1827. *
  1828. * @see PHPMailer::setSMTPInstance() to use a different class.
  1829. *
  1830. * @uses \PHPMailer\PHPMailer\SMTP
  1831. *
  1832. * @param string $header The message headers
  1833. * @param string $body The message body
  1834. *
  1835. * @throws Exception
  1836. *
  1837. * @return bool
  1838. */
  1839. protected function smtpSend($header, $body)
  1840. {
  1841. $header = static::stripTrailingWSP($header) . static::$LE . static::$LE;
  1842. $bad_rcpt = [];
  1843. if (!$this->smtpConnect($this->SMTPOptions)) {
  1844. throw new Exception($this->lang('smtp_connect_failed'), self::STOP_CRITICAL);
  1845. }
  1846. //Sender already validated in preSend()
  1847. if ('' === $this->Sender) {
  1848. $smtp_from = $this->From;
  1849. } else {
  1850. $smtp_from = $this->Sender;
  1851. }
  1852. if (!$this->smtp->mail($smtp_from)) {
  1853. $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError()));
  1854. throw new Exception($this->ErrorInfo, self::STOP_CRITICAL);
  1855. }
  1856. $callbacks = [];
  1857. //Attempt to send to all recipients
  1858. foreach ([$this->to, $this->cc, $this->bcc] as $togroup) {
  1859. foreach ($togroup as $to) {
  1860. if (!$this->smtp->recipient($to[0], $this->dsn)) {
  1861. $error = $this->smtp->getError();
  1862. $bad_rcpt[] = ['to' => $to[0], 'error' => $error['detail']];
  1863. $isSent = false;
  1864. } else {
  1865. $isSent = true;
  1866. }
  1867. $callbacks[] = ['issent' => $isSent, 'to' => $to[0], 'name' => $to[1]];
  1868. }
  1869. }
  1870. //Only send the DATA command if we have viable recipients
  1871. if ((count($this->all_recipients) > count($bad_rcpt)) && !$this->smtp->data($header . $body)) {
  1872. throw new Exception($this->lang('data_not_accepted'), self::STOP_CRITICAL);
  1873. }
  1874. $smtp_transaction_id = $this->smtp->getLastTransactionID();
  1875. if ($this->SMTPKeepAlive) {
  1876. $this->smtp->reset();
  1877. } else {
  1878. $this->smtp->quit();
  1879. $this->smtp->close();
  1880. }
  1881. foreach ($callbacks as $cb) {
  1882. $this->doCallback(
  1883. $cb['issent'],
  1884. [[$cb['to'], $cb['name']]],
  1885. [],
  1886. [],
  1887. $this->Subject,
  1888. $body,
  1889. $this->From,
  1890. ['smtp_transaction_id' => $smtp_transaction_id]
  1891. );
  1892. }
  1893. //Create error message for any bad addresses
  1894. if (count($bad_rcpt) > 0) {
  1895. $errstr = '';
  1896. foreach ($bad_rcpt as $bad) {
  1897. $errstr .= $bad['to'] . ': ' . $bad['error'];
  1898. }
  1899. throw new Exception($this->lang('recipients_failed') . $errstr, self::STOP_CONTINUE);
  1900. }
  1901. return true;
  1902. }
  1903. /**
  1904. * Initiate a connection to an SMTP server.
  1905. * Returns false if the operation failed.
  1906. *
  1907. * @param array $options An array of options compatible with stream_context_create()
  1908. *
  1909. * @throws Exception
  1910. *
  1911. * @uses \PHPMailer\PHPMailer\SMTP
  1912. *
  1913. * @return bool
  1914. */
  1915. public function smtpConnect($options = null)
  1916. {
  1917. if (null === $this->smtp) {
  1918. $this->smtp = $this->getSMTPInstance();
  1919. }
  1920. //If no options are provided, use whatever is set in the instance
  1921. if (null === $options) {
  1922. $options = $this->SMTPOptions;
  1923. }
  1924. //Already connected?
  1925. if ($this->smtp->connected()) {
  1926. return true;
  1927. }
  1928. $this->smtp->setTimeout($this->Timeout);
  1929. $this->smtp->setDebugLevel($this->SMTPDebug);
  1930. $this->smtp->setDebugOutput($this->Debugoutput);
  1931. $this->smtp->setVerp($this->do_verp);
  1932. if ($this->Host === null) {
  1933. $this->Host = 'localhost';
  1934. }
  1935. $hosts = explode(';', $this->Host);
  1936. $lastexception = null;
  1937. foreach ($hosts as $hostentry) {
  1938. $hostinfo = [];
  1939. if (
  1940. !preg_match(
  1941. '/^(?:(ssl|tls):\/\/)?(.+?)(?::(\d+))?$/',
  1942. trim($hostentry),
  1943. $hostinfo
  1944. )
  1945. ) {
  1946. $this->edebug($this->lang('invalid_hostentry') . ' ' . trim($hostentry));
  1947. //Not a valid host entry
  1948. continue;
  1949. }
  1950. //$hostinfo[1]: optional ssl or tls prefix
  1951. //$hostinfo[2]: the hostname
  1952. //$hostinfo[3]: optional port number
  1953. //The host string prefix can temporarily override the current setting for SMTPSecure
  1954. //If it's not specified, the default value is used
  1955. //Check the host name is a valid name or IP address before trying to use it
  1956. if (!static::isValidHost($hostinfo[2])) {
  1957. $this->edebug($this->lang('invalid_host') . ' ' . $hostinfo[2]);
  1958. continue;
  1959. }
  1960. $prefix = '';
  1961. $secure = $this->SMTPSecure;
  1962. $tls = (static::ENCRYPTION_STARTTLS === $this->SMTPSecure);
  1963. if ('ssl' === $hostinfo[1] || ('' === $hostinfo[1] && static::ENCRYPTION_SMTPS === $this->SMTPSecure)) {
  1964. $prefix = 'ssl://';
  1965. $tls = false; //Can't have SSL and TLS at the same time
  1966. $secure = static::ENCRYPTION_SMTPS;
  1967. } elseif ('tls' === $hostinfo[1]) {
  1968. $tls = true;
  1969. //TLS doesn't use a prefix
  1970. $secure = static::ENCRYPTION_STARTTLS;
  1971. }
  1972. //Do we need the OpenSSL extension?
  1973. $sslext = defined('OPENSSL_ALGO_SHA256');
  1974. if (static::ENCRYPTION_STARTTLS === $secure || static::ENCRYPTION_SMTPS === $secure) {
  1975. //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled
  1976. if (!$sslext) {
  1977. throw new Exception($this->lang('extension_missing') . 'openssl', self::STOP_CRITICAL);
  1978. }
  1979. }
  1980. $host = $hostinfo[2];
  1981. $port = $this->Port;
  1982. if (
  1983. array_key_exists(3, $hostinfo) &&
  1984. is_numeric($hostinfo[3]) &&
  1985. $hostinfo[3] > 0 &&
  1986. $hostinfo[3] < 65536
  1987. ) {
  1988. $port = (int) $hostinfo[3];
  1989. }
  1990. if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) {
  1991. try {
  1992. if ($this->Helo) {
  1993. $hello = $this->Helo;
  1994. } else {
  1995. $hello = $this->serverHostname();
  1996. }
  1997. $this->smtp->hello($hello);
  1998. //Automatically enable TLS encryption if:
  1999. //* it's not disabled
  2000. //* we have openssl extension
  2001. //* we are not already using SSL
  2002. //* the server offers STARTTLS
  2003. if ($this->SMTPAutoTLS && $sslext && 'ssl' !== $secure && $this->smtp->getServerExt('STARTTLS')) {
  2004. $tls = true;
  2005. }
  2006. if ($tls) {
  2007. if (!$this->smtp->startTLS()) {
  2008. $message = $this->getSmtpErrorMessage('connect_host');
  2009. throw new Exception($message);
  2010. }
  2011. //We must resend EHLO after TLS negotiation
  2012. $this->smtp->hello($hello);
  2013. }
  2014. if (
  2015. $this->SMTPAuth && !$this->smtp->authenticate(
  2016. $this->Username,
  2017. $this->Password,
  2018. $this->AuthType,
  2019. $this->oauth
  2020. )
  2021. ) {
  2022. throw new Exception($this->lang('authenticate'));
  2023. }
  2024. return true;
  2025. } catch (Exception $exc) {
  2026. $lastexception = $exc;
  2027. $this->edebug($exc->getMessage());
  2028. //We must have connected, but then failed TLS or Auth, so close connection nicely
  2029. $this->smtp->quit();
  2030. }
  2031. }
  2032. }
  2033. //If we get here, all connection attempts have failed, so close connection hard
  2034. $this->smtp->close();
  2035. //As we've caught all exceptions, just report whatever the last one was
  2036. if ($this->exceptions && null !== $lastexception) {
  2037. throw $lastexception;
  2038. }
  2039. if ($this->exceptions) {
  2040. // no exception was thrown, likely $this->smtp->connect() failed
  2041. $message = $this->getSmtpErrorMessage('connect_host');
  2042. throw new Exception($message);
  2043. }
  2044. return false;
  2045. }
  2046. /**
  2047. * Close the active SMTP session if one exists.
  2048. */
  2049. public function smtpClose()
  2050. {
  2051. if ((null !== $this->smtp) && $this->smtp->connected()) {
  2052. $this->smtp->quit();
  2053. $this->smtp->close();
  2054. }
  2055. }
  2056. /**
  2057. * Set the language for error messages.
  2058. * The default language is English.
  2059. *
  2060. * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr")
  2061. * Optionally, the language code can be enhanced with a 4-character
  2062. * script annotation and/or a 2-character country annotation.
  2063. * @param string $lang_path Path to the language file directory, with trailing separator (slash)
  2064. * Do not set this from user input!
  2065. *
  2066. * @return bool Returns true if the requested language was loaded, false otherwise.
  2067. */
  2068. public function setLanguage($langcode = 'en', $lang_path = '')
  2069. {
  2070. //Backwards compatibility for renamed language codes
  2071. $renamed_langcodes = [
  2072. 'br' => 'pt_br',
  2073. 'cz' => 'cs',
  2074. 'dk' => 'da',
  2075. 'no' => 'nb',
  2076. 'se' => 'sv',
  2077. 'rs' => 'sr',
  2078. 'tg' => 'tl',
  2079. 'am' => 'hy',
  2080. ];
  2081. if (array_key_exists($langcode, $renamed_langcodes)) {
  2082. $langcode = $renamed_langcodes[$langcode];
  2083. }
  2084. //Define full set of translatable strings in English
  2085. $PHPMAILER_LANG = [
  2086. 'authenticate' => 'SMTP Error: Could not authenticate.',
  2087. 'buggy_php' => 'Your version of PHP is affected by a bug that may result in corrupted messages.' .
  2088. ' To fix it, switch to sending using SMTP, disable the mail.add_x_header option in' .
  2089. ' your php.ini, switch to MacOS or Linux, or upgrade your PHP to version 7.0.17+ or 7.1.3+.',
  2090. 'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
  2091. 'data_not_accepted' => 'SMTP Error: data not accepted.',
  2092. 'empty_message' => 'Message body empty',
  2093. 'encoding' => 'Unknown encoding: ',
  2094. 'execute' => 'Could not execute: ',
  2095. 'extension_missing' => 'Extension missing: ',
  2096. 'file_access' => 'Could not access file: ',
  2097. 'file_open' => 'File Error: Could not open file: ',
  2098. 'from_failed' => 'The following From address failed: ',
  2099. 'instantiate' => 'Could not instantiate mail function.',
  2100. 'invalid_address' => 'Invalid address: ',
  2101. 'invalid_header' => 'Invalid header name or value',
  2102. 'invalid_hostentry' => 'Invalid hostentry: ',
  2103. 'invalid_host' => 'Invalid host: ',
  2104. 'mailer_not_supported' => ' mailer is not supported.',
  2105. 'provide_address' => 'You must provide at least one recipient email address.',
  2106. 'recipients_failed' => 'SMTP Error: The following recipients failed: ',
  2107. 'signing' => 'Signing Error: ',
  2108. 'smtp_code' => 'SMTP code: ',
  2109. 'smtp_code_ex' => 'Additional SMTP info: ',
  2110. 'smtp_connect_failed' => 'SMTP connect() failed.',
  2111. 'smtp_detail' => 'Detail: ',
  2112. 'smtp_error' => 'SMTP server error: ',
  2113. 'variable_set' => 'Cannot set or reset variable: ',
  2114. ];
  2115. if (empty($lang_path)) {
  2116. //Calculate an absolute path so it can work if CWD is not here
  2117. $lang_path = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'language' . DIRECTORY_SEPARATOR;
  2118. }
  2119. //Validate $langcode
  2120. $foundlang = true;
  2121. $langcode = strtolower($langcode);
  2122. if (
  2123. !preg_match('/^(?P<lang>[a-z]{2})(?P<script>_[a-z]{4})?(?P<country>_[a-z]{2})?$/', $langcode, $matches)
  2124. && $langcode !== 'en'
  2125. ) {
  2126. $foundlang = false;
  2127. $langcode = 'en';
  2128. }
  2129. //There is no English translation file
  2130. if ('en' !== $langcode) {
  2131. $langcodes = [];
  2132. if (!empty($matches['script']) && !empty($matches['country'])) {
  2133. $langcodes[] = $matches['lang'] . $matches['script'] . $matches['country'];
  2134. }
  2135. if (!empty($matches['country'])) {
  2136. $langcodes[] = $matches['lang'] . $matches['country'];
  2137. }
  2138. if (!empty($matches['script'])) {
  2139. $langcodes[] = $matches['lang'] . $matches['script'];
  2140. }
  2141. $langcodes[] = $matches['lang'];
  2142. //Try and find a readable language file for the requested language.
  2143. $foundFile = false;
  2144. foreach ($langcodes as $code) {
  2145. $lang_file = $lang_path . 'phpmailer.lang-' . $code . '.php';
  2146. if (static::fileIsAccessible($lang_file)) {
  2147. $foundFile = true;
  2148. break;
  2149. }
  2150. }
  2151. if ($foundFile === false) {
  2152. $foundlang = false;
  2153. } else {
  2154. $lines = file($lang_file);
  2155. foreach ($lines as $line) {
  2156. //Translation file lines look like this:
  2157. //$PHPMAILER_LANG['authenticate'] = 'SMTP-Fehler: Authentifizierung fehlgeschlagen.';
  2158. //These files are parsed as text and not PHP so as to avoid the possibility of code injection
  2159. //See https://blog.stevenlevithan.com/archives/match-quoted-string
  2160. $matches = [];
  2161. if (
  2162. preg_match(
  2163. '/^\$PHPMAILER_LANG\[\'([a-z\d_]+)\'\]\s*=\s*(["\'])(.+)*?\2;/',
  2164. $line,
  2165. $matches
  2166. ) &&
  2167. //Ignore unknown translation keys
  2168. array_key_exists($matches[1], $PHPMAILER_LANG)
  2169. ) {
  2170. //Overwrite language-specific strings so we'll never have missing translation keys.
  2171. $PHPMAILER_LANG[$matches[1]] = (string)$matches[3];
  2172. }
  2173. }
  2174. }
  2175. }
  2176. $this->language = $PHPMAILER_LANG;
  2177. return $foundlang; //Returns false if language not found
  2178. }
  2179. /**
  2180. * Get the array of strings for the current language.
  2181. *
  2182. * @return array
  2183. */
  2184. public function getTranslations()
  2185. {
  2186. if (empty($this->language)) {
  2187. $this->setLanguage(); // Set the default language.
  2188. }
  2189. return $this->language;
  2190. }
  2191. /**
  2192. * Create recipient headers.
  2193. *
  2194. * @param string $type
  2195. * @param array $addr An array of recipients,
  2196. * where each recipient is a 2-element indexed array with element 0 containing an address
  2197. * and element 1 containing a name, like:
  2198. * [['joe@example.com', 'Joe User'], ['zoe@example.com', 'Zoe User']]
  2199. *
  2200. * @return string
  2201. */
  2202. public function addrAppend($type, $addr)
  2203. {
  2204. $addresses = [];
  2205. foreach ($addr as $address) {
  2206. $addresses[] = $this->addrFormat($address);
  2207. }
  2208. return $type . ': ' . implode(', ', $addresses) . static::$LE;
  2209. }
  2210. /**
  2211. * Format an address for use in a message header.
  2212. *
  2213. * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name like
  2214. * ['joe@example.com', 'Joe User']
  2215. *
  2216. * @return string
  2217. */
  2218. public function addrFormat($addr)
  2219. {
  2220. if (!isset($addr[1]) || ($addr[1] === '')) { //No name provided
  2221. return $this->secureHeader($addr[0]);
  2222. }
  2223. return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') .
  2224. ' <' . $this->secureHeader($addr[0]) . '>';
  2225. }
  2226. /**
  2227. * Word-wrap message.
  2228. * For use with mailers that do not automatically perform wrapping
  2229. * and for quoted-printable encoded messages.
  2230. * Original written by philippe.
  2231. *
  2232. * @param string $message The message to wrap
  2233. * @param int $length The line length to wrap to
  2234. * @param bool $qp_mode Whether to run in Quoted-Printable mode
  2235. *
  2236. * @return string
  2237. */
  2238. public function wrapText($message, $length, $qp_mode = false)
  2239. {
  2240. if ($qp_mode) {
  2241. $soft_break = sprintf(' =%s', static::$LE);
  2242. } else {
  2243. $soft_break = static::$LE;
  2244. }
  2245. //If utf-8 encoding is used, we will need to make sure we don't
  2246. //split multibyte characters when we wrap
  2247. $is_utf8 = static::CHARSET_UTF8 === strtolower($this->CharSet);
  2248. $lelen = strlen(static::$LE);
  2249. $crlflen = strlen(static::$LE);
  2250. $message = static::normalizeBreaks($message);
  2251. //Remove a trailing line break
  2252. if (substr($message, -$lelen) === static::$LE) {
  2253. $message = substr($message, 0, -$lelen);
  2254. }
  2255. //Split message into lines
  2256. $lines = explode(static::$LE, $message);
  2257. //Message will be rebuilt in here
  2258. $message = '';
  2259. foreach ($lines as $line) {
  2260. $words = explode(' ', $line);
  2261. $buf = '';
  2262. $firstword = true;
  2263. foreach ($words as $word) {
  2264. if ($qp_mode && (strlen($word) > $length)) {
  2265. $space_left = $length - strlen($buf) - $crlflen;
  2266. if (!$firstword) {
  2267. if ($space_left > 20) {
  2268. $len = $space_left;
  2269. if ($is_utf8) {
  2270. $len = $this->utf8CharBoundary($word, $len);
  2271. } elseif ('=' === substr($word, $len - 1, 1)) {
  2272. --$len;
  2273. } elseif ('=' === substr($word, $len - 2, 1)) {
  2274. $len -= 2;
  2275. }
  2276. $part = substr($word, 0, $len);
  2277. $word = substr($word, $len);
  2278. $buf .= ' ' . $part;
  2279. $message .= $buf . sprintf('=%s', static::$LE);
  2280. } else {
  2281. $message .= $buf . $soft_break;
  2282. }
  2283. $buf = '';
  2284. }
  2285. while ($word !== '') {
  2286. if ($length <= 0) {
  2287. break;
  2288. }
  2289. $len = $length;
  2290. if ($is_utf8) {
  2291. $len = $this->utf8CharBoundary($word, $len);
  2292. } elseif ('=' === substr($word, $len - 1, 1)) {
  2293. --$len;
  2294. } elseif ('=' === substr($word, $len - 2, 1)) {
  2295. $len -= 2;
  2296. }
  2297. $part = substr($word, 0, $len);
  2298. $word = (string) substr($word, $len);
  2299. if ($word !== '') {
  2300. $message .= $part . sprintf('=%s', static::$LE);
  2301. } else {
  2302. $buf = $part;
  2303. }
  2304. }
  2305. } else {
  2306. $buf_o = $buf;
  2307. if (!$firstword) {
  2308. $buf .= ' ';
  2309. }
  2310. $buf .= $word;
  2311. if ('' !== $buf_o && strlen($buf) > $length) {
  2312. $message .= $buf_o . $soft_break;
  2313. $buf = $word;
  2314. }
  2315. }
  2316. $firstword = false;
  2317. }
  2318. $message .= $buf . static::$LE;
  2319. }
  2320. return $message;
  2321. }
  2322. /**
  2323. * Find the last character boundary prior to $maxLength in a utf-8
  2324. * quoted-printable encoded string.
  2325. * Original written by Colin Brown.
  2326. *
  2327. * @param string $encodedText utf-8 QP text
  2328. * @param int $maxLength Find the last character boundary prior to this length
  2329. *
  2330. * @return int
  2331. */
  2332. public function utf8CharBoundary($encodedText, $maxLength)
  2333. {
  2334. $foundSplitPos = false;
  2335. $lookBack = 3;
  2336. while (!$foundSplitPos) {
  2337. $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
  2338. $encodedCharPos = strpos($lastChunk, '=');
  2339. if (false !== $encodedCharPos) {
  2340. //Found start of encoded character byte within $lookBack block.
  2341. //Check the encoded byte value (the 2 chars after the '=')
  2342. $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
  2343. $dec = hexdec($hex);
  2344. if ($dec < 128) {
  2345. //Single byte character.
  2346. //If the encoded char was found at pos 0, it will fit
  2347. //otherwise reduce maxLength to start of the encoded char
  2348. if ($encodedCharPos > 0) {
  2349. $maxLength -= $lookBack - $encodedCharPos;
  2350. }
  2351. $foundSplitPos = true;
  2352. } elseif ($dec >= 192) {
  2353. //First byte of a multi byte character
  2354. //Reduce maxLength to split at start of character
  2355. $maxLength -= $lookBack - $encodedCharPos;
  2356. $foundSplitPos = true;
  2357. } elseif ($dec < 192) {
  2358. //Middle byte of a multi byte character, look further back
  2359. $lookBack += 3;
  2360. }
  2361. } else {
  2362. //No encoded character found
  2363. $foundSplitPos = true;
  2364. }
  2365. }
  2366. return $maxLength;
  2367. }
  2368. /**
  2369. * Apply word wrapping to the message body.
  2370. * Wraps the message body to the number of chars set in the WordWrap property.
  2371. * You should only do this to plain-text bodies as wrapping HTML tags may break them.
  2372. * This is called automatically by createBody(), so you don't need to call it yourself.
  2373. */
  2374. public function setWordWrap()
  2375. {
  2376. if ($this->WordWrap < 1) {
  2377. return;
  2378. }
  2379. switch ($this->message_type) {
  2380. case 'alt':
  2381. case 'alt_inline':
  2382. case 'alt_attach':
  2383. case 'alt_inline_attach':
  2384. $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap);
  2385. break;
  2386. default:
  2387. $this->Body = $this->wrapText($this->Body, $this->WordWrap);
  2388. break;
  2389. }
  2390. }
  2391. /**
  2392. * Assemble message headers.
  2393. *
  2394. * @return string The assembled headers
  2395. */
  2396. public function createHeader()
  2397. {
  2398. $result = '';
  2399. $result .= $this->headerLine('Date', '' === $this->MessageDate ? self::rfcDate() : $this->MessageDate);
  2400. //The To header is created automatically by mail(), so needs to be omitted here
  2401. if ('mail' !== $this->Mailer) {
  2402. if ($this->SingleTo) {
  2403. foreach ($this->to as $toaddr) {
  2404. $this->SingleToArray[] = $this->addrFormat($toaddr);
  2405. }
  2406. } elseif (count($this->to) > 0) {
  2407. $result .= $this->addrAppend('To', $this->to);
  2408. } elseif (count($this->cc) === 0) {
  2409. $result .= $this->headerLine('To', 'undisclosed-recipients:;');
  2410. }
  2411. }
  2412. $result .= $this->addrAppend('From', [[trim($this->From), $this->FromName]]);
  2413. //sendmail and mail() extract Cc from the header before sending
  2414. if (count($this->cc) > 0) {
  2415. $result .= $this->addrAppend('Cc', $this->cc);
  2416. }
  2417. //sendmail and mail() extract Bcc from the header before sending
  2418. if (
  2419. (
  2420. 'sendmail' === $this->Mailer || 'qmail' === $this->Mailer || 'mail' === $this->Mailer
  2421. )
  2422. && count($this->bcc) > 0
  2423. ) {
  2424. $result .= $this->addrAppend('Bcc', $this->bcc);
  2425. }
  2426. if (count($this->ReplyTo) > 0) {
  2427. $result .= $this->addrAppend('Reply-To', $this->ReplyTo);
  2428. }
  2429. //mail() sets the subject itself
  2430. if ('mail' !== $this->Mailer) {
  2431. $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject)));
  2432. }
  2433. //Only allow a custom message ID if it conforms to RFC 5322 section 3.6.4
  2434. //https://tools.ietf.org/html/rfc5322#section-3.6.4
  2435. if (
  2436. '' !== $this->MessageID &&
  2437. preg_match(
  2438. '/^<((([a-z\d!#$%&\'*+\/=?^_`{|}~-]+(\.[a-z\d!#$%&\'*+\/=?^_`{|}~-]+)*)' .
  2439. '|("(([\x01-\x08\x0B\x0C\x0E-\x1F\x7F]|[\x21\x23-\x5B\x5D-\x7E])' .
  2440. '|(\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*"))@(([a-z\d!#$%&\'*+\/=?^_`{|}~-]+' .
  2441. '(\.[a-z\d!#$%&\'*+\/=?^_`{|}~-]+)*)|(\[(([\x01-\x08\x0B\x0C\x0E-\x1F\x7F]' .
  2442. '|[\x21-\x5A\x5E-\x7E])|(\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*\])))>$/Di',
  2443. $this->MessageID
  2444. )
  2445. ) {
  2446. $this->lastMessageID = $this->MessageID;
  2447. } else {
  2448. $this->lastMessageID = sprintf('<%s@%s>', $this->uniqueid, $this->serverHostname());
  2449. }
  2450. $result .= $this->headerLine('Message-ID', $this->lastMessageID);
  2451. if (null !== $this->Priority) {
  2452. $result .= $this->headerLine('X-Priority', $this->Priority);
  2453. }
  2454. if ('' === $this->XMailer) {
  2455. //Empty string for default X-Mailer header
  2456. $result .= $this->headerLine(
  2457. 'X-Mailer',
  2458. 'PHPMailer ' . self::VERSION . ' (https://github.com/PHPMailer/PHPMailer)'
  2459. );
  2460. } elseif (is_string($this->XMailer) && trim($this->XMailer) !== '') {
  2461. //Some string
  2462. $result .= $this->headerLine('X-Mailer', trim($this->XMailer));
  2463. } //Other values result in no X-Mailer header
  2464. if ('' !== $this->ConfirmReadingTo) {
  2465. $result .= $this->headerLine('Disposition-Notification-To', '<' . $this->ConfirmReadingTo . '>');
  2466. }
  2467. //Add custom headers
  2468. foreach ($this->CustomHeader as $header) {
  2469. $result .= $this->headerLine(
  2470. trim($header[0]),
  2471. $this->encodeHeader(trim($header[1]))
  2472. );
  2473. }
  2474. if (!$this->sign_key_file) {
  2475. $result .= $this->headerLine('MIME-Version', '1.0');
  2476. $result .= $this->getMailMIME();
  2477. }
  2478. return $result;
  2479. }
  2480. /**
  2481. * Get the message MIME type headers.
  2482. *
  2483. * @return string
  2484. */
  2485. public function getMailMIME()
  2486. {
  2487. $result = '';
  2488. $ismultipart = true;
  2489. switch ($this->message_type) {
  2490. case 'inline':
  2491. $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
  2492. $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"');
  2493. break;
  2494. case 'attach':
  2495. case 'inline_attach':
  2496. case 'alt_attach':
  2497. case 'alt_inline_attach':
  2498. $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_MIXED . ';');
  2499. $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"');
  2500. break;
  2501. case 'alt':
  2502. case 'alt_inline':
  2503. $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';');
  2504. $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"');
  2505. break;
  2506. default:
  2507. //Catches case 'plain': and case '':
  2508. $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet);
  2509. $ismultipart = false;
  2510. break;
  2511. }
  2512. //RFC1341 part 5 says 7bit is assumed if not specified
  2513. if (static::ENCODING_7BIT !== $this->Encoding) {
  2514. //RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE
  2515. if ($ismultipart) {
  2516. if (static::ENCODING_8BIT === $this->Encoding) {
  2517. $result .= $this->headerLine('Content-Transfer-Encoding', static::ENCODING_8BIT);
  2518. }
  2519. //The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible
  2520. } else {
  2521. $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding);
  2522. }
  2523. }
  2524. return $result;
  2525. }
  2526. /**
  2527. * Returns the whole MIME message.
  2528. * Includes complete headers and body.
  2529. * Only valid post preSend().
  2530. *
  2531. * @see PHPMailer::preSend()
  2532. *
  2533. * @return string
  2534. */
  2535. public function getSentMIMEMessage()
  2536. {
  2537. return static::stripTrailingWSP($this->MIMEHeader . $this->mailHeader) .
  2538. static::$LE . static::$LE . $this->MIMEBody;
  2539. }
  2540. /**
  2541. * Create a unique ID to use for boundaries.
  2542. *
  2543. * @return string
  2544. */
  2545. protected function generateId()
  2546. {
  2547. $len = 32; //32 bytes = 256 bits
  2548. $bytes = '';
  2549. if (function_exists('random_bytes')) {
  2550. try {
  2551. $bytes = random_bytes($len);
  2552. } catch (\Exception $e) {
  2553. //Do nothing
  2554. }
  2555. } elseif (function_exists('openssl_random_pseudo_bytes')) {
  2556. /** @noinspection CryptographicallySecureRandomnessInspection */
  2557. $bytes = openssl_random_pseudo_bytes($len);
  2558. }
  2559. if ($bytes === '') {
  2560. //We failed to produce a proper random string, so make do.
  2561. //Use a hash to force the length to the same as the other methods
  2562. $bytes = hash('sha256', uniqid((string) mt_rand(), true), true);
  2563. }
  2564. //We don't care about messing up base64 format here, just want a random string
  2565. return str_replace(['=', '+', '/'], '', base64_encode(hash('sha256', $bytes, true)));
  2566. }
  2567. /**
  2568. * Assemble the message body.
  2569. * Returns an empty string on failure.
  2570. *
  2571. * @throws Exception
  2572. *
  2573. * @return string The assembled message body
  2574. */
  2575. public function createBody()
  2576. {
  2577. $body = '';
  2578. //Create unique IDs and preset boundaries
  2579. $this->setBoundaries();
  2580. if ($this->sign_key_file) {
  2581. $body .= $this->getMailMIME() . static::$LE;
  2582. }
  2583. $this->setWordWrap();
  2584. $bodyEncoding = $this->Encoding;
  2585. $bodyCharSet = $this->CharSet;
  2586. //Can we do a 7-bit downgrade?
  2587. if (static::ENCODING_8BIT === $bodyEncoding && !$this->has8bitChars($this->Body)) {
  2588. $bodyEncoding = static::ENCODING_7BIT;
  2589. //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit
  2590. $bodyCharSet = static::CHARSET_ASCII;
  2591. }
  2592. //If lines are too long, and we're not already using an encoding that will shorten them,
  2593. //change to quoted-printable transfer encoding for the body part only
  2594. if (static::ENCODING_BASE64 !== $this->Encoding && static::hasLineLongerThanMax($this->Body)) {
  2595. $bodyEncoding = static::ENCODING_QUOTED_PRINTABLE;
  2596. }
  2597. $altBodyEncoding = $this->Encoding;
  2598. $altBodyCharSet = $this->CharSet;
  2599. //Can we do a 7-bit downgrade?
  2600. if (static::ENCODING_8BIT === $altBodyEncoding && !$this->has8bitChars($this->AltBody)) {
  2601. $altBodyEncoding = static::ENCODING_7BIT;
  2602. //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit
  2603. $altBodyCharSet = static::CHARSET_ASCII;
  2604. }
  2605. //If lines are too long, and we're not already using an encoding that will shorten them,
  2606. //change to quoted-printable transfer encoding for the alt body part only
  2607. if (static::ENCODING_BASE64 !== $altBodyEncoding && static::hasLineLongerThanMax($this->AltBody)) {
  2608. $altBodyEncoding = static::ENCODING_QUOTED_PRINTABLE;
  2609. }
  2610. //Use this as a preamble in all multipart message types
  2611. $mimepre = '';
  2612. switch ($this->message_type) {
  2613. case 'inline':
  2614. $body .= $mimepre;
  2615. $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
  2616. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2617. $body .= static::$LE;
  2618. $body .= $this->attachAll('inline', $this->boundary[1]);
  2619. break;
  2620. case 'attach':
  2621. $body .= $mimepre;
  2622. $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
  2623. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2624. $body .= static::$LE;
  2625. $body .= $this->attachAll('attachment', $this->boundary[1]);
  2626. break;
  2627. case 'inline_attach':
  2628. $body .= $mimepre;
  2629. $body .= $this->textLine('--' . $this->boundary[1]);
  2630. $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
  2631. $body .= $this->textLine(' boundary="' . $this->boundary[2] . '";');
  2632. $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"');
  2633. $body .= static::$LE;
  2634. $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding);
  2635. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2636. $body .= static::$LE;
  2637. $body .= $this->attachAll('inline', $this->boundary[2]);
  2638. $body .= static::$LE;
  2639. $body .= $this->attachAll('attachment', $this->boundary[1]);
  2640. break;
  2641. case 'alt':
  2642. $body .= $mimepre;
  2643. $body .= $this->getBoundary(
  2644. $this->boundary[1],
  2645. $altBodyCharSet,
  2646. static::CONTENT_TYPE_PLAINTEXT,
  2647. $altBodyEncoding
  2648. );
  2649. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  2650. $body .= static::$LE;
  2651. $body .= $this->getBoundary(
  2652. $this->boundary[1],
  2653. $bodyCharSet,
  2654. static::CONTENT_TYPE_TEXT_HTML,
  2655. $bodyEncoding
  2656. );
  2657. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2658. $body .= static::$LE;
  2659. if (!empty($this->Ical)) {
  2660. $method = static::ICAL_METHOD_REQUEST;
  2661. foreach (static::$IcalMethods as $imethod) {
  2662. if (stripos($this->Ical, 'METHOD:' . $imethod) !== false) {
  2663. $method = $imethod;
  2664. break;
  2665. }
  2666. }
  2667. $body .= $this->getBoundary(
  2668. $this->boundary[1],
  2669. '',
  2670. static::CONTENT_TYPE_TEXT_CALENDAR . '; method=' . $method,
  2671. ''
  2672. );
  2673. $body .= $this->encodeString($this->Ical, $this->Encoding);
  2674. $body .= static::$LE;
  2675. }
  2676. $body .= $this->endBoundary($this->boundary[1]);
  2677. break;
  2678. case 'alt_inline':
  2679. $body .= $mimepre;
  2680. $body .= $this->getBoundary(
  2681. $this->boundary[1],
  2682. $altBodyCharSet,
  2683. static::CONTENT_TYPE_PLAINTEXT,
  2684. $altBodyEncoding
  2685. );
  2686. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  2687. $body .= static::$LE;
  2688. $body .= $this->textLine('--' . $this->boundary[1]);
  2689. $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
  2690. $body .= $this->textLine(' boundary="' . $this->boundary[2] . '";');
  2691. $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"');
  2692. $body .= static::$LE;
  2693. $body .= $this->getBoundary(
  2694. $this->boundary[2],
  2695. $bodyCharSet,
  2696. static::CONTENT_TYPE_TEXT_HTML,
  2697. $bodyEncoding
  2698. );
  2699. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2700. $body .= static::$LE;
  2701. $body .= $this->attachAll('inline', $this->boundary[2]);
  2702. $body .= static::$LE;
  2703. $body .= $this->endBoundary($this->boundary[1]);
  2704. break;
  2705. case 'alt_attach':
  2706. $body .= $mimepre;
  2707. $body .= $this->textLine('--' . $this->boundary[1]);
  2708. $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';');
  2709. $body .= $this->textLine(' boundary="' . $this->boundary[2] . '"');
  2710. $body .= static::$LE;
  2711. $body .= $this->getBoundary(
  2712. $this->boundary[2],
  2713. $altBodyCharSet,
  2714. static::CONTENT_TYPE_PLAINTEXT,
  2715. $altBodyEncoding
  2716. );
  2717. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  2718. $body .= static::$LE;
  2719. $body .= $this->getBoundary(
  2720. $this->boundary[2],
  2721. $bodyCharSet,
  2722. static::CONTENT_TYPE_TEXT_HTML,
  2723. $bodyEncoding
  2724. );
  2725. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2726. $body .= static::$LE;
  2727. if (!empty($this->Ical)) {
  2728. $method = static::ICAL_METHOD_REQUEST;
  2729. foreach (static::$IcalMethods as $imethod) {
  2730. if (stripos($this->Ical, 'METHOD:' . $imethod) !== false) {
  2731. $method = $imethod;
  2732. break;
  2733. }
  2734. }
  2735. $body .= $this->getBoundary(
  2736. $this->boundary[2],
  2737. '',
  2738. static::CONTENT_TYPE_TEXT_CALENDAR . '; method=' . $method,
  2739. ''
  2740. );
  2741. $body .= $this->encodeString($this->Ical, $this->Encoding);
  2742. }
  2743. $body .= $this->endBoundary($this->boundary[2]);
  2744. $body .= static::$LE;
  2745. $body .= $this->attachAll('attachment', $this->boundary[1]);
  2746. break;
  2747. case 'alt_inline_attach':
  2748. $body .= $mimepre;
  2749. $body .= $this->textLine('--' . $this->boundary[1]);
  2750. $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';');
  2751. $body .= $this->textLine(' boundary="' . $this->boundary[2] . '"');
  2752. $body .= static::$LE;
  2753. $body .= $this->getBoundary(
  2754. $this->boundary[2],
  2755. $altBodyCharSet,
  2756. static::CONTENT_TYPE_PLAINTEXT,
  2757. $altBodyEncoding
  2758. );
  2759. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  2760. $body .= static::$LE;
  2761. $body .= $this->textLine('--' . $this->boundary[2]);
  2762. $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
  2763. $body .= $this->textLine(' boundary="' . $this->boundary[3] . '";');
  2764. $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"');
  2765. $body .= static::$LE;
  2766. $body .= $this->getBoundary(
  2767. $this->boundary[3],
  2768. $bodyCharSet,
  2769. static::CONTENT_TYPE_TEXT_HTML,
  2770. $bodyEncoding
  2771. );
  2772. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2773. $body .= static::$LE;
  2774. $body .= $this->attachAll('inline', $this->boundary[3]);
  2775. $body .= static::$LE;
  2776. $body .= $this->endBoundary($this->boundary[2]);
  2777. $body .= static::$LE;
  2778. $body .= $this->attachAll('attachment', $this->boundary[1]);
  2779. break;
  2780. default:
  2781. //Catch case 'plain' and case '', applies to simple `text/plain` and `text/html` body content types
  2782. //Reset the `Encoding` property in case we changed it for line length reasons
  2783. $this->Encoding = $bodyEncoding;
  2784. $body .= $this->encodeString($this->Body, $this->Encoding);
  2785. break;
  2786. }
  2787. if ($this->isError()) {
  2788. $body = '';
  2789. if ($this->exceptions) {
  2790. throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL);
  2791. }
  2792. } elseif ($this->sign_key_file) {
  2793. try {
  2794. if (!defined('PKCS7_TEXT')) {
  2795. throw new Exception($this->lang('extension_missing') . 'openssl');
  2796. }
  2797. $file = tempnam(sys_get_temp_dir(), 'srcsign');
  2798. $signed = tempnam(sys_get_temp_dir(), 'mailsign');
  2799. file_put_contents($file, $body);
  2800. //Workaround for PHP bug https://bugs.php.net/bug.php?id=69197
  2801. if (empty($this->sign_extracerts_file)) {
  2802. $sign = @openssl_pkcs7_sign(
  2803. $file,
  2804. $signed,
  2805. 'file://' . realpath($this->sign_cert_file),
  2806. ['file://' . realpath($this->sign_key_file), $this->sign_key_pass],
  2807. []
  2808. );
  2809. } else {
  2810. $sign = @openssl_pkcs7_sign(
  2811. $file,
  2812. $signed,
  2813. 'file://' . realpath($this->sign_cert_file),
  2814. ['file://' . realpath($this->sign_key_file), $this->sign_key_pass],
  2815. [],
  2816. PKCS7_DETACHED,
  2817. $this->sign_extracerts_file
  2818. );
  2819. }
  2820. @unlink($file);
  2821. if ($sign) {
  2822. $body = file_get_contents($signed);
  2823. @unlink($signed);
  2824. //The message returned by openssl contains both headers and body, so need to split them up
  2825. $parts = explode("\n\n", $body, 2);
  2826. $this->MIMEHeader .= $parts[0] . static::$LE . static::$LE;
  2827. $body = $parts[1];
  2828. } else {
  2829. @unlink($signed);
  2830. throw new Exception($this->lang('signing') . openssl_error_string());
  2831. }
  2832. } catch (Exception $exc) {
  2833. $body = '';
  2834. if ($this->exceptions) {
  2835. throw $exc;
  2836. }
  2837. }
  2838. }
  2839. return $body;
  2840. }
  2841. /**
  2842. * Get the boundaries that this message will use
  2843. * @return array
  2844. */
  2845. public function getBoundaries()
  2846. {
  2847. if (empty($this->boundary)) {
  2848. $this->setBoundaries();
  2849. }
  2850. return $this->boundary;
  2851. }
  2852. /**
  2853. * Return the start of a message boundary.
  2854. *
  2855. * @param string $boundary
  2856. * @param string $charSet
  2857. * @param string $contentType
  2858. * @param string $encoding
  2859. *
  2860. * @return string
  2861. */
  2862. protected function getBoundary($boundary, $charSet, $contentType, $encoding)
  2863. {
  2864. $result = '';
  2865. if ('' === $charSet) {
  2866. $charSet = $this->CharSet;
  2867. }
  2868. if ('' === $contentType) {
  2869. $contentType = $this->ContentType;
  2870. }
  2871. if ('' === $encoding) {
  2872. $encoding = $this->Encoding;
  2873. }
  2874. $result .= $this->textLine('--' . $boundary);
  2875. $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet);
  2876. $result .= static::$LE;
  2877. //RFC1341 part 5 says 7bit is assumed if not specified
  2878. if (static::ENCODING_7BIT !== $encoding) {
  2879. $result .= $this->headerLine('Content-Transfer-Encoding', $encoding);
  2880. }
  2881. $result .= static::$LE;
  2882. return $result;
  2883. }
  2884. /**
  2885. * Return the end of a message boundary.
  2886. *
  2887. * @param string $boundary
  2888. *
  2889. * @return string
  2890. */
  2891. protected function endBoundary($boundary)
  2892. {
  2893. return static::$LE . '--' . $boundary . '--' . static::$LE;
  2894. }
  2895. /**
  2896. * Set the message type.
  2897. * PHPMailer only supports some preset message types, not arbitrary MIME structures.
  2898. */
  2899. protected function setMessageType()
  2900. {
  2901. $type = [];
  2902. if ($this->alternativeExists()) {
  2903. $type[] = 'alt';
  2904. }
  2905. if ($this->inlineImageExists()) {
  2906. $type[] = 'inline';
  2907. }
  2908. if ($this->attachmentExists()) {
  2909. $type[] = 'attach';
  2910. }
  2911. $this->message_type = implode('_', $type);
  2912. if ('' === $this->message_type) {
  2913. //The 'plain' message_type refers to the message having a single body element, not that it is plain-text
  2914. $this->message_type = 'plain';
  2915. }
  2916. }
  2917. /**
  2918. * Format a header line.
  2919. *
  2920. * @param string $name
  2921. * @param string|int $value
  2922. *
  2923. * @return string
  2924. */
  2925. public function headerLine($name, $value)
  2926. {
  2927. return $name . ': ' . $value . static::$LE;
  2928. }
  2929. /**
  2930. * Return a formatted mail line.
  2931. *
  2932. * @param string $value
  2933. *
  2934. * @return string
  2935. */
  2936. public function textLine($value)
  2937. {
  2938. return $value . static::$LE;
  2939. }
  2940. /**
  2941. * Add an attachment from a path on the filesystem.
  2942. * Never use a user-supplied path to a file!
  2943. * Returns false if the file could not be found or read.
  2944. * Explicitly *does not* support passing URLs; PHPMailer is not an HTTP client.
  2945. * If you need to do that, fetch the resource yourself and pass it in via a local file or string.
  2946. *
  2947. * @param string $path Path to the attachment
  2948. * @param string $name Overrides the attachment name
  2949. * @param string $encoding File encoding (see $Encoding)
  2950. * @param string $type MIME type, e.g. `image/jpeg`; determined automatically from $path if not specified
  2951. * @param string $disposition Disposition to use
  2952. *
  2953. * @throws Exception
  2954. *
  2955. * @return bool
  2956. */
  2957. public function addAttachment(
  2958. $path,
  2959. $name = '',
  2960. $encoding = self::ENCODING_BASE64,
  2961. $type = '',
  2962. $disposition = 'attachment'
  2963. ) {
  2964. try {
  2965. if (!static::fileIsAccessible($path)) {
  2966. throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE);
  2967. }
  2968. //If a MIME type is not specified, try to work it out from the file name
  2969. if ('' === $type) {
  2970. $type = static::filenameToType($path);
  2971. }
  2972. $filename = (string) static::mb_pathinfo($path, PATHINFO_BASENAME);
  2973. if ('' === $name) {
  2974. $name = $filename;
  2975. }
  2976. if (!$this->validateEncoding($encoding)) {
  2977. throw new Exception($this->lang('encoding') . $encoding);
  2978. }
  2979. $this->attachment[] = [
  2980. 0 => $path,
  2981. 1 => $filename,
  2982. 2 => $name,
  2983. 3 => $encoding,
  2984. 4 => $type,
  2985. 5 => false, //isStringAttachment
  2986. 6 => $disposition,
  2987. 7 => $name,
  2988. ];
  2989. } catch (Exception $exc) {
  2990. $this->setError($exc->getMessage());
  2991. $this->edebug($exc->getMessage());
  2992. if ($this->exceptions) {
  2993. throw $exc;
  2994. }
  2995. return false;
  2996. }
  2997. return true;
  2998. }
  2999. /**
  3000. * Return the array of attachments.
  3001. *
  3002. * @return array
  3003. */
  3004. public function getAttachments()
  3005. {
  3006. return $this->attachment;
  3007. }
  3008. /**
  3009. * Attach all file, string, and binary attachments to the message.
  3010. * Returns an empty string on failure.
  3011. *
  3012. * @param string $disposition_type
  3013. * @param string $boundary
  3014. *
  3015. * @throws Exception
  3016. *
  3017. * @return string
  3018. */
  3019. protected function attachAll($disposition_type, $boundary)
  3020. {
  3021. //Return text of body
  3022. $mime = [];
  3023. $cidUniq = [];
  3024. $incl = [];
  3025. //Add all attachments
  3026. foreach ($this->attachment as $attachment) {
  3027. //Check if it is a valid disposition_filter
  3028. if ($attachment[6] === $disposition_type) {
  3029. //Check for string attachment
  3030. $string = '';
  3031. $path = '';
  3032. $bString = $attachment[5];
  3033. if ($bString) {
  3034. $string = $attachment[0];
  3035. } else {
  3036. $path = $attachment[0];
  3037. }
  3038. $inclhash = hash('sha256', serialize($attachment));
  3039. if (in_array($inclhash, $incl, true)) {
  3040. continue;
  3041. }
  3042. $incl[] = $inclhash;
  3043. $name = $attachment[2];
  3044. $encoding = $attachment[3];
  3045. $type = $attachment[4];
  3046. $disposition = $attachment[6];
  3047. $cid = $attachment[7];
  3048. if ('inline' === $disposition && array_key_exists($cid, $cidUniq)) {
  3049. continue;
  3050. }
  3051. $cidUniq[$cid] = true;
  3052. $mime[] = sprintf('--%s%s', $boundary, static::$LE);
  3053. //Only include a filename property if we have one
  3054. if (!empty($name)) {
  3055. $mime[] = sprintf(
  3056. 'Content-Type: %s; name=%s%s',
  3057. $type,
  3058. static::quotedString($this->encodeHeader($this->secureHeader($name))),
  3059. static::$LE
  3060. );
  3061. } else {
  3062. $mime[] = sprintf(
  3063. 'Content-Type: %s%s',
  3064. $type,
  3065. static::$LE
  3066. );
  3067. }
  3068. //RFC1341 part 5 says 7bit is assumed if not specified
  3069. if (static::ENCODING_7BIT !== $encoding) {
  3070. $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, static::$LE);
  3071. }
  3072. //Only set Content-IDs on inline attachments
  3073. if ((string) $cid !== '' && $disposition === 'inline') {
  3074. $mime[] = 'Content-ID: <' . $this->encodeHeader($this->secureHeader($cid)) . '>' . static::$LE;
  3075. }
  3076. //Allow for bypassing the Content-Disposition header
  3077. if (!empty($disposition)) {
  3078. $encoded_name = $this->encodeHeader($this->secureHeader($name));
  3079. if (!empty($encoded_name)) {
  3080. $mime[] = sprintf(
  3081. 'Content-Disposition: %s; filename=%s%s',
  3082. $disposition,
  3083. static::quotedString($encoded_name),
  3084. static::$LE . static::$LE
  3085. );
  3086. } else {
  3087. $mime[] = sprintf(
  3088. 'Content-Disposition: %s%s',
  3089. $disposition,
  3090. static::$LE . static::$LE
  3091. );
  3092. }
  3093. } else {
  3094. $mime[] = static::$LE;
  3095. }
  3096. //Encode as string attachment
  3097. if ($bString) {
  3098. $mime[] = $this->encodeString($string, $encoding);
  3099. } else {
  3100. $mime[] = $this->encodeFile($path, $encoding);
  3101. }
  3102. if ($this->isError()) {
  3103. return '';
  3104. }
  3105. $mime[] = static::$LE;
  3106. }
  3107. }
  3108. $mime[] = sprintf('--%s--%s', $boundary, static::$LE);
  3109. return implode('', $mime);
  3110. }
  3111. /**
  3112. * Encode a file attachment in requested format.
  3113. * Returns an empty string on failure.
  3114. *
  3115. * @param string $path The full path to the file
  3116. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  3117. *
  3118. * @return string
  3119. */
  3120. protected function encodeFile($path, $encoding = self::ENCODING_BASE64)
  3121. {
  3122. try {
  3123. if (!static::fileIsAccessible($path)) {
  3124. throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE);
  3125. }
  3126. $file_buffer = file_get_contents($path);
  3127. if (false === $file_buffer) {
  3128. throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE);
  3129. }
  3130. $file_buffer = $this->encodeString($file_buffer, $encoding);
  3131. return $file_buffer;
  3132. } catch (Exception $exc) {
  3133. $this->setError($exc->getMessage());
  3134. $this->edebug($exc->getMessage());
  3135. if ($this->exceptions) {
  3136. throw $exc;
  3137. }
  3138. return '';
  3139. }
  3140. }
  3141. /**
  3142. * Encode a string in requested format.
  3143. * Returns an empty string on failure.
  3144. *
  3145. * @param string $str The text to encode
  3146. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  3147. *
  3148. * @throws Exception
  3149. *
  3150. * @return string
  3151. */
  3152. public function encodeString($str, $encoding = self::ENCODING_BASE64)
  3153. {
  3154. $encoded = '';
  3155. switch (strtolower($encoding)) {
  3156. case static::ENCODING_BASE64:
  3157. $encoded = chunk_split(
  3158. base64_encode($str),
  3159. static::STD_LINE_LENGTH,
  3160. static::$LE
  3161. );
  3162. break;
  3163. case static::ENCODING_7BIT:
  3164. case static::ENCODING_8BIT:
  3165. $encoded = static::normalizeBreaks($str);
  3166. //Make sure it ends with a line break
  3167. if (substr($encoded, -(strlen(static::$LE))) !== static::$LE) {
  3168. $encoded .= static::$LE;
  3169. }
  3170. break;
  3171. case static::ENCODING_BINARY:
  3172. $encoded = $str;
  3173. break;
  3174. case static::ENCODING_QUOTED_PRINTABLE:
  3175. $encoded = $this->encodeQP($str);
  3176. break;
  3177. default:
  3178. $this->setError($this->lang('encoding') . $encoding);
  3179. if ($this->exceptions) {
  3180. throw new Exception($this->lang('encoding') . $encoding);
  3181. }
  3182. break;
  3183. }
  3184. return $encoded;
  3185. }
  3186. /**
  3187. * Encode a header value (not including its label) optimally.
  3188. * Picks shortest of Q, B, or none. Result includes folding if needed.
  3189. * See RFC822 definitions for phrase, comment and text positions.
  3190. *
  3191. * @param string $str The header value to encode
  3192. * @param string $position What context the string will be used in
  3193. *
  3194. * @return string
  3195. */
  3196. public function encodeHeader($str, $position = 'text')
  3197. {
  3198. $matchcount = 0;
  3199. switch (strtolower($position)) {
  3200. case 'phrase':
  3201. if (!preg_match('/[\200-\377]/', $str)) {
  3202. //Can't use addslashes as we don't know the value of magic_quotes_sybase
  3203. $encoded = addcslashes($str, "\0..\37\177\\\"");
  3204. if (($str === $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
  3205. return $encoded;
  3206. }
  3207. return "\"$encoded\"";
  3208. }
  3209. $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
  3210. break;
  3211. /* @noinspection PhpMissingBreakStatementInspection */
  3212. case 'comment':
  3213. $matchcount = preg_match_all('/[()"]/', $str, $matches);
  3214. //fallthrough
  3215. case 'text':
  3216. default:
  3217. $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
  3218. break;
  3219. }
  3220. if ($this->has8bitChars($str)) {
  3221. $charset = $this->CharSet;
  3222. } else {
  3223. $charset = static::CHARSET_ASCII;
  3224. }
  3225. //Q/B encoding adds 8 chars and the charset ("` =?<charset>?[QB]?<content>?=`").
  3226. $overhead = 8 + strlen($charset);
  3227. if ('mail' === $this->Mailer) {
  3228. $maxlen = static::MAIL_MAX_LINE_LENGTH - $overhead;
  3229. } else {
  3230. $maxlen = static::MAX_LINE_LENGTH - $overhead;
  3231. }
  3232. //Select the encoding that produces the shortest output and/or prevents corruption.
  3233. if ($matchcount > strlen($str) / 3) {
  3234. //More than 1/3 of the content needs encoding, use B-encode.
  3235. $encoding = 'B';
  3236. } elseif ($matchcount > 0) {
  3237. //Less than 1/3 of the content needs encoding, use Q-encode.
  3238. $encoding = 'Q';
  3239. } elseif (strlen($str) > $maxlen) {
  3240. //No encoding needed, but value exceeds max line length, use Q-encode to prevent corruption.
  3241. $encoding = 'Q';
  3242. } else {
  3243. //No reformatting needed
  3244. $encoding = false;
  3245. }
  3246. switch ($encoding) {
  3247. case 'B':
  3248. if ($this->hasMultiBytes($str)) {
  3249. //Use a custom function which correctly encodes and wraps long
  3250. //multibyte strings without breaking lines within a character
  3251. $encoded = $this->base64EncodeWrapMB($str, "\n");
  3252. } else {
  3253. $encoded = base64_encode($str);
  3254. $maxlen -= $maxlen % 4;
  3255. $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
  3256. }
  3257. $encoded = preg_replace('/^(.*)$/m', ' =?' . $charset . "?$encoding?\\1?=", $encoded);
  3258. break;
  3259. case 'Q':
  3260. $encoded = $this->encodeQ($str, $position);
  3261. $encoded = $this->wrapText($encoded, $maxlen, true);
  3262. $encoded = str_replace('=' . static::$LE, "\n", trim($encoded));
  3263. $encoded = preg_replace('/^(.*)$/m', ' =?' . $charset . "?$encoding?\\1?=", $encoded);
  3264. break;
  3265. default:
  3266. return $str;
  3267. }
  3268. return trim(static::normalizeBreaks($encoded));
  3269. }
  3270. /**
  3271. * Check if a string contains multi-byte characters.
  3272. *
  3273. * @param string $str multi-byte text to wrap encode
  3274. *
  3275. * @return bool
  3276. */
  3277. public function hasMultiBytes($str)
  3278. {
  3279. if (function_exists('mb_strlen')) {
  3280. return strlen($str) > mb_strlen($str, $this->CharSet);
  3281. }
  3282. //Assume no multibytes (we can't handle without mbstring functions anyway)
  3283. return false;
  3284. }
  3285. /**
  3286. * Does a string contain any 8-bit chars (in any charset)?
  3287. *
  3288. * @param string $text
  3289. *
  3290. * @return bool
  3291. */
  3292. public function has8bitChars($text)
  3293. {
  3294. return (bool) preg_match('/[\x80-\xFF]/', $text);
  3295. }
  3296. /**
  3297. * Encode and wrap long multibyte strings for mail headers
  3298. * without breaking lines within a character.
  3299. * Adapted from a function by paravoid.
  3300. *
  3301. * @see http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283
  3302. *
  3303. * @param string $str multi-byte text to wrap encode
  3304. * @param string $linebreak string to use as linefeed/end-of-line
  3305. *
  3306. * @return string
  3307. */
  3308. public function base64EncodeWrapMB($str, $linebreak = null)
  3309. {
  3310. $start = '=?' . $this->CharSet . '?B?';
  3311. $end = '?=';
  3312. $encoded = '';
  3313. if (null === $linebreak) {
  3314. $linebreak = static::$LE;
  3315. }
  3316. $mb_length = mb_strlen($str, $this->CharSet);
  3317. //Each line must have length <= 75, including $start and $end
  3318. $length = 75 - strlen($start) - strlen($end);
  3319. //Average multi-byte ratio
  3320. $ratio = $mb_length / strlen($str);
  3321. //Base64 has a 4:3 ratio
  3322. $avgLength = floor($length * $ratio * .75);
  3323. $offset = 0;
  3324. for ($i = 0; $i < $mb_length; $i += $offset) {
  3325. $lookBack = 0;
  3326. do {
  3327. $offset = $avgLength - $lookBack;
  3328. $chunk = mb_substr($str, $i, $offset, $this->CharSet);
  3329. $chunk = base64_encode($chunk);
  3330. ++$lookBack;
  3331. } while (strlen($chunk) > $length);
  3332. $encoded .= $chunk . $linebreak;
  3333. }
  3334. //Chomp the last linefeed
  3335. return substr($encoded, 0, -strlen($linebreak));
  3336. }
  3337. /**
  3338. * Encode a string in quoted-printable format.
  3339. * According to RFC2045 section 6.7.
  3340. *
  3341. * @param string $string The text to encode
  3342. *
  3343. * @return string
  3344. */
  3345. public function encodeQP($string)
  3346. {
  3347. return static::normalizeBreaks(quoted_printable_encode($string));
  3348. }
  3349. /**
  3350. * Encode a string using Q encoding.
  3351. *
  3352. * @see http://tools.ietf.org/html/rfc2047#section-4.2
  3353. *
  3354. * @param string $str the text to encode
  3355. * @param string $position Where the text is going to be used, see the RFC for what that means
  3356. *
  3357. * @return string
  3358. */
  3359. public function encodeQ($str, $position = 'text')
  3360. {
  3361. //There should not be any EOL in the string
  3362. $pattern = '';
  3363. $encoded = str_replace(["\r", "\n"], '', $str);
  3364. switch (strtolower($position)) {
  3365. case 'phrase':
  3366. //RFC 2047 section 5.3
  3367. $pattern = '^A-Za-z0-9!*+\/ -';
  3368. break;
  3369. /*
  3370. * RFC 2047 section 5.2.
  3371. * Build $pattern without including delimiters and []
  3372. */
  3373. /* @noinspection PhpMissingBreakStatementInspection */
  3374. case 'comment':
  3375. $pattern = '\(\)"';
  3376. /* Intentional fall through */
  3377. case 'text':
  3378. default:
  3379. //RFC 2047 section 5.1
  3380. //Replace every high ascii, control, =, ? and _ characters
  3381. $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern;
  3382. break;
  3383. }
  3384. $matches = [];
  3385. if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
  3386. //If the string contains an '=', make sure it's the first thing we replace
  3387. //so as to avoid double-encoding
  3388. $eqkey = array_search('=', $matches[0], true);
  3389. if (false !== $eqkey) {
  3390. unset($matches[0][$eqkey]);
  3391. array_unshift($matches[0], '=');
  3392. }
  3393. foreach (array_unique($matches[0]) as $char) {
  3394. $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
  3395. }
  3396. }
  3397. //Replace spaces with _ (more readable than =20)
  3398. //RFC 2047 section 4.2(2)
  3399. return str_replace(' ', '_', $encoded);
  3400. }
  3401. /**
  3402. * Add a string or binary attachment (non-filesystem).
  3403. * This method can be used to attach ascii or binary data,
  3404. * such as a BLOB record from a database.
  3405. *
  3406. * @param string $string String attachment data
  3407. * @param string $filename Name of the attachment
  3408. * @param string $encoding File encoding (see $Encoding)
  3409. * @param string $type File extension (MIME) type
  3410. * @param string $disposition Disposition to use
  3411. *
  3412. * @throws Exception
  3413. *
  3414. * @return bool True on successfully adding an attachment
  3415. */
  3416. public function addStringAttachment(
  3417. $string,
  3418. $filename,
  3419. $encoding = self::ENCODING_BASE64,
  3420. $type = '',
  3421. $disposition = 'attachment'
  3422. ) {
  3423. try {
  3424. //If a MIME type is not specified, try to work it out from the file name
  3425. if ('' === $type) {
  3426. $type = static::filenameToType($filename);
  3427. }
  3428. if (!$this->validateEncoding($encoding)) {
  3429. throw new Exception($this->lang('encoding') . $encoding);
  3430. }
  3431. //Append to $attachment array
  3432. $this->attachment[] = [
  3433. 0 => $string,
  3434. 1 => $filename,
  3435. 2 => static::mb_pathinfo($filename, PATHINFO_BASENAME),
  3436. 3 => $encoding,
  3437. 4 => $type,
  3438. 5 => true, //isStringAttachment
  3439. 6 => $disposition,
  3440. 7 => 0,
  3441. ];
  3442. } catch (Exception $exc) {
  3443. $this->setError($exc->getMessage());
  3444. $this->edebug($exc->getMessage());
  3445. if ($this->exceptions) {
  3446. throw $exc;
  3447. }
  3448. return false;
  3449. }
  3450. return true;
  3451. }
  3452. /**
  3453. * Add an embedded (inline) attachment from a file.
  3454. * This can include images, sounds, and just about any other document type.
  3455. * These differ from 'regular' attachments in that they are intended to be
  3456. * displayed inline with the message, not just attached for download.
  3457. * This is used in HTML messages that embed the images
  3458. * the HTML refers to using the `$cid` value in `img` tags, for example `<img src="cid:mylogo">`.
  3459. * Never use a user-supplied path to a file!
  3460. *
  3461. * @param string $path Path to the attachment
  3462. * @param string $cid Content ID of the attachment; Use this to reference
  3463. * the content when using an embedded image in HTML
  3464. * @param string $name Overrides the attachment filename
  3465. * @param string $encoding File encoding (see $Encoding) defaults to `base64`
  3466. * @param string $type File MIME type (by default mapped from the `$path` filename's extension)
  3467. * @param string $disposition Disposition to use: `inline` (default) or `attachment`
  3468. * (unlikely you want this – {@see `addAttachment()`} instead)
  3469. *
  3470. * @return bool True on successfully adding an attachment
  3471. * @throws Exception
  3472. *
  3473. */
  3474. public function addEmbeddedImage(
  3475. $path,
  3476. $cid,
  3477. $name = '',
  3478. $encoding = self::ENCODING_BASE64,
  3479. $type = '',
  3480. $disposition = 'inline'
  3481. ) {
  3482. try {
  3483. if (!static::fileIsAccessible($path)) {
  3484. throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE);
  3485. }
  3486. //If a MIME type is not specified, try to work it out from the file name
  3487. if ('' === $type) {
  3488. $type = static::filenameToType($path);
  3489. }
  3490. if (!$this->validateEncoding($encoding)) {
  3491. throw new Exception($this->lang('encoding') . $encoding);
  3492. }
  3493. $filename = (string) static::mb_pathinfo($path, PATHINFO_BASENAME);
  3494. if ('' === $name) {
  3495. $name = $filename;
  3496. }
  3497. //Append to $attachment array
  3498. $this->attachment[] = [
  3499. 0 => $path,
  3500. 1 => $filename,
  3501. 2 => $name,
  3502. 3 => $encoding,
  3503. 4 => $type,
  3504. 5 => false, //isStringAttachment
  3505. 6 => $disposition,
  3506. 7 => $cid,
  3507. ];
  3508. } catch (Exception $exc) {
  3509. $this->setError($exc->getMessage());
  3510. $this->edebug($exc->getMessage());
  3511. if ($this->exceptions) {
  3512. throw $exc;
  3513. }
  3514. return false;
  3515. }
  3516. return true;
  3517. }
  3518. /**
  3519. * Add an embedded stringified attachment.
  3520. * This can include images, sounds, and just about any other document type.
  3521. * If your filename doesn't contain an extension, be sure to set the $type to an appropriate MIME type.
  3522. *
  3523. * @param string $string The attachment binary data
  3524. * @param string $cid Content ID of the attachment; Use this to reference
  3525. * the content when using an embedded image in HTML
  3526. * @param string $name A filename for the attachment. If this contains an extension,
  3527. * PHPMailer will attempt to set a MIME type for the attachment.
  3528. * For example 'file.jpg' would get an 'image/jpeg' MIME type.
  3529. * @param string $encoding File encoding (see $Encoding), defaults to 'base64'
  3530. * @param string $type MIME type - will be used in preference to any automatically derived type
  3531. * @param string $disposition Disposition to use
  3532. *
  3533. * @throws Exception
  3534. *
  3535. * @return bool True on successfully adding an attachment
  3536. */
  3537. public function addStringEmbeddedImage(
  3538. $string,
  3539. $cid,
  3540. $name = '',
  3541. $encoding = self::ENCODING_BASE64,
  3542. $type = '',
  3543. $disposition = 'inline'
  3544. ) {
  3545. try {
  3546. //If a MIME type is not specified, try to work it out from the name
  3547. if ('' === $type && !empty($name)) {
  3548. $type = static::filenameToType($name);
  3549. }
  3550. if (!$this->validateEncoding($encoding)) {
  3551. throw new Exception($this->lang('encoding') . $encoding);
  3552. }
  3553. //Append to $attachment array
  3554. $this->attachment[] = [
  3555. 0 => $string,
  3556. 1 => $name,
  3557. 2 => $name,
  3558. 3 => $encoding,
  3559. 4 => $type,
  3560. 5 => true, //isStringAttachment
  3561. 6 => $disposition,
  3562. 7 => $cid,
  3563. ];
  3564. } catch (Exception $exc) {
  3565. $this->setError($exc->getMessage());
  3566. $this->edebug($exc->getMessage());
  3567. if ($this->exceptions) {
  3568. throw $exc;
  3569. }
  3570. return false;
  3571. }
  3572. return true;
  3573. }
  3574. /**
  3575. * Validate encodings.
  3576. *
  3577. * @param string $encoding
  3578. *
  3579. * @return bool
  3580. */
  3581. protected function validateEncoding($encoding)
  3582. {
  3583. return in_array(
  3584. $encoding,
  3585. [
  3586. self::ENCODING_7BIT,
  3587. self::ENCODING_QUOTED_PRINTABLE,
  3588. self::ENCODING_BASE64,
  3589. self::ENCODING_8BIT,
  3590. self::ENCODING_BINARY,
  3591. ],
  3592. true
  3593. );
  3594. }
  3595. /**
  3596. * Check if an embedded attachment is present with this cid.
  3597. *
  3598. * @param string $cid
  3599. *
  3600. * @return bool
  3601. */
  3602. protected function cidExists($cid)
  3603. {
  3604. foreach ($this->attachment as $attachment) {
  3605. if ('inline' === $attachment[6] && $cid === $attachment[7]) {
  3606. return true;
  3607. }
  3608. }
  3609. return false;
  3610. }
  3611. /**
  3612. * Check if an inline attachment is present.
  3613. *
  3614. * @return bool
  3615. */
  3616. public function inlineImageExists()
  3617. {
  3618. foreach ($this->attachment as $attachment) {
  3619. if ('inline' === $attachment[6]) {
  3620. return true;
  3621. }
  3622. }
  3623. return false;
  3624. }
  3625. /**
  3626. * Check if an attachment (non-inline) is present.
  3627. *
  3628. * @return bool
  3629. */
  3630. public function attachmentExists()
  3631. {
  3632. foreach ($this->attachment as $attachment) {
  3633. if ('attachment' === $attachment[6]) {
  3634. return true;
  3635. }
  3636. }
  3637. return false;
  3638. }
  3639. /**
  3640. * Check if this message has an alternative body set.
  3641. *
  3642. * @return bool
  3643. */
  3644. public function alternativeExists()
  3645. {
  3646. return !empty($this->AltBody);
  3647. }
  3648. /**
  3649. * Clear queued addresses of given kind.
  3650. *
  3651. * @param string $kind 'to', 'cc', or 'bcc'
  3652. */
  3653. public function clearQueuedAddresses($kind)
  3654. {
  3655. $this->RecipientsQueue = array_filter(
  3656. $this->RecipientsQueue,
  3657. static function ($params) use ($kind) {
  3658. return $params[0] !== $kind;
  3659. }
  3660. );
  3661. }
  3662. /**
  3663. * Clear all To recipients.
  3664. */
  3665. public function clearAddresses()
  3666. {
  3667. foreach ($this->to as $to) {
  3668. unset($this->all_recipients[strtolower($to[0])]);
  3669. }
  3670. $this->to = [];
  3671. $this->clearQueuedAddresses('to');
  3672. }
  3673. /**
  3674. * Clear all CC recipients.
  3675. */
  3676. public function clearCCs()
  3677. {
  3678. foreach ($this->cc as $cc) {
  3679. unset($this->all_recipients[strtolower($cc[0])]);
  3680. }
  3681. $this->cc = [];
  3682. $this->clearQueuedAddresses('cc');
  3683. }
  3684. /**
  3685. * Clear all BCC recipients.
  3686. */
  3687. public function clearBCCs()
  3688. {
  3689. foreach ($this->bcc as $bcc) {
  3690. unset($this->all_recipients[strtolower($bcc[0])]);
  3691. }
  3692. $this->bcc = [];
  3693. $this->clearQueuedAddresses('bcc');
  3694. }
  3695. /**
  3696. * Clear all ReplyTo recipients.
  3697. */
  3698. public function clearReplyTos()
  3699. {
  3700. $this->ReplyTo = [];
  3701. $this->ReplyToQueue = [];
  3702. }
  3703. /**
  3704. * Clear all recipient types.
  3705. */
  3706. public function clearAllRecipients()
  3707. {
  3708. $this->to = [];
  3709. $this->cc = [];
  3710. $this->bcc = [];
  3711. $this->all_recipients = [];
  3712. $this->RecipientsQueue = [];
  3713. }
  3714. /**
  3715. * Clear all filesystem, string, and binary attachments.
  3716. */
  3717. public function clearAttachments()
  3718. {
  3719. $this->attachment = [];
  3720. }
  3721. /**
  3722. * Clear all custom headers.
  3723. */
  3724. public function clearCustomHeaders()
  3725. {
  3726. $this->CustomHeader = [];
  3727. }
  3728. /**
  3729. * Add an error message to the error container.
  3730. *
  3731. * @param string $msg
  3732. */
  3733. protected function setError($msg)
  3734. {
  3735. ++$this->error_count;
  3736. if ('smtp' === $this->Mailer && null !== $this->smtp) {
  3737. $lasterror = $this->smtp->getError();
  3738. if (!empty($lasterror['error'])) {
  3739. $msg .= $this->lang('smtp_error') . $lasterror['error'];
  3740. if (!empty($lasterror['detail'])) {
  3741. $msg .= ' ' . $this->lang('smtp_detail') . $lasterror['detail'];
  3742. }
  3743. if (!empty($lasterror['smtp_code'])) {
  3744. $msg .= ' ' . $this->lang('smtp_code') . $lasterror['smtp_code'];
  3745. }
  3746. if (!empty($lasterror['smtp_code_ex'])) {
  3747. $msg .= ' ' . $this->lang('smtp_code_ex') . $lasterror['smtp_code_ex'];
  3748. }
  3749. }
  3750. }
  3751. $this->ErrorInfo = $msg;
  3752. }
  3753. /**
  3754. * Return an RFC 822 formatted date.
  3755. *
  3756. * @return string
  3757. */
  3758. public static function rfcDate()
  3759. {
  3760. //Set the time zone to whatever the default is to avoid 500 errors
  3761. //Will default to UTC if it's not set properly in php.ini
  3762. date_default_timezone_set(@date_default_timezone_get());
  3763. return date('D, j M Y H:i:s O');
  3764. }
  3765. /**
  3766. * Get the server hostname.
  3767. * Returns 'localhost.localdomain' if unknown.
  3768. *
  3769. * @return string
  3770. */
  3771. protected function serverHostname()
  3772. {
  3773. $result = '';
  3774. if (!empty($this->Hostname)) {
  3775. $result = $this->Hostname;
  3776. } elseif (isset($_SERVER) && array_key_exists('SERVER_NAME', $_SERVER)) {
  3777. $result = $_SERVER['SERVER_NAME'];
  3778. } elseif (function_exists('gethostname') && gethostname() !== false) {
  3779. $result = gethostname();
  3780. } elseif (php_uname('n') !== false) {
  3781. $result = php_uname('n');
  3782. }
  3783. if (!static::isValidHost($result)) {
  3784. return 'localhost.localdomain';
  3785. }
  3786. return $result;
  3787. }
  3788. /**
  3789. * Validate whether a string contains a valid value to use as a hostname or IP address.
  3790. * IPv6 addresses must include [], e.g. `[::1]`, not just `::1`.
  3791. *
  3792. * @param string $host The host name or IP address to check
  3793. *
  3794. * @return bool
  3795. */
  3796. public static function isValidHost($host)
  3797. {
  3798. //Simple syntax limits
  3799. if (
  3800. empty($host)
  3801. || !is_string($host)
  3802. || strlen($host) > 256
  3803. || !preg_match('/^([a-zA-Z\d.-]*|\[[a-fA-F\d:]+\])$/', $host)
  3804. ) {
  3805. return false;
  3806. }
  3807. //Looks like a bracketed IPv6 address
  3808. if (strlen($host) > 2 && substr($host, 0, 1) === '[' && substr($host, -1, 1) === ']') {
  3809. return filter_var(substr($host, 1, -1), FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false;
  3810. }
  3811. //If removing all the dots results in a numeric string, it must be an IPv4 address.
  3812. //Need to check this first because otherwise things like `999.0.0.0` are considered valid host names
  3813. if (is_numeric(str_replace('.', '', $host))) {
  3814. //Is it a valid IPv4 address?
  3815. return filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false;
  3816. }
  3817. //Is it a syntactically valid hostname (when embeded in a URL)?
  3818. return filter_var('http://' . $host, FILTER_VALIDATE_URL) !== false;
  3819. }
  3820. /**
  3821. * Get an error message in the current language.
  3822. *
  3823. * @param string $key
  3824. *
  3825. * @return string
  3826. */
  3827. protected function lang($key)
  3828. {
  3829. if (count($this->language) < 1) {
  3830. $this->setLanguage(); //Set the default language
  3831. }
  3832. if (array_key_exists($key, $this->language)) {
  3833. if ('smtp_connect_failed' === $key) {
  3834. //Include a link to troubleshooting docs on SMTP connection failure.
  3835. //This is by far the biggest cause of support questions
  3836. //but it's usually not PHPMailer's fault.
  3837. return $this->language[$key] . ' https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting';
  3838. }
  3839. return $this->language[$key];
  3840. }
  3841. //Return the key as a fallback
  3842. return $key;
  3843. }
  3844. /**
  3845. * Build an error message starting with a generic one and adding details if possible.
  3846. *
  3847. * @param string $base_key
  3848. * @return string
  3849. */
  3850. private function getSmtpErrorMessage($base_key)
  3851. {
  3852. $message = $this->lang($base_key);
  3853. $error = $this->smtp->getError();
  3854. if (!empty($error['error'])) {
  3855. $message .= ' ' . $error['error'];
  3856. if (!empty($error['detail'])) {
  3857. $message .= ' ' . $error['detail'];
  3858. }
  3859. }
  3860. return $message;
  3861. }
  3862. /**
  3863. * Check if an error occurred.
  3864. *
  3865. * @return bool True if an error did occur
  3866. */
  3867. public function isError()
  3868. {
  3869. return $this->error_count > 0;
  3870. }
  3871. /**
  3872. * Add a custom header.
  3873. * $name value can be overloaded to contain
  3874. * both header name and value (name:value).
  3875. *
  3876. * @param string $name Custom header name
  3877. * @param string|null $value Header value
  3878. *
  3879. * @return bool True if a header was set successfully
  3880. * @throws Exception
  3881. */
  3882. public function addCustomHeader($name, $value = null)
  3883. {
  3884. if (null === $value && strpos($name, ':') !== false) {
  3885. //Value passed in as name:value
  3886. list($name, $value) = explode(':', $name, 2);
  3887. }
  3888. $name = trim($name);
  3889. $value = (null === $value) ? '' : trim($value);
  3890. //Ensure name is not empty, and that neither name nor value contain line breaks
  3891. if (empty($name) || strpbrk($name . $value, "\r\n") !== false) {
  3892. if ($this->exceptions) {
  3893. throw new Exception($this->lang('invalid_header'));
  3894. }
  3895. return false;
  3896. }
  3897. $this->CustomHeader[] = [$name, $value];
  3898. return true;
  3899. }
  3900. /**
  3901. * Returns all custom headers.
  3902. *
  3903. * @return array
  3904. */
  3905. public function getCustomHeaders()
  3906. {
  3907. return $this->CustomHeader;
  3908. }
  3909. /**
  3910. * Create a message body from an HTML string.
  3911. * Automatically inlines images and creates a plain-text version by converting the HTML,
  3912. * overwriting any existing values in Body and AltBody.
  3913. * Do not source $message content from user input!
  3914. * $basedir is prepended when handling relative URLs, e.g. <img src="/images/a.png"> and must not be empty
  3915. * will look for an image file in $basedir/images/a.png and convert it to inline.
  3916. * If you don't provide a $basedir, relative paths will be left untouched (and thus probably break in email)
  3917. * Converts data-uri images into embedded attachments.
  3918. * If you don't want to apply these transformations to your HTML, just set Body and AltBody directly.
  3919. *
  3920. * @param string $message HTML message string
  3921. * @param string $basedir Absolute path to a base directory to prepend to relative paths to images
  3922. * @param bool|callable $advanced Whether to use the internal HTML to text converter
  3923. * or your own custom converter
  3924. * @return string The transformed message body
  3925. *
  3926. * @throws Exception
  3927. *
  3928. * @see PHPMailer::html2text()
  3929. */
  3930. public function msgHTML($message, $basedir = '', $advanced = false)
  3931. {
  3932. preg_match_all('/(?<!-)(src|background)=["\'](.*)["\']/Ui', $message, $images);
  3933. if (array_key_exists(2, $images)) {
  3934. if (strlen($basedir) > 1 && '/' !== substr($basedir, -1)) {
  3935. //Ensure $basedir has a trailing /
  3936. $basedir .= '/';
  3937. }
  3938. foreach ($images[2] as $imgindex => $url) {
  3939. //Convert data URIs into embedded images
  3940. //e.g. "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
  3941. $match = [];
  3942. if (preg_match('#^data:(image/(?:jpe?g|gif|png));?(base64)?,(.+)#', $url, $match)) {
  3943. if (count($match) === 4 && static::ENCODING_BASE64 === $match[2]) {
  3944. $data = base64_decode($match[3]);
  3945. } elseif ('' === $match[2]) {
  3946. $data = rawurldecode($match[3]);
  3947. } else {
  3948. //Not recognised so leave it alone
  3949. continue;
  3950. }
  3951. //Hash the decoded data, not the URL, so that the same data-URI image used in multiple places
  3952. //will only be embedded once, even if it used a different encoding
  3953. $cid = substr(hash('sha256', $data), 0, 32) . '@phpmailer.0'; //RFC2392 S 2
  3954. if (!$this->cidExists($cid)) {
  3955. $this->addStringEmbeddedImage(
  3956. $data,
  3957. $cid,
  3958. 'embed' . $imgindex,
  3959. static::ENCODING_BASE64,
  3960. $match[1]
  3961. );
  3962. }
  3963. $message = str_replace(
  3964. $images[0][$imgindex],
  3965. $images[1][$imgindex] . '="cid:' . $cid . '"',
  3966. $message
  3967. );
  3968. continue;
  3969. }
  3970. if (
  3971. //Only process relative URLs if a basedir is provided (i.e. no absolute local paths)
  3972. !empty($basedir)
  3973. //Ignore URLs containing parent dir traversal (..)
  3974. && (strpos($url, '..') === false)
  3975. //Do not change urls that are already inline images
  3976. && 0 !== strpos($url, 'cid:')
  3977. //Do not change absolute URLs, including anonymous protocol
  3978. && !preg_match('#^[a-z][a-z0-9+.-]*:?//#i', $url)
  3979. ) {
  3980. $filename = static::mb_pathinfo($url, PATHINFO_BASENAME);
  3981. $directory = dirname($url);
  3982. if ('.' === $directory) {
  3983. $directory = '';
  3984. }
  3985. //RFC2392 S 2
  3986. $cid = substr(hash('sha256', $url), 0, 32) . '@phpmailer.0';
  3987. if (strlen($basedir) > 1 && '/' !== substr($basedir, -1)) {
  3988. $basedir .= '/';
  3989. }
  3990. if (strlen($directory) > 1 && '/' !== substr($directory, -1)) {
  3991. $directory .= '/';
  3992. }
  3993. if (
  3994. $this->addEmbeddedImage(
  3995. $basedir . $directory . $filename,
  3996. $cid,
  3997. $filename,
  3998. static::ENCODING_BASE64,
  3999. static::_mime_types((string) static::mb_pathinfo($filename, PATHINFO_EXTENSION))
  4000. )
  4001. ) {
  4002. $message = preg_replace(
  4003. '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui',
  4004. $images[1][$imgindex] . '="cid:' . $cid . '"',
  4005. $message
  4006. );
  4007. }
  4008. }
  4009. }
  4010. }
  4011. $this->isHTML();
  4012. //Convert all message body line breaks to LE, makes quoted-printable encoding work much better
  4013. $this->Body = static::normalizeBreaks($message);
  4014. $this->AltBody = static::normalizeBreaks($this->html2text($message, $advanced));
  4015. if (!$this->alternativeExists()) {
  4016. $this->AltBody = 'This is an HTML-only message. To view it, activate HTML in your email application.'
  4017. . static::$LE;
  4018. }
  4019. return $this->Body;
  4020. }
  4021. /**
  4022. * Convert an HTML string into plain text.
  4023. * This is used by msgHTML().
  4024. * Note - older versions of this function used a bundled advanced converter
  4025. * which was removed for license reasons in #232.
  4026. * Example usage:
  4027. *
  4028. * ```php
  4029. * //Use default conversion
  4030. * $plain = $mail->html2text($html);
  4031. * //Use your own custom converter
  4032. * $plain = $mail->html2text($html, function($html) {
  4033. * $converter = new MyHtml2text($html);
  4034. * return $converter->get_text();
  4035. * });
  4036. * ```
  4037. *
  4038. * @param string $html The HTML text to convert
  4039. * @param bool|callable $advanced Any boolean value to use the internal converter,
  4040. * or provide your own callable for custom conversion.
  4041. * *Never* pass user-supplied data into this parameter
  4042. *
  4043. * @return string
  4044. */
  4045. public function html2text($html, $advanced = false)
  4046. {
  4047. if (is_callable($advanced)) {
  4048. return call_user_func($advanced, $html);
  4049. }
  4050. return html_entity_decode(
  4051. trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))),
  4052. ENT_QUOTES,
  4053. $this->CharSet
  4054. );
  4055. }
  4056. /**
  4057. * Get the MIME type for a file extension.
  4058. *
  4059. * @param string $ext File extension
  4060. *
  4061. * @return string MIME type of file
  4062. */
  4063. public static function _mime_types($ext = '')
  4064. {
  4065. $mimes = [
  4066. 'xl' => 'application/excel',
  4067. 'js' => 'application/javascript',
  4068. 'hqx' => 'application/mac-binhex40',
  4069. 'cpt' => 'application/mac-compactpro',
  4070. 'bin' => 'application/macbinary',
  4071. 'doc' => 'application/msword',
  4072. 'word' => 'application/msword',
  4073. 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  4074. 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
  4075. 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
  4076. 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
  4077. 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  4078. 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
  4079. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  4080. 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
  4081. 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
  4082. 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
  4083. 'class' => 'application/octet-stream',
  4084. 'dll' => 'application/octet-stream',
  4085. 'dms' => 'application/octet-stream',
  4086. 'exe' => 'application/octet-stream',
  4087. 'lha' => 'application/octet-stream',
  4088. 'lzh' => 'application/octet-stream',
  4089. 'psd' => 'application/octet-stream',
  4090. 'sea' => 'application/octet-stream',
  4091. 'so' => 'application/octet-stream',
  4092. 'oda' => 'application/oda',
  4093. 'pdf' => 'application/pdf',
  4094. 'ai' => 'application/postscript',
  4095. 'eps' => 'application/postscript',
  4096. 'ps' => 'application/postscript',
  4097. 'smi' => 'application/smil',
  4098. 'smil' => 'application/smil',
  4099. 'mif' => 'application/vnd.mif',
  4100. 'xls' => 'application/vnd.ms-excel',
  4101. 'ppt' => 'application/vnd.ms-powerpoint',
  4102. 'wbxml' => 'application/vnd.wap.wbxml',
  4103. 'wmlc' => 'application/vnd.wap.wmlc',
  4104. 'dcr' => 'application/x-director',
  4105. 'dir' => 'application/x-director',
  4106. 'dxr' => 'application/x-director',
  4107. 'dvi' => 'application/x-dvi',
  4108. 'gtar' => 'application/x-gtar',
  4109. 'php3' => 'application/x-httpd-php',
  4110. 'php4' => 'application/x-httpd-php',
  4111. 'php' => 'application/x-httpd-php',
  4112. 'phtml' => 'application/x-httpd-php',
  4113. 'phps' => 'application/x-httpd-php-source',
  4114. 'swf' => 'application/x-shockwave-flash',
  4115. 'sit' => 'application/x-stuffit',
  4116. 'tar' => 'application/x-tar',
  4117. 'tgz' => 'application/x-tar',
  4118. 'xht' => 'application/xhtml+xml',
  4119. 'xhtml' => 'application/xhtml+xml',
  4120. 'zip' => 'application/zip',
  4121. 'mid' => 'audio/midi',
  4122. 'midi' => 'audio/midi',
  4123. 'mp2' => 'audio/mpeg',
  4124. 'mp3' => 'audio/mpeg',
  4125. 'm4a' => 'audio/mp4',
  4126. 'mpga' => 'audio/mpeg',
  4127. 'aif' => 'audio/x-aiff',
  4128. 'aifc' => 'audio/x-aiff',
  4129. 'aiff' => 'audio/x-aiff',
  4130. 'ram' => 'audio/x-pn-realaudio',
  4131. 'rm' => 'audio/x-pn-realaudio',
  4132. 'rpm' => 'audio/x-pn-realaudio-plugin',
  4133. 'ra' => 'audio/x-realaudio',
  4134. 'wav' => 'audio/x-wav',
  4135. 'mka' => 'audio/x-matroska',
  4136. 'bmp' => 'image/bmp',
  4137. 'gif' => 'image/gif',
  4138. 'jpeg' => 'image/jpeg',
  4139. 'jpe' => 'image/jpeg',
  4140. 'jpg' => 'image/jpeg',
  4141. 'png' => 'image/png',
  4142. 'tiff' => 'image/tiff',
  4143. 'tif' => 'image/tiff',
  4144. 'webp' => 'image/webp',
  4145. 'avif' => 'image/avif',
  4146. 'heif' => 'image/heif',
  4147. 'heifs' => 'image/heif-sequence',
  4148. 'heic' => 'image/heic',
  4149. 'heics' => 'image/heic-sequence',
  4150. 'eml' => 'message/rfc822',
  4151. 'css' => 'text/css',
  4152. 'html' => 'text/html',
  4153. 'htm' => 'text/html',
  4154. 'shtml' => 'text/html',
  4155. 'log' => 'text/plain',
  4156. 'text' => 'text/plain',
  4157. 'txt' => 'text/plain',
  4158. 'rtx' => 'text/richtext',
  4159. 'rtf' => 'text/rtf',
  4160. 'vcf' => 'text/vcard',
  4161. 'vcard' => 'text/vcard',
  4162. 'ics' => 'text/calendar',
  4163. 'xml' => 'text/xml',
  4164. 'xsl' => 'text/xml',
  4165. 'csv' => 'text/csv',
  4166. 'wmv' => 'video/x-ms-wmv',
  4167. 'mpeg' => 'video/mpeg',
  4168. 'mpe' => 'video/mpeg',
  4169. 'mpg' => 'video/mpeg',
  4170. 'mp4' => 'video/mp4',
  4171. 'm4v' => 'video/mp4',
  4172. 'mov' => 'video/quicktime',
  4173. 'qt' => 'video/quicktime',
  4174. 'rv' => 'video/vnd.rn-realvideo',
  4175. 'avi' => 'video/x-msvideo',
  4176. 'movie' => 'video/x-sgi-movie',
  4177. 'webm' => 'video/webm',
  4178. 'mkv' => 'video/x-matroska',
  4179. ];
  4180. $ext = strtolower($ext);
  4181. if (array_key_exists($ext, $mimes)) {
  4182. return $mimes[$ext];
  4183. }
  4184. return 'application/octet-stream';
  4185. }
  4186. /**
  4187. * Map a file name to a MIME type.
  4188. * Defaults to 'application/octet-stream', i.e.. arbitrary binary data.
  4189. *
  4190. * @param string $filename A file name or full path, does not need to exist as a file
  4191. *
  4192. * @return string
  4193. */
  4194. public static function filenameToType($filename)
  4195. {
  4196. //In case the path is a URL, strip any query string before getting extension
  4197. $qpos = strpos($filename, '?');
  4198. if (false !== $qpos) {
  4199. $filename = substr($filename, 0, $qpos);
  4200. }
  4201. $ext = static::mb_pathinfo($filename, PATHINFO_EXTENSION);
  4202. return static::_mime_types($ext);
  4203. }
  4204. /**
  4205. * Multi-byte-safe pathinfo replacement.
  4206. * Drop-in replacement for pathinfo(), but multibyte- and cross-platform-safe.
  4207. *
  4208. * @see http://www.php.net/manual/en/function.pathinfo.php#107461
  4209. *
  4210. * @param string $path A filename or path, does not need to exist as a file
  4211. * @param int|string $options Either a PATHINFO_* constant,
  4212. * or a string name to return only the specified piece
  4213. *
  4214. * @return string|array
  4215. */
  4216. public static function mb_pathinfo($path, $options = null)
  4217. {
  4218. $ret = ['dirname' => '', 'basename' => '', 'extension' => '', 'filename' => ''];
  4219. $pathinfo = [];
  4220. if (preg_match('#^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^.\\\\/]+?)|))[\\\\/.]*$#m', $path, $pathinfo)) {
  4221. if (array_key_exists(1, $pathinfo)) {
  4222. $ret['dirname'] = $pathinfo[1];
  4223. }
  4224. if (array_key_exists(2, $pathinfo)) {
  4225. $ret['basename'] = $pathinfo[2];
  4226. }
  4227. if (array_key_exists(5, $pathinfo)) {
  4228. $ret['extension'] = $pathinfo[5];
  4229. }
  4230. if (array_key_exists(3, $pathinfo)) {
  4231. $ret['filename'] = $pathinfo[3];
  4232. }
  4233. }
  4234. switch ($options) {
  4235. case PATHINFO_DIRNAME:
  4236. case 'dirname':
  4237. return $ret['dirname'];
  4238. case PATHINFO_BASENAME:
  4239. case 'basename':
  4240. return $ret['basename'];
  4241. case PATHINFO_EXTENSION:
  4242. case 'extension':
  4243. return $ret['extension'];
  4244. case PATHINFO_FILENAME:
  4245. case 'filename':
  4246. return $ret['filename'];
  4247. default:
  4248. return $ret;
  4249. }
  4250. }
  4251. /**
  4252. * Set or reset instance properties.
  4253. * You should avoid this function - it's more verbose, less efficient, more error-prone and
  4254. * harder to debug than setting properties directly.
  4255. * Usage Example:
  4256. * `$mail->set('SMTPSecure', static::ENCRYPTION_STARTTLS);`
  4257. * is the same as:
  4258. * `$mail->SMTPSecure = static::ENCRYPTION_STARTTLS;`.
  4259. *
  4260. * @param string $name The property name to set
  4261. * @param mixed $value The value to set the property to
  4262. *
  4263. * @return bool
  4264. */
  4265. public function set($name, $value = '')
  4266. {
  4267. if (property_exists($this, $name)) {
  4268. $this->{$name} = $value;
  4269. return true;
  4270. }
  4271. $this->setError($this->lang('variable_set') . $name);
  4272. return false;
  4273. }
  4274. /**
  4275. * Strip newlines to prevent header injection.
  4276. *
  4277. * @param string $str
  4278. *
  4279. * @return string
  4280. */
  4281. public function secureHeader($str)
  4282. {
  4283. return trim(str_replace(["\r", "\n"], '', $str));
  4284. }
  4285. /**
  4286. * Normalize line breaks in a string.
  4287. * Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format.
  4288. * Defaults to CRLF (for message bodies) and preserves consecutive breaks.
  4289. *
  4290. * @param string $text
  4291. * @param string $breaktype What kind of line break to use; defaults to static::$LE
  4292. *
  4293. * @return string
  4294. */
  4295. public static function normalizeBreaks($text, $breaktype = null)
  4296. {
  4297. if (null === $breaktype) {
  4298. $breaktype = static::$LE;
  4299. }
  4300. //Normalise to \n
  4301. $text = str_replace([self::CRLF, "\r"], "\n", $text);
  4302. //Now convert LE as needed
  4303. if ("\n" !== $breaktype) {
  4304. $text = str_replace("\n", $breaktype, $text);
  4305. }
  4306. return $text;
  4307. }
  4308. /**
  4309. * Remove trailing whitespace from a string.
  4310. *
  4311. * @param string $text
  4312. *
  4313. * @return string The text to remove whitespace from
  4314. */
  4315. public static function stripTrailingWSP($text)
  4316. {
  4317. return rtrim($text, " \r\n\t");
  4318. }
  4319. /**
  4320. * Strip trailing line breaks from a string.
  4321. *
  4322. * @param string $text
  4323. *
  4324. * @return string The text to remove breaks from
  4325. */
  4326. public static function stripTrailingBreaks($text)
  4327. {
  4328. return rtrim($text, "\r\n");
  4329. }
  4330. /**
  4331. * Return the current line break format string.
  4332. *
  4333. * @return string
  4334. */
  4335. public static function getLE()
  4336. {
  4337. return static::$LE;
  4338. }
  4339. /**
  4340. * Set the line break format string, e.g. "\r\n".
  4341. *
  4342. * @param string $le
  4343. */
  4344. protected static function setLE($le)
  4345. {
  4346. static::$LE = $le;
  4347. }
  4348. /**
  4349. * Set the public and private key files and password for S/MIME signing.
  4350. *
  4351. * @param string $cert_filename
  4352. * @param string $key_filename
  4353. * @param string $key_pass Password for private key
  4354. * @param string $extracerts_filename Optional path to chain certificate
  4355. */
  4356. public function sign($cert_filename, $key_filename, $key_pass, $extracerts_filename = '')
  4357. {
  4358. $this->sign_cert_file = $cert_filename;
  4359. $this->sign_key_file = $key_filename;
  4360. $this->sign_key_pass = $key_pass;
  4361. $this->sign_extracerts_file = $extracerts_filename;
  4362. }
  4363. /**
  4364. * Quoted-Printable-encode a DKIM header.
  4365. *
  4366. * @param string $txt
  4367. *
  4368. * @return string
  4369. */
  4370. public function DKIM_QP($txt)
  4371. {
  4372. $line = '';
  4373. $len = strlen($txt);
  4374. for ($i = 0; $i < $len; ++$i) {
  4375. $ord = ord($txt[$i]);
  4376. if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord === 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) {
  4377. $line .= $txt[$i];
  4378. } else {
  4379. $line .= '=' . sprintf('%02X', $ord);
  4380. }
  4381. }
  4382. return $line;
  4383. }
  4384. /**
  4385. * Generate a DKIM signature.
  4386. *
  4387. * @param string $signHeader
  4388. *
  4389. * @throws Exception
  4390. *
  4391. * @return string The DKIM signature value
  4392. */
  4393. public function DKIM_Sign($signHeader)
  4394. {
  4395. if (!defined('PKCS7_TEXT')) {
  4396. if ($this->exceptions) {
  4397. throw new Exception($this->lang('extension_missing') . 'openssl');
  4398. }
  4399. return '';
  4400. }
  4401. $privKeyStr = !empty($this->DKIM_private_string) ?
  4402. $this->DKIM_private_string :
  4403. file_get_contents($this->DKIM_private);
  4404. if ('' !== $this->DKIM_passphrase) {
  4405. $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
  4406. } else {
  4407. $privKey = openssl_pkey_get_private($privKeyStr);
  4408. }
  4409. if (openssl_sign($signHeader, $signature, $privKey, 'sha256WithRSAEncryption')) {
  4410. if (\PHP_MAJOR_VERSION < 8) {
  4411. openssl_pkey_free($privKey);
  4412. }
  4413. return base64_encode($signature);
  4414. }
  4415. if (\PHP_MAJOR_VERSION < 8) {
  4416. openssl_pkey_free($privKey);
  4417. }
  4418. return '';
  4419. }
  4420. /**
  4421. * Generate a DKIM canonicalization header.
  4422. * Uses the 'relaxed' algorithm from RFC6376 section 3.4.2.
  4423. * Canonicalized headers should *always* use CRLF, regardless of mailer setting.
  4424. *
  4425. * @see https://tools.ietf.org/html/rfc6376#section-3.4.2
  4426. *
  4427. * @param string $signHeader Header
  4428. *
  4429. * @return string
  4430. */
  4431. public function DKIM_HeaderC($signHeader)
  4432. {
  4433. //Normalize breaks to CRLF (regardless of the mailer)
  4434. $signHeader = static::normalizeBreaks($signHeader, self::CRLF);
  4435. //Unfold header lines
  4436. //Note PCRE \s is too broad a definition of whitespace; RFC5322 defines it as `[ \t]`
  4437. //@see https://tools.ietf.org/html/rfc5322#section-2.2
  4438. //That means this may break if you do something daft like put vertical tabs in your headers.
  4439. $signHeader = preg_replace('/\r\n[ \t]+/', ' ', $signHeader);
  4440. //Break headers out into an array
  4441. $lines = explode(self::CRLF, $signHeader);
  4442. foreach ($lines as $key => $line) {
  4443. //If the header is missing a :, skip it as it's invalid
  4444. //This is likely to happen because the explode() above will also split
  4445. //on the trailing LE, leaving an empty line
  4446. if (strpos($line, ':') === false) {
  4447. continue;
  4448. }
  4449. list($heading, $value) = explode(':', $line, 2);
  4450. //Lower-case header name
  4451. $heading = strtolower($heading);
  4452. //Collapse white space within the value, also convert WSP to space
  4453. $value = preg_replace('/[ \t]+/', ' ', $value);
  4454. //RFC6376 is slightly unclear here - it says to delete space at the *end* of each value
  4455. //But then says to delete space before and after the colon.
  4456. //Net result is the same as trimming both ends of the value.
  4457. //By elimination, the same applies to the field name
  4458. $lines[$key] = trim($heading, " \t") . ':' . trim($value, " \t");
  4459. }
  4460. return implode(self::CRLF, $lines);
  4461. }
  4462. /**
  4463. * Generate a DKIM canonicalization body.
  4464. * Uses the 'simple' algorithm from RFC6376 section 3.4.3.
  4465. * Canonicalized bodies should *always* use CRLF, regardless of mailer setting.
  4466. *
  4467. * @see https://tools.ietf.org/html/rfc6376#section-3.4.3
  4468. *
  4469. * @param string $body Message Body
  4470. *
  4471. * @return string
  4472. */
  4473. public function DKIM_BodyC($body)
  4474. {
  4475. if (empty($body)) {
  4476. return self::CRLF;
  4477. }
  4478. //Normalize line endings to CRLF
  4479. $body = static::normalizeBreaks($body, self::CRLF);
  4480. //Reduce multiple trailing line breaks to a single one
  4481. return static::stripTrailingBreaks($body) . self::CRLF;
  4482. }
  4483. /**
  4484. * Create the DKIM header and body in a new message header.
  4485. *
  4486. * @param string $headers_line Header lines
  4487. * @param string $subject Subject
  4488. * @param string $body Body
  4489. *
  4490. * @throws Exception
  4491. *
  4492. * @return string
  4493. */
  4494. public function DKIM_Add($headers_line, $subject, $body)
  4495. {
  4496. $DKIMsignatureType = 'rsa-sha256'; //Signature & hash algorithms
  4497. $DKIMcanonicalization = 'relaxed/simple'; //Canonicalization methods of header & body
  4498. $DKIMquery = 'dns/txt'; //Query method
  4499. $DKIMtime = time();
  4500. //Always sign these headers without being asked
  4501. //Recommended list from https://tools.ietf.org/html/rfc6376#section-5.4.1
  4502. $autoSignHeaders = [
  4503. 'from',
  4504. 'to',
  4505. 'cc',
  4506. 'date',
  4507. 'subject',
  4508. 'reply-to',
  4509. 'message-id',
  4510. 'content-type',
  4511. 'mime-version',
  4512. 'x-mailer',
  4513. ];
  4514. if (stripos($headers_line, 'Subject') === false) {
  4515. $headers_line .= 'Subject: ' . $subject . static::$LE;
  4516. }
  4517. $headerLines = explode(static::$LE, $headers_line);
  4518. $currentHeaderLabel = '';
  4519. $currentHeaderValue = '';
  4520. $parsedHeaders = [];
  4521. $headerLineIndex = 0;
  4522. $headerLineCount = count($headerLines);
  4523. foreach ($headerLines as $headerLine) {
  4524. $matches = [];
  4525. if (preg_match('/^([^ \t]*?)(?::[ \t]*)(.*)$/', $headerLine, $matches)) {
  4526. if ($currentHeaderLabel !== '') {
  4527. //We were previously in another header; This is the start of a new header, so save the previous one
  4528. $parsedHeaders[] = ['label' => $currentHeaderLabel, 'value' => $currentHeaderValue];
  4529. }
  4530. $currentHeaderLabel = $matches[1];
  4531. $currentHeaderValue = $matches[2];
  4532. } elseif (preg_match('/^[ \t]+(.*)$/', $headerLine, $matches)) {
  4533. //This is a folded continuation of the current header, so unfold it
  4534. $currentHeaderValue .= ' ' . $matches[1];
  4535. }
  4536. ++$headerLineIndex;
  4537. if ($headerLineIndex >= $headerLineCount) {
  4538. //This was the last line, so finish off this header
  4539. $parsedHeaders[] = ['label' => $currentHeaderLabel, 'value' => $currentHeaderValue];
  4540. }
  4541. }
  4542. $copiedHeaders = [];
  4543. $headersToSignKeys = [];
  4544. $headersToSign = [];
  4545. foreach ($parsedHeaders as $header) {
  4546. //Is this header one that must be included in the DKIM signature?
  4547. if (in_array(strtolower($header['label']), $autoSignHeaders, true)) {
  4548. $headersToSignKeys[] = $header['label'];
  4549. $headersToSign[] = $header['label'] . ': ' . $header['value'];
  4550. if ($this->DKIM_copyHeaderFields) {
  4551. $copiedHeaders[] = $header['label'] . ':' . //Note no space after this, as per RFC
  4552. str_replace('|', '=7C', $this->DKIM_QP($header['value']));
  4553. }
  4554. continue;
  4555. }
  4556. //Is this an extra custom header we've been asked to sign?
  4557. if (in_array($header['label'], $this->DKIM_extraHeaders, true)) {
  4558. //Find its value in custom headers
  4559. foreach ($this->CustomHeader as $customHeader) {
  4560. if ($customHeader[0] === $header['label']) {
  4561. $headersToSignKeys[] = $header['label'];
  4562. $headersToSign[] = $header['label'] . ': ' . $header['value'];
  4563. if ($this->DKIM_copyHeaderFields) {
  4564. $copiedHeaders[] = $header['label'] . ':' . //Note no space after this, as per RFC
  4565. str_replace('|', '=7C', $this->DKIM_QP($header['value']));
  4566. }
  4567. //Skip straight to the next header
  4568. continue 2;
  4569. }
  4570. }
  4571. }
  4572. }
  4573. $copiedHeaderFields = '';
  4574. if ($this->DKIM_copyHeaderFields && count($copiedHeaders) > 0) {
  4575. //Assemble a DKIM 'z' tag
  4576. $copiedHeaderFields = ' z=';
  4577. $first = true;
  4578. foreach ($copiedHeaders as $copiedHeader) {
  4579. if (!$first) {
  4580. $copiedHeaderFields .= static::$LE . ' |';
  4581. }
  4582. //Fold long values
  4583. if (strlen($copiedHeader) > self::STD_LINE_LENGTH - 3) {
  4584. $copiedHeaderFields .= substr(
  4585. chunk_split($copiedHeader, self::STD_LINE_LENGTH - 3, static::$LE . self::FWS),
  4586. 0,
  4587. -strlen(static::$LE . self::FWS)
  4588. );
  4589. } else {
  4590. $copiedHeaderFields .= $copiedHeader;
  4591. }
  4592. $first = false;
  4593. }
  4594. $copiedHeaderFields .= ';' . static::$LE;
  4595. }
  4596. $headerKeys = ' h=' . implode(':', $headersToSignKeys) . ';' . static::$LE;
  4597. $headerValues = implode(static::$LE, $headersToSign);
  4598. $body = $this->DKIM_BodyC($body);
  4599. //Base64 of packed binary SHA-256 hash of body
  4600. $DKIMb64 = base64_encode(pack('H*', hash('sha256', $body)));
  4601. $ident = '';
  4602. if ('' !== $this->DKIM_identity) {
  4603. $ident = ' i=' . $this->DKIM_identity . ';' . static::$LE;
  4604. }
  4605. //The DKIM-Signature header is included in the signature *except for* the value of the `b` tag
  4606. //which is appended after calculating the signature
  4607. //https://tools.ietf.org/html/rfc6376#section-3.5
  4608. $dkimSignatureHeader = 'DKIM-Signature: v=1;' .
  4609. ' d=' . $this->DKIM_domain . ';' .
  4610. ' s=' . $this->DKIM_selector . ';' . static::$LE .
  4611. ' a=' . $DKIMsignatureType . ';' .
  4612. ' q=' . $DKIMquery . ';' .
  4613. ' t=' . $DKIMtime . ';' .
  4614. ' c=' . $DKIMcanonicalization . ';' . static::$LE .
  4615. $headerKeys .
  4616. $ident .
  4617. $copiedHeaderFields .
  4618. ' bh=' . $DKIMb64 . ';' . static::$LE .
  4619. ' b=';
  4620. //Canonicalize the set of headers
  4621. $canonicalizedHeaders = $this->DKIM_HeaderC(
  4622. $headerValues . static::$LE . $dkimSignatureHeader
  4623. );
  4624. $signature = $this->DKIM_Sign($canonicalizedHeaders);
  4625. $signature = trim(chunk_split($signature, self::STD_LINE_LENGTH - 3, static::$LE . self::FWS));
  4626. return static::normalizeBreaks($dkimSignatureHeader . $signature);
  4627. }
  4628. /**
  4629. * Detect if a string contains a line longer than the maximum line length
  4630. * allowed by RFC 2822 section 2.1.1.
  4631. *
  4632. * @param string $str
  4633. *
  4634. * @return bool
  4635. */
  4636. public static function hasLineLongerThanMax($str)
  4637. {
  4638. return (bool) preg_match('/^(.{' . (self::MAX_LINE_LENGTH + strlen(static::$LE)) . ',})/m', $str);
  4639. }
  4640. /**
  4641. * If a string contains any "special" characters, double-quote the name,
  4642. * and escape any double quotes with a backslash.
  4643. *
  4644. * @param string $str
  4645. *
  4646. * @return string
  4647. *
  4648. * @see RFC822 3.4.1
  4649. */
  4650. public static function quotedString($str)
  4651. {
  4652. if (preg_match('/[ ()<>@,;:"\/\[\]?=]/', $str)) {
  4653. //If the string contains any of these chars, it must be double-quoted
  4654. //and any double quotes must be escaped with a backslash
  4655. return '"' . str_replace('"', '\\"', $str) . '"';
  4656. }
  4657. //Return the string untouched, it doesn't need quoting
  4658. return $str;
  4659. }
  4660. /**
  4661. * Allows for public read access to 'to' property.
  4662. * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
  4663. *
  4664. * @return array
  4665. */
  4666. public function getToAddresses()
  4667. {
  4668. return $this->to;
  4669. }
  4670. /**
  4671. * Allows for public read access to 'cc' property.
  4672. * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
  4673. *
  4674. * @return array
  4675. */
  4676. public function getCcAddresses()
  4677. {
  4678. return $this->cc;
  4679. }
  4680. /**
  4681. * Allows for public read access to 'bcc' property.
  4682. * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
  4683. *
  4684. * @return array
  4685. */
  4686. public function getBccAddresses()
  4687. {
  4688. return $this->bcc;
  4689. }
  4690. /**
  4691. * Allows for public read access to 'ReplyTo' property.
  4692. * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
  4693. *
  4694. * @return array
  4695. */
  4696. public function getReplyToAddresses()
  4697. {
  4698. return $this->ReplyTo;
  4699. }
  4700. /**
  4701. * Allows for public read access to 'all_recipients' property.
  4702. * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
  4703. *
  4704. * @return array
  4705. */
  4706. public function getAllRecipientAddresses()
  4707. {
  4708. return $this->all_recipients;
  4709. }
  4710. /**
  4711. * Perform a callback.
  4712. *
  4713. * @param bool $isSent
  4714. * @param array $to
  4715. * @param array $cc
  4716. * @param array $bcc
  4717. * @param string $subject
  4718. * @param string $body
  4719. * @param string $from
  4720. * @param array $extra
  4721. */
  4722. protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from, $extra)
  4723. {
  4724. if (!empty($this->action_function) && is_callable($this->action_function)) {
  4725. call_user_func($this->action_function, $isSent, $to, $cc, $bcc, $subject, $body, $from, $extra);
  4726. }
  4727. }
  4728. /**
  4729. * Get the OAuthTokenProvider instance.
  4730. *
  4731. * @return OAuthTokenProvider
  4732. */
  4733. public function getOAuth()
  4734. {
  4735. return $this->oauth;
  4736. }
  4737. /**
  4738. * Set an OAuthTokenProvider instance.
  4739. */
  4740. public function setOAuth(OAuthTokenProvider $oauth)
  4741. {
  4742. $this->oauth = $oauth;
  4743. }
  4744. }