PHPMailer.php 171 KB

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