Нет описания

PHPMailer.php 169KB

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