phpmailer.php 145 KB

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