PHPMailer.php 176 KB

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