PHPMailer.php 161 KB

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