PHPMailer.php 161 KB

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