PHPMailer.php 147 KB

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