PHPMailer.php 136 KB

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