PHPMailer.php 167 KB

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