class.phpmailer.php 144 KB

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