PHPMailer.php 175 KB

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