Phpmailer.class.php 94 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959
  1. <?php
  2. /*~ class.phpmailer.php
  3. .---------------------------------------------------------------------------.
  4. | Software: PHPMailer - PHP email class |
  5. | Version: 5.2.6 |
  6. | Site: https://github.com/PHPMailer/PHPMailer/ |
  7. | ------------------------------------------------------------------------- |
  8. | Admins: Marcus Bointon |
  9. | Admins: Jim Jagielski |
  10. | Authors: Andy Prevost (codeworxtech) codeworxtech@users.sourceforge.net |
  11. | : Marcus Bointon (coolbru) phpmailer@synchromedia.co.uk |
  12. | : Jim Jagielski (jimjag) jimjag@gmail.com |
  13. | Founder: Brent R. Matzelle (original founder) |
  14. | Copyright (c) 2010-2012, Jim Jagielski. All Rights Reserved. |
  15. | Copyright (c) 2004-2009, Andy Prevost. All Rights Reserved. |
  16. | Copyright (c) 2001-2003, Brent R. Matzelle |
  17. | ------------------------------------------------------------------------- |
  18. | License: Distributed under the Lesser General Public License (LGPL) |
  19. | http://www.gnu.org/copyleft/lesser.html |
  20. | This program is distributed in the hope that it will be useful - WITHOUT |
  21. | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
  22. | FITNESS FOR A PARTICULAR PURPOSE. |
  23. '---------------------------------------------------------------------------'
  24. */
  25. /**
  26. * PHPMailer - PHP email creation and transport class
  27. * NOTE: Requires PHP version 5 or later
  28. * @package PHPMailer
  29. * @author Andy Prevost
  30. * @author Marcus Bointon
  31. * @author Jim Jagielski
  32. * @copyright 2010 - 2012 Jim Jagielski
  33. * @copyright 2004 - 2009 Andy Prevost
  34. * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
  35. */
  36. namespace Lib\PHPMailer;
  37. if (version_compare(PHP_VERSION, '5.0.0', '<') ) {
  38. exit("Sorry, PHPMailer will only run on PHP version 5 or greater!\n");
  39. }
  40. /**
  41. * PHP email creation and transport class
  42. * @package PHPMailer
  43. */
  44. class Phpmailer {
  45. /////////////////////////////////////////////////
  46. // PROPERTIES, PUBLIC
  47. /////////////////////////////////////////////////
  48. /**
  49. * Email priority (1 = High, 3 = Normal, 5 = low).
  50. * @var int
  51. */
  52. public $Priority = 3;
  53. /**
  54. * Sets the CharSet of the message.
  55. * @var string
  56. */
  57. public $CharSet = 'iso-8859-1';
  58. /**
  59. * Sets the Content-type of the message.
  60. * @var string
  61. */
  62. public $ContentType = 'text/plain';
  63. /**
  64. * Sets the Encoding of the message. Options for this are
  65. * "8bit", "7bit", "binary", "base64", and "quoted-printable".
  66. * @var string
  67. */
  68. public $Encoding = '8bit';
  69. /**
  70. * Holds the most recent mailer error message.
  71. * @var string
  72. */
  73. public $ErrorInfo = '';
  74. /**
  75. * Sets the From email address for the message.
  76. * @var string
  77. */
  78. public $From = 'root@localhost';
  79. /**
  80. * Sets the From name of the message.
  81. * @var string
  82. */
  83. public $FromName = 'Root User';
  84. /**
  85. * Sets the Sender email (Return-Path) of the message.
  86. * If not empty, will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
  87. * @var string
  88. */
  89. public $Sender = '';
  90. /**
  91. * Sets the Return-Path of the message. If empty, it will
  92. * be set to either From or Sender.
  93. * @var string
  94. */
  95. public $ReturnPath = '';
  96. /**
  97. * Sets the Subject of the message.
  98. * @var string
  99. */
  100. public $Subject = '';
  101. /**
  102. * An HTML or plain text message body.
  103. * If HTML then call IsHTML(true).
  104. * @var string
  105. */
  106. public $Body = '';
  107. /**
  108. * The plain-text message body.
  109. * This body can be read by mail clients that do not have HTML email
  110. * capability such as mutt & Eudora.
  111. * Clients that can read HTML will view the normal Body.
  112. * @var string
  113. */
  114. public $AltBody = '';
  115. /**
  116. * An iCal message part body
  117. * Only supported in simple alt or alt_inline message types
  118. * To generate iCal events, use the bundled extras/EasyPeasyICS.php class or iCalcreator
  119. * @link http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/
  120. * @link http://kigkonsult.se/iCalcreator/
  121. * @var string
  122. */
  123. public $Ical = '';
  124. /**
  125. * Stores the complete compiled MIME message body.
  126. * @var string
  127. * @access protected
  128. */
  129. protected $MIMEBody = '';
  130. /**
  131. * Stores the complete compiled MIME message headers.
  132. * @var string
  133. * @access protected
  134. */
  135. protected $MIMEHeader = '';
  136. /**
  137. * Stores the extra header list which CreateHeader() doesn't fold in
  138. * @var string
  139. * @access protected
  140. */
  141. protected $mailHeader = '';
  142. /**
  143. * Sets word wrapping on the body of the message to a given number of
  144. * characters.
  145. * @var int
  146. */
  147. public $WordWrap = 0;
  148. /**
  149. * Method to send mail: ("mail", "sendmail", or "smtp").
  150. * @var string
  151. */
  152. public $Mailer = 'mail';
  153. /**
  154. * Sets the path of the sendmail program.
  155. * @var string
  156. */
  157. public $Sendmail = '/usr/sbin/sendmail';
  158. /**
  159. * Determine if mail() uses a fully sendmail compatible MTA that
  160. * supports sendmail's "-oi -f" options
  161. * @var boolean
  162. */
  163. public $UseSendmailOptions = true;
  164. /**
  165. * Path to PHPMailer plugins. Useful if the SMTP class
  166. * is in a different directory than the PHP include path.
  167. * @var string
  168. */
  169. public $PluginDir = '';
  170. /**
  171. * Sets the email address that a reading confirmation will be sent.
  172. * @var string
  173. */
  174. public $ConfirmReadingTo = '';
  175. /**
  176. * Sets the hostname to use in Message-Id and Received headers
  177. * and as default HELO string. If empty, the value returned
  178. * by SERVER_NAME is used or 'localhost.localdomain'.
  179. * @var string
  180. */
  181. public $Hostname = '';
  182. /**
  183. * Sets the message ID to be used in the Message-Id header.
  184. * If empty, a unique id will be generated.
  185. * @var string
  186. */
  187. public $MessageID = '';
  188. /**
  189. * Sets the message Date to be used in the Date header.
  190. * If empty, the current date will be added.
  191. * @var string
  192. */
  193. public $MessageDate = '';
  194. /////////////////////////////////////////////////
  195. // PROPERTIES FOR SMTP
  196. /////////////////////////////////////////////////
  197. /**
  198. * Sets the SMTP hosts.
  199. *
  200. * All hosts must be separated by a
  201. * semicolon. You can also specify a different port
  202. * for each host by using this format: [hostname:port]
  203. * (e.g. "smtp1.example.com:25;smtp2.example.com").
  204. * Hosts will be tried in order.
  205. * @var string
  206. */
  207. public $Host = 'localhost';
  208. /**
  209. * Sets the default SMTP server port.
  210. * @var int
  211. */
  212. public $Port = 25;
  213. /**
  214. * Sets the SMTP HELO of the message (Default is $Hostname).
  215. * @var string
  216. */
  217. public $Helo = '';
  218. /**
  219. * Sets connection prefix. Options are "", "ssl" or "tls"
  220. * @var string
  221. */
  222. public $SMTPSecure = '';
  223. /**
  224. * Sets SMTP authentication. Utilizes the Username and Password variables.
  225. * @var bool
  226. */
  227. public $SMTPAuth = false;
  228. /**
  229. * Sets SMTP username.
  230. * @var string
  231. */
  232. public $Username = '';
  233. /**
  234. * Sets SMTP password.
  235. * @var string
  236. */
  237. public $Password = '';
  238. /**
  239. * Sets SMTP auth type. Options are LOGIN | PLAIN | NTLM | CRAM-MD5 (default LOGIN)
  240. * @var string
  241. */
  242. public $AuthType = '';
  243. /**
  244. * Sets SMTP realm.
  245. * @var string
  246. */
  247. public $Realm = '';
  248. /**
  249. * Sets SMTP workstation.
  250. * @var string
  251. */
  252. public $Workstation = '';
  253. /**
  254. * Sets the SMTP server timeout in seconds.
  255. * This function will not work with the win32 version.
  256. * @var int
  257. */
  258. public $Timeout = 10;
  259. /**
  260. * Sets SMTP class debugging on or off.
  261. * @var bool
  262. */
  263. public $SMTPDebug = false;
  264. /**
  265. * Sets the function/method to use for debugging output.
  266. * Right now we only honor "echo" or "error_log"
  267. * @var string
  268. */
  269. public $Debugoutput = "echo";
  270. /**
  271. * Prevents the SMTP connection from being closed after each mail
  272. * sending. If this is set to true then to close the connection
  273. * requires an explicit call to SmtpClose().
  274. * @var bool
  275. */
  276. public $SMTPKeepAlive = false;
  277. /**
  278. * Provides the ability to have the TO field process individual
  279. * emails, instead of sending to entire TO addresses
  280. * @var bool
  281. */
  282. public $SingleTo = false;
  283. /**
  284. * Should we generate VERP addresses when sending via SMTP?
  285. * @link http://en.wikipedia.org/wiki/Variable_envelope_return_path
  286. * @var bool
  287. */
  288. public $do_verp = false;
  289. /**
  290. * If SingleTo is true, this provides the array to hold the email addresses
  291. * @var bool
  292. */
  293. public $SingleToArray = array();
  294. /**
  295. * Should we allow sending messages with empty body?
  296. * @var bool
  297. */
  298. public $AllowEmpty = false;
  299. /**
  300. * Provides the ability to change the generic line ending
  301. * NOTE: The default remains '\n'. We force CRLF where we KNOW
  302. * it must be used via self::CRLF
  303. * @var string
  304. */
  305. public $LE = "\n";
  306. /**
  307. * Used with DKIM Signing
  308. * required parameter if DKIM is enabled
  309. *
  310. * domain selector example domainkey
  311. * @var string
  312. */
  313. public $DKIM_selector = '';
  314. /**
  315. * Used with DKIM Signing
  316. * required if DKIM is enabled, in format of email address 'you@yourdomain.com' typically used as the source of the email
  317. * @var string
  318. */
  319. public $DKIM_identity = '';
  320. /**
  321. * Used with DKIM Signing
  322. * optional parameter if your private key requires a passphras
  323. * @var string
  324. */
  325. public $DKIM_passphrase = '';
  326. /**
  327. * Used with DKIM Singing
  328. * required if DKIM is enabled, in format of email address 'domain.com'
  329. * @var string
  330. */
  331. public $DKIM_domain = '';
  332. /**
  333. * Used with DKIM Signing
  334. * required if DKIM is enabled, path to private key file
  335. * @var string
  336. */
  337. public $DKIM_private = '';
  338. /**
  339. * Callback Action function name.
  340. * The function that handles the result of the send email action.
  341. * It is called out by Send() for each email sent.
  342. *
  343. * Value can be:
  344. * - 'function_name' for function names
  345. * - 'Class::Method' for static method calls
  346. * - array($object, 'Method') for calling methods on $object
  347. * See http://php.net/is_callable manual page for more details.
  348. *
  349. * Parameters:
  350. * bool $result result of the send action
  351. * string $to email address of the recipient
  352. * string $cc cc email addresses
  353. * string $bcc bcc email addresses
  354. * string $subject the subject
  355. * string $body the email body
  356. * string $from email address of sender
  357. * @var string
  358. */
  359. public $action_function = ''; //'callbackAction';
  360. /**
  361. * Sets the PHPMailer Version number
  362. * @var string
  363. */
  364. public $Version = '5.2.6';
  365. /**
  366. * What to use in the X-Mailer header
  367. * @var string NULL for default, whitespace for None, or actual string to use
  368. */
  369. public $XMailer = '';
  370. /////////////////////////////////////////////////
  371. // PROPERTIES, PRIVATE AND PROTECTED
  372. /////////////////////////////////////////////////
  373. /**
  374. * @var SMTP An instance of the SMTP sender class
  375. * @access protected
  376. */
  377. protected $smtp = null;
  378. /**
  379. * @var array An array of 'to' addresses
  380. * @access protected
  381. */
  382. protected $to = array();
  383. /**
  384. * @var array An array of 'cc' addresses
  385. * @access protected
  386. */
  387. protected $cc = array();
  388. /**
  389. * @var array An array of 'bcc' addresses
  390. * @access protected
  391. */
  392. protected $bcc = array();
  393. /**
  394. * @var array An array of reply-to name and address
  395. * @access protected
  396. */
  397. protected $ReplyTo = array();
  398. /**
  399. * @var array An array of all kinds of addresses: to, cc, bcc, replyto
  400. * @access protected
  401. */
  402. protected $all_recipients = array();
  403. /**
  404. * @var array An array of attachments
  405. * @access protected
  406. */
  407. protected $attachment = array();
  408. /**
  409. * @var array An array of custom headers
  410. * @access protected
  411. */
  412. protected $CustomHeader = array();
  413. /**
  414. * @var string The message's MIME type
  415. * @access protected
  416. */
  417. protected $message_type = '';
  418. /**
  419. * @var array An array of MIME boundary strings
  420. * @access protected
  421. */
  422. protected $boundary = array();
  423. /**
  424. * @var array An array of available languages
  425. * @access protected
  426. */
  427. protected $language = array();
  428. /**
  429. * @var integer The number of errors encountered
  430. * @access protected
  431. */
  432. protected $error_count = 0;
  433. /**
  434. * @var string The filename of a DKIM certificate file
  435. * @access protected
  436. */
  437. protected $sign_cert_file = '';
  438. /**
  439. * @var string The filename of a DKIM key file
  440. * @access protected
  441. */
  442. protected $sign_key_file = '';
  443. /**
  444. * @var string The password of a DKIM key
  445. * @access protected
  446. */
  447. protected $sign_key_pass = '';
  448. /**
  449. * @var boolean Whether to throw exceptions for errors
  450. * @access protected
  451. */
  452. protected $exceptions = false;
  453. /////////////////////////////////////////////////
  454. // CONSTANTS
  455. /////////////////////////////////////////////////
  456. const STOP_MESSAGE = 0; // message only, continue processing
  457. const STOP_CONTINUE = 1; // message?, likely ok to continue processing
  458. const STOP_CRITICAL = 2; // message, plus full stop, critical error reached
  459. const CRLF = "\r\n"; // SMTP RFC specified EOL
  460. /////////////////////////////////////////////////
  461. // METHODS, VARIABLES
  462. /////////////////////////////////////////////////
  463. /**
  464. * Calls actual mail() function, but in a safe_mode aware fashion
  465. * Also, unless sendmail_path points to sendmail (or something that
  466. * claims to be sendmail), don't pass params (not a perfect fix,
  467. * but it will do)
  468. * @param string $to To
  469. * @param string $subject Subject
  470. * @param string $body Message Body
  471. * @param string $header Additional Header(s)
  472. * @param string $params Params
  473. * @access private
  474. * @return bool
  475. */
  476. private function mail_passthru($to, $subject, $body, $header, $params) {
  477. if ( ini_get('safe_mode') || !($this->UseSendmailOptions) ) {
  478. $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header);
  479. } else {
  480. $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header, $params);
  481. }
  482. return $rt;
  483. }
  484. /**
  485. * Outputs debugging info via user-defined method
  486. * @param string $str
  487. */
  488. protected function edebug($str) {
  489. switch ($this->Debugoutput) {
  490. case 'error_log':
  491. error_log($str);
  492. break;
  493. case 'html':
  494. //Cleans up output a bit for a better looking display that's HTML-safe
  495. echo htmlentities(preg_replace('/[\r\n]+/', '', $str), ENT_QUOTES, $this->CharSet)."<br>\n";
  496. break;
  497. case 'echo':
  498. default:
  499. //Just echoes exactly what was received
  500. echo $str;
  501. }
  502. }
  503. /**
  504. * Constructor
  505. * @param boolean $exceptions Should we throw external exceptions?
  506. */
  507. public function __construct($exceptions = false) {
  508. $this->exceptions = ($exceptions == true);
  509. }
  510. /**
  511. * Destructor
  512. */
  513. public function __destruct() {
  514. if ($this->Mailer == 'smtp') { //Close any open SMTP connection nicely
  515. $this->SmtpClose();
  516. }
  517. }
  518. /**
  519. * Sets message type to HTML.
  520. * @param bool $ishtml
  521. * @return void
  522. */
  523. public function IsHTML($ishtml = true) {
  524. if ($ishtml) {
  525. $this->ContentType = 'text/html';
  526. } else {
  527. $this->ContentType = 'text/plain';
  528. }
  529. }
  530. /**
  531. * Sets Mailer to send message using SMTP.
  532. * @return void
  533. */
  534. public function IsSMTP() {
  535. $this->Mailer = 'smtp';
  536. }
  537. /**
  538. * Sets Mailer to send message using PHP mail() function.
  539. * @return void
  540. */
  541. public function IsMail() {
  542. $this->Mailer = 'mail';
  543. }
  544. /**
  545. * Sets Mailer to send message using the $Sendmail program.
  546. * @return void
  547. */
  548. public function IsSendmail() {
  549. if (!stristr(ini_get('sendmail_path'), 'sendmail')) {
  550. $this->Sendmail = '/var/qmail/bin/sendmail';
  551. }
  552. $this->Mailer = 'sendmail';
  553. }
  554. /**
  555. * Sets Mailer to send message using the qmail MTA.
  556. * @return void
  557. */
  558. public function IsQmail() {
  559. if (stristr(ini_get('sendmail_path'), 'qmail')) {
  560. $this->Sendmail = '/var/qmail/bin/sendmail';
  561. }
  562. $this->Mailer = 'sendmail';
  563. }
  564. /////////////////////////////////////////////////
  565. // METHODS, RECIPIENTS
  566. /////////////////////////////////////////////////
  567. /**
  568. * Adds a "To" address.
  569. * @param string $address
  570. * @param string $name
  571. * @return boolean true on success, false if address already used
  572. */
  573. public function AddAddress($address, $name = '') {
  574. return $this->AddAnAddress('to', $address, $name);
  575. }
  576. /**
  577. * Adds a "Cc" address.
  578. * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
  579. * @param string $address
  580. * @param string $name
  581. * @return boolean true on success, false if address already used
  582. */
  583. public function AddCC($address, $name = '') {
  584. return $this->AddAnAddress('cc', $address, $name);
  585. }
  586. /**
  587. * Adds a "Bcc" address.
  588. * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
  589. * @param string $address
  590. * @param string $name
  591. * @return boolean true on success, false if address already used
  592. */
  593. public function AddBCC($address, $name = '') {
  594. return $this->AddAnAddress('bcc', $address, $name);
  595. }
  596. /**
  597. * Adds a "Reply-to" address.
  598. * @param string $address
  599. * @param string $name
  600. * @return boolean
  601. */
  602. public function AddReplyTo($address, $name = '') {
  603. return $this->AddAnAddress('Reply-To', $address, $name);
  604. }
  605. /**
  606. * Adds an address to one of the recipient arrays
  607. * Addresses that have been added already return false, but do not throw exceptions
  608. * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo'
  609. * @param string $address The email address to send to
  610. * @param string $name
  611. * @throws phpmailerException
  612. * @return boolean true on success, false if address already used or invalid in some way
  613. * @access protected
  614. */
  615. protected function AddAnAddress($kind, $address, $name = '') {
  616. if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) {
  617. $this->SetError($this->Lang('Invalid recipient array').': '.$kind);
  618. if ($this->exceptions) {
  619. throw new phpmailerException('Invalid recipient array: ' . $kind);
  620. }
  621. if ($this->SMTPDebug) {
  622. $this->edebug($this->Lang('Invalid recipient array').': '.$kind);
  623. }
  624. return false;
  625. }
  626. $address = trim($address);
  627. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  628. if (!$this->ValidateAddress($address)) {
  629. $this->SetError($this->Lang('invalid_address').': '. $address);
  630. if ($this->exceptions) {
  631. throw new phpmailerException($this->Lang('invalid_address').': '.$address);
  632. }
  633. if ($this->SMTPDebug) {
  634. $this->edebug($this->Lang('invalid_address').': '.$address);
  635. }
  636. return false;
  637. }
  638. if ($kind != 'Reply-To') {
  639. if (!isset($this->all_recipients[strtolower($address)])) {
  640. array_push($this->$kind, array($address, $name));
  641. $this->all_recipients[strtolower($address)] = true;
  642. return true;
  643. }
  644. } else {
  645. if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
  646. $this->ReplyTo[strtolower($address)] = array($address, $name);
  647. return true;
  648. }
  649. }
  650. return false;
  651. }
  652. /**
  653. * Set the From and FromName properties
  654. * @param string $address
  655. * @param string $name
  656. * @param boolean $auto Whether to also set the Sender address, defaults to true
  657. * @throws phpmailerException
  658. * @return boolean
  659. */
  660. public function SetFrom($address, $name = '', $auto = true) {
  661. $address = trim($address);
  662. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  663. if (!$this->ValidateAddress($address)) {
  664. $this->SetError($this->Lang('invalid_address').': '. $address);
  665. if ($this->exceptions) {
  666. throw new phpmailerException($this->Lang('invalid_address').': '.$address);
  667. }
  668. if ($this->SMTPDebug) {
  669. $this->edebug($this->Lang('invalid_address').': '.$address);
  670. }
  671. return false;
  672. }
  673. $this->From = $address;
  674. $this->FromName = $name;
  675. if ($auto) {
  676. if (empty($this->Sender)) {
  677. $this->Sender = $address;
  678. }
  679. }
  680. return true;
  681. }
  682. /**
  683. * Check that a string looks roughly like an email address should
  684. * Static so it can be used without instantiation, public so people can overload
  685. * Conforms to RFC5322: Uses *correct* regex on which FILTER_VALIDATE_EMAIL is
  686. * based; So why not use FILTER_VALIDATE_EMAIL? Because it was broken to
  687. * not allow a@b type valid addresses :(
  688. * @link http://squiloople.com/2009/12/20/email-address-validation/
  689. * @copyright regex Copyright Michael Rushton 2009-10 | http://squiloople.com/ | Feel free to use and redistribute this code. But please keep this copyright notice.
  690. * @param string $address The email address to check
  691. * @return boolean
  692. * @static
  693. * @access public
  694. */
  695. public static function ValidateAddress($address) {
  696. if (defined('PCRE_VERSION')) { //Check this instead of extension_loaded so it works when that function is disabled
  697. if (version_compare(PCRE_VERSION, '8.0') >= 0) {
  698. return (boolean)preg_match('/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD', $address);
  699. } else {
  700. //Fall back to an older regex that doesn't need a recent PCRE
  701. return (boolean)preg_match('/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!(?>"?(?>\\\[ -~]|[^"])"?){65,}@)(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*")(?>\.(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*"))*@(?>(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)){0,126}|\[(?:(?>IPv6:(?>(?>[a-f0-9]{1,4})(?>:[a-f0-9]{1,4}){7}|(?!(?:.*[a-f0-9][:\]]){8,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?::(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?))|(?>(?>IPv6:(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){5}:|(?!(?:.*[a-f0-9]:){6,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4})?::(?>(?:[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4}):)?))?(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\.(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}))\])$/isD', $address);
  702. }
  703. } else {
  704. //No PCRE! Do something _very_ approximate!
  705. //Check the address is 3 chars or longer and contains an @ that's not the first or last char
  706. return (strlen($address) >= 3 and strpos($address, '@') >= 1 and strpos($address, '@') != strlen($address) - 1);
  707. }
  708. }
  709. /////////////////////////////////////////////////
  710. // METHODS, MAIL SENDING
  711. /////////////////////////////////////////////////
  712. /**
  713. * Creates message and assigns Mailer. If the message is
  714. * not sent successfully then it returns false. Use the ErrorInfo
  715. * variable to view description of the error.
  716. * @throws phpmailerException
  717. * @return bool
  718. */
  719. public function Send() {
  720. try {
  721. if(!$this->PreSend()) return false;
  722. return $this->PostSend();
  723. } catch (phpmailerException $e) {
  724. $this->mailHeader = '';
  725. $this->SetError($e->getMessage());
  726. if ($this->exceptions) {
  727. throw $e;
  728. }
  729. return false;
  730. }
  731. }
  732. /**
  733. * Prep mail by constructing all message entities
  734. * @throws phpmailerException
  735. * @return bool
  736. */
  737. public function PreSend() {
  738. try {
  739. $this->mailHeader = "";
  740. if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
  741. throw new phpmailerException($this->Lang('provide_address'), self::STOP_CRITICAL);
  742. }
  743. // Set whether the message is multipart/alternative
  744. if(!empty($this->AltBody)) {
  745. $this->ContentType = 'multipart/alternative';
  746. }
  747. $this->error_count = 0; // reset errors
  748. $this->SetMessageType();
  749. //Refuse to send an empty message unless we are specifically allowing it
  750. if (!$this->AllowEmpty and empty($this->Body)) {
  751. throw new phpmailerException($this->Lang('empty_message'), self::STOP_CRITICAL);
  752. }
  753. $this->MIMEHeader = $this->CreateHeader();
  754. $this->MIMEBody = $this->CreateBody();
  755. // To capture the complete message when using mail(), create
  756. // an extra header list which CreateHeader() doesn't fold in
  757. if ($this->Mailer == 'mail') {
  758. if (count($this->to) > 0) {
  759. $this->mailHeader .= $this->AddrAppend("To", $this->to);
  760. } else {
  761. $this->mailHeader .= $this->HeaderLine("To", "undisclosed-recipients:;");
  762. }
  763. $this->mailHeader .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader(trim($this->Subject))));
  764. }
  765. // digitally sign with DKIM if enabled
  766. if (!empty($this->DKIM_domain) && !empty($this->DKIM_private) && !empty($this->DKIM_selector) && !empty($this->DKIM_domain) && file_exists($this->DKIM_private)) {
  767. $header_dkim = $this->DKIM_Add($this->MIMEHeader . $this->mailHeader, $this->EncodeHeader($this->SecureHeader($this->Subject)), $this->MIMEBody);
  768. $this->MIMEHeader = str_replace("\r\n", "\n", $header_dkim) . $this->MIMEHeader;
  769. }
  770. return true;
  771. } catch (phpmailerException $e) {
  772. $this->SetError($e->getMessage());
  773. if ($this->exceptions) {
  774. throw $e;
  775. }
  776. return false;
  777. }
  778. }
  779. /**
  780. * Actual Email transport function
  781. * Send the email via the selected mechanism
  782. * @throws phpmailerException
  783. * @return bool
  784. */
  785. public function PostSend() {
  786. try {
  787. // Choose the mailer and send through it
  788. switch($this->Mailer) {
  789. case 'sendmail':
  790. return $this->SendmailSend($this->MIMEHeader, $this->MIMEBody);
  791. case 'smtp':
  792. return $this->SmtpSend($this->MIMEHeader, $this->MIMEBody);
  793. case 'mail':
  794. return $this->MailSend($this->MIMEHeader, $this->MIMEBody);
  795. default:
  796. return $this->MailSend($this->MIMEHeader, $this->MIMEBody);
  797. }
  798. } catch (phpmailerException $e) {
  799. $this->SetError($e->getMessage());
  800. if ($this->exceptions) {
  801. throw $e;
  802. }
  803. if ($this->SMTPDebug) {
  804. $this->edebug($e->getMessage()."\n");
  805. }
  806. }
  807. return false;
  808. }
  809. /**
  810. * Sends mail using the $Sendmail program.
  811. * @param string $header The message headers
  812. * @param string $body The message body
  813. * @throws phpmailerException
  814. * @access protected
  815. * @return bool
  816. */
  817. protected function SendmailSend($header, $body) {
  818. if ($this->Sender != '') {
  819. $sendmail = sprintf("%s -oi -f%s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
  820. } else {
  821. $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail));
  822. }
  823. if ($this->SingleTo === true) {
  824. foreach ($this->SingleToArray as $val) {
  825. if(!@$mail = popen($sendmail, 'w')) {
  826. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  827. }
  828. fputs($mail, "To: " . $val . "\n");
  829. fputs($mail, $header);
  830. fputs($mail, $body);
  831. $result = pclose($mail);
  832. // implement call back function if it exists
  833. $isSent = ($result == 0) ? 1 : 0;
  834. $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
  835. if($result != 0) {
  836. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  837. }
  838. }
  839. } else {
  840. if(!@$mail = popen($sendmail, 'w')) {
  841. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  842. }
  843. fputs($mail, $header);
  844. fputs($mail, $body);
  845. $result = pclose($mail);
  846. // implement call back function if it exists
  847. $isSent = ($result == 0) ? 1 : 0;
  848. $this->doCallback($isSent, $this->to, $this->cc, $this->bcc, $this->Subject, $body);
  849. if($result != 0) {
  850. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  851. }
  852. }
  853. return true;
  854. }
  855. /**
  856. * Sends mail using the PHP mail() function.
  857. * @param string $header The message headers
  858. * @param string $body The message body
  859. * @throws phpmailerException
  860. * @access protected
  861. * @return bool
  862. */
  863. protected function MailSend($header, $body) {
  864. $toArr = array();
  865. foreach($this->to as $t) {
  866. $toArr[] = $this->AddrFormat($t);
  867. }
  868. $to = implode(', ', $toArr);
  869. if (empty($this->Sender)) {
  870. $params = " ";
  871. } else {
  872. $params = sprintf("-f%s", $this->Sender);
  873. }
  874. if ($this->Sender != '' and !ini_get('safe_mode')) {
  875. $old_from = ini_get('sendmail_from');
  876. ini_set('sendmail_from', $this->Sender);
  877. }
  878. $rt = false;
  879. if ($this->SingleTo === true && count($toArr) > 1) {
  880. foreach ($toArr as $val) {
  881. $rt = $this->mail_passthru($val, $this->Subject, $body, $header, $params);
  882. // implement call back function if it exists
  883. $isSent = ($rt == 1) ? 1 : 0;
  884. $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
  885. }
  886. } else {
  887. $rt = $this->mail_passthru($to, $this->Subject, $body, $header, $params);
  888. // implement call back function if it exists
  889. $isSent = ($rt == 1) ? 1 : 0;
  890. $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body);
  891. }
  892. if (isset($old_from)) {
  893. ini_set('sendmail_from', $old_from);
  894. }
  895. if(!$rt) {
  896. throw new phpmailerException($this->Lang('instantiate'), self::STOP_CRITICAL);
  897. }
  898. return true;
  899. }
  900. /**
  901. * Sends mail via SMTP using PhpSMTP
  902. * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
  903. * @param string $header The message headers
  904. * @param string $body The message body
  905. * @throws phpmailerException
  906. * @uses SMTP
  907. * @access protected
  908. * @return bool
  909. */
  910. protected function SmtpSend($header, $body) {
  911. require_once $this->PluginDir . 'Smtp.class.php';
  912. $bad_rcpt = array();
  913. if(!$this->SmtpConnect()) {
  914. throw new phpmailerException($this->Lang('smtp_connect_failed'), self::STOP_CRITICAL);
  915. }
  916. $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender;
  917. if(!$this->smtp->Mail($smtp_from)) {
  918. $this->SetError($this->Lang('from_failed') . $smtp_from . ' : ' .implode(',', $this->smtp->getError()));
  919. throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL);
  920. }
  921. // Attempt to send attach all recipients
  922. foreach($this->to as $to) {
  923. if (!$this->smtp->Recipient($to[0])) {
  924. $bad_rcpt[] = $to[0];
  925. // implement call back function if it exists
  926. $isSent = 0;
  927. $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body);
  928. } else {
  929. // implement call back function if it exists
  930. $isSent = 1;
  931. $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body);
  932. }
  933. }
  934. foreach($this->cc as $cc) {
  935. if (!$this->smtp->Recipient($cc[0])) {
  936. $bad_rcpt[] = $cc[0];
  937. // implement call back function if it exists
  938. $isSent = 0;
  939. $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body);
  940. } else {
  941. // implement call back function if it exists
  942. $isSent = 1;
  943. $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body);
  944. }
  945. }
  946. foreach($this->bcc as $bcc) {
  947. if (!$this->smtp->Recipient($bcc[0])) {
  948. $bad_rcpt[] = $bcc[0];
  949. // implement call back function if it exists
  950. $isSent = 0;
  951. $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body);
  952. } else {
  953. // implement call back function if it exists
  954. $isSent = 1;
  955. $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body);
  956. }
  957. }
  958. if (count($bad_rcpt) > 0 ) { //Create error message for any bad addresses
  959. $badaddresses = implode(', ', $bad_rcpt);
  960. throw new phpmailerException($this->Lang('recipients_failed') . $badaddresses);
  961. }
  962. if(!$this->smtp->Data($header . $body)) {
  963. throw new phpmailerException($this->Lang('data_not_accepted'), self::STOP_CRITICAL);
  964. }
  965. if($this->SMTPKeepAlive == true) {
  966. $this->smtp->Reset();
  967. } else {
  968. $this->smtp->Quit();
  969. $this->smtp->Close();
  970. }
  971. return true;
  972. }
  973. /**
  974. * Initiates a connection to an SMTP server.
  975. * Returns false if the operation failed.
  976. * @param array $options An array of options compatible with stream_context_create()
  977. * @uses SMTP
  978. * @access public
  979. * @throws phpmailerException
  980. * @return bool
  981. */
  982. public function SmtpConnect($options = array()) {
  983. if(is_null($this->smtp)) {
  984. $this->smtp = new SMTP;
  985. }
  986. //Already connected?
  987. if ($this->smtp->Connected()) {
  988. return true;
  989. }
  990. $this->smtp->Timeout = $this->Timeout;
  991. $this->smtp->do_debug = $this->SMTPDebug;
  992. $this->smtp->Debugoutput = $this->Debugoutput;
  993. $this->smtp->do_verp = $this->do_verp;
  994. $index = 0;
  995. $tls = ($this->SMTPSecure == 'tls');
  996. $ssl = ($this->SMTPSecure == 'ssl');
  997. $hosts = explode(';', $this->Host);
  998. $lastexception = null;
  999. foreach ($hosts as $hostentry) {
  1000. $hostinfo = array();
  1001. $host = $hostentry;
  1002. $port = $this->Port;
  1003. if (preg_match('/^(.+):([0-9]+)$/', $hostentry, $hostinfo)) { //If $hostentry contains 'address:port', override default
  1004. $host = $hostinfo[1];
  1005. $port = $hostinfo[2];
  1006. }
  1007. if ($this->smtp->Connect(($ssl ? 'ssl://':'').$host, $port, $this->Timeout, $options)) {
  1008. try {
  1009. if ($this->Helo) {
  1010. $hello = $this->Helo;
  1011. } else {
  1012. $hello = $this->ServerHostname();
  1013. }
  1014. $this->smtp->Hello($hello);
  1015. if ($tls) {
  1016. if (!$this->smtp->StartTLS()) {
  1017. throw new phpmailerException($this->Lang('connect_host'));
  1018. }
  1019. //We must resend HELO after tls negotiation
  1020. $this->smtp->Hello($hello);
  1021. }
  1022. if ($this->SMTPAuth) {
  1023. if (!$this->smtp->Authenticate($this->Username, $this->Password, $this->AuthType, $this->Realm, $this->Workstation)) {
  1024. throw new phpmailerException($this->Lang('authenticate'));
  1025. }
  1026. }
  1027. return true;
  1028. } catch (phpmailerException $e) {
  1029. $lastexception = $e;
  1030. //We must have connected, but then failed TLS or Auth, so close connection nicely
  1031. $this->smtp->Quit();
  1032. }
  1033. }
  1034. }
  1035. //If we get here, all connection attempts have failed, so close connection hard
  1036. $this->smtp->Close();
  1037. //As we've caught all exceptions, just report whatever the last one was
  1038. if ($this->exceptions and !is_null($lastexception)) {
  1039. throw $lastexception;
  1040. }
  1041. return false;
  1042. }
  1043. /**
  1044. * Closes the active SMTP session if one exists.
  1045. * @return void
  1046. */
  1047. public function SmtpClose() {
  1048. if ($this->smtp !== null) {
  1049. if($this->smtp->Connected()) {
  1050. $this->smtp->Quit();
  1051. $this->smtp->Close();
  1052. }
  1053. }
  1054. }
  1055. /**
  1056. * Sets the language for all class error messages.
  1057. * Returns false if it cannot load the language file. The default language is English.
  1058. * @param string $langcode ISO 639-1 2-character language code (e.g. Portuguese: "br")
  1059. * @param string $lang_path Path to the language file directory
  1060. * @return bool
  1061. * @access public
  1062. */
  1063. function SetLanguage($langcode = 'en', $lang_path = 'language/') {
  1064. //Define full set of translatable strings
  1065. $PHPMAILER_LANG = array(
  1066. 'authenticate' => 'SMTP Error: Could not authenticate.',
  1067. 'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
  1068. 'data_not_accepted' => 'SMTP Error: Data not accepted.',
  1069. 'empty_message' => 'Message body empty',
  1070. 'encoding' => 'Unknown encoding: ',
  1071. 'execute' => 'Could not execute: ',
  1072. 'file_access' => 'Could not access file: ',
  1073. 'file_open' => 'File Error: Could not open file: ',
  1074. 'from_failed' => 'The following From address failed: ',
  1075. 'instantiate' => 'Could not instantiate mail function.',
  1076. 'invalid_address' => 'Invalid address',
  1077. 'mailer_not_supported' => ' mailer is not supported.',
  1078. 'provide_address' => 'You must provide at least one recipient email address.',
  1079. 'recipients_failed' => 'SMTP Error: The following recipients failed: ',
  1080. 'signing' => 'Signing Error: ',
  1081. 'smtp_connect_failed' => 'SMTP Connect() failed.',
  1082. 'smtp_error' => 'SMTP server error: ',
  1083. 'variable_set' => 'Cannot set or reset variable: '
  1084. );
  1085. //Overwrite language-specific strings. This way we'll never have missing translations - no more "language string failed to load"!
  1086. $l = true;
  1087. if ($langcode != 'en') { //There is no English translation file
  1088. $l = @include $lang_path.'phpmailer.lang-'.$langcode.'.php';
  1089. }
  1090. $this->language = $PHPMAILER_LANG;
  1091. return ($l == true); //Returns false if language not found
  1092. }
  1093. /**
  1094. * Return the current array of language strings
  1095. * @return array
  1096. */
  1097. public function GetTranslations() {
  1098. return $this->language;
  1099. }
  1100. /////////////////////////////////////////////////
  1101. // METHODS, MESSAGE CREATION
  1102. /////////////////////////////////////////////////
  1103. /**
  1104. * Creates recipient headers.
  1105. * @access public
  1106. * @param string $type
  1107. * @param array $addr
  1108. * @return string
  1109. */
  1110. public function AddrAppend($type, $addr) {
  1111. $addr_str = $type . ': ';
  1112. $addresses = array();
  1113. foreach ($addr as $a) {
  1114. $addresses[] = $this->AddrFormat($a);
  1115. }
  1116. $addr_str .= implode(', ', $addresses);
  1117. $addr_str .= $this->LE;
  1118. return $addr_str;
  1119. }
  1120. /**
  1121. * Formats an address correctly.
  1122. * @access public
  1123. * @param string $addr
  1124. * @return string
  1125. */
  1126. public function AddrFormat($addr) {
  1127. if (empty($addr[1])) {
  1128. return $this->SecureHeader($addr[0]);
  1129. } else {
  1130. return $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">";
  1131. }
  1132. }
  1133. /**
  1134. * Wraps message for use with mailers that do not
  1135. * automatically perform wrapping and for quoted-printable.
  1136. * Original written by philippe.
  1137. * @param string $message The message to wrap
  1138. * @param integer $length The line length to wrap to
  1139. * @param boolean $qp_mode Whether to run in Quoted-Printable mode
  1140. * @access public
  1141. * @return string
  1142. */
  1143. public function WrapText($message, $length, $qp_mode = false) {
  1144. $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE;
  1145. // If utf-8 encoding is used, we will need to make sure we don't
  1146. // split multibyte characters when we wrap
  1147. $is_utf8 = (strtolower($this->CharSet) == "utf-8");
  1148. $lelen = strlen($this->LE);
  1149. $crlflen = strlen(self::CRLF);
  1150. $message = $this->FixEOL($message);
  1151. if (substr($message, -$lelen) == $this->LE) {
  1152. $message = substr($message, 0, -$lelen);
  1153. }
  1154. $line = explode($this->LE, $message); // Magic. We know FixEOL uses $LE
  1155. $message = '';
  1156. for ($i = 0 ;$i < count($line); $i++) {
  1157. $line_part = explode(' ', $line[$i]);
  1158. $buf = '';
  1159. for ($e = 0; $e<count($line_part); $e++) {
  1160. $word = $line_part[$e];
  1161. if ($qp_mode and (strlen($word) > $length)) {
  1162. $space_left = $length - strlen($buf) - $crlflen;
  1163. if ($e != 0) {
  1164. if ($space_left > 20) {
  1165. $len = $space_left;
  1166. if ($is_utf8) {
  1167. $len = $this->UTF8CharBoundary($word, $len);
  1168. } elseif (substr($word, $len - 1, 1) == "=") {
  1169. $len--;
  1170. } elseif (substr($word, $len - 2, 1) == "=") {
  1171. $len -= 2;
  1172. }
  1173. $part = substr($word, 0, $len);
  1174. $word = substr($word, $len);
  1175. $buf .= ' ' . $part;
  1176. $message .= $buf . sprintf("=%s", self::CRLF);
  1177. } else {
  1178. $message .= $buf . $soft_break;
  1179. }
  1180. $buf = '';
  1181. }
  1182. while (strlen($word) > 0) {
  1183. if ($length <= 0) {
  1184. break;
  1185. }
  1186. $len = $length;
  1187. if ($is_utf8) {
  1188. $len = $this->UTF8CharBoundary($word, $len);
  1189. } elseif (substr($word, $len - 1, 1) == "=") {
  1190. $len--;
  1191. } elseif (substr($word, $len - 2, 1) == "=") {
  1192. $len -= 2;
  1193. }
  1194. $part = substr($word, 0, $len);
  1195. $word = substr($word, $len);
  1196. if (strlen($word) > 0) {
  1197. $message .= $part . sprintf("=%s", self::CRLF);
  1198. } else {
  1199. $buf = $part;
  1200. }
  1201. }
  1202. } else {
  1203. $buf_o = $buf;
  1204. $buf .= ($e == 0) ? $word : (' ' . $word);
  1205. if (strlen($buf) > $length and $buf_o != '') {
  1206. $message .= $buf_o . $soft_break;
  1207. $buf = $word;
  1208. }
  1209. }
  1210. }
  1211. $message .= $buf . self::CRLF;
  1212. }
  1213. return $message;
  1214. }
  1215. /**
  1216. * Finds last character boundary prior to maxLength in a utf-8
  1217. * quoted (printable) encoded string.
  1218. * Original written by Colin Brown.
  1219. * @access public
  1220. * @param string $encodedText utf-8 QP text
  1221. * @param int $maxLength find last character boundary prior to this length
  1222. * @return int
  1223. */
  1224. public function UTF8CharBoundary($encodedText, $maxLength) {
  1225. $foundSplitPos = false;
  1226. $lookBack = 3;
  1227. while (!$foundSplitPos) {
  1228. $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
  1229. $encodedCharPos = strpos($lastChunk, "=");
  1230. if ($encodedCharPos !== false) {
  1231. // Found start of encoded character byte within $lookBack block.
  1232. // Check the encoded byte value (the 2 chars after the '=')
  1233. $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
  1234. $dec = hexdec($hex);
  1235. if ($dec < 128) { // Single byte character.
  1236. // If the encoded char was found at pos 0, it will fit
  1237. // otherwise reduce maxLength to start of the encoded char
  1238. $maxLength = ($encodedCharPos == 0) ? $maxLength :
  1239. $maxLength - ($lookBack - $encodedCharPos);
  1240. $foundSplitPos = true;
  1241. } elseif ($dec >= 192) { // First byte of a multi byte character
  1242. // Reduce maxLength to split at start of character
  1243. $maxLength = $maxLength - ($lookBack - $encodedCharPos);
  1244. $foundSplitPos = true;
  1245. } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back
  1246. $lookBack += 3;
  1247. }
  1248. } else {
  1249. // No encoded character found
  1250. $foundSplitPos = true;
  1251. }
  1252. }
  1253. return $maxLength;
  1254. }
  1255. /**
  1256. * Set the body wrapping.
  1257. * @access public
  1258. * @return void
  1259. */
  1260. public function SetWordWrap() {
  1261. if($this->WordWrap < 1) {
  1262. return;
  1263. }
  1264. switch($this->message_type) {
  1265. case 'alt':
  1266. case 'alt_inline':
  1267. case 'alt_attach':
  1268. case 'alt_inline_attach':
  1269. $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap);
  1270. break;
  1271. default:
  1272. $this->Body = $this->WrapText($this->Body, $this->WordWrap);
  1273. break;
  1274. }
  1275. }
  1276. /**
  1277. * Assembles message header.
  1278. * @access public
  1279. * @return string The assembled header
  1280. */
  1281. public function CreateHeader() {
  1282. $result = '';
  1283. // Set the boundaries
  1284. $uniq_id = md5(uniqid(time()));
  1285. $this->boundary[1] = 'b1_' . $uniq_id;
  1286. $this->boundary[2] = 'b2_' . $uniq_id;
  1287. $this->boundary[3] = 'b3_' . $uniq_id;
  1288. if ($this->MessageDate == '') {
  1289. $result .= $this->HeaderLine('Date', self::RFCDate());
  1290. } else {
  1291. $result .= $this->HeaderLine('Date', $this->MessageDate);
  1292. }
  1293. if ($this->ReturnPath) {
  1294. $result .= $this->HeaderLine('Return-Path', '<'.trim($this->ReturnPath).'>');
  1295. } elseif ($this->Sender == '') {
  1296. $result .= $this->HeaderLine('Return-Path', '<'.trim($this->From).'>');
  1297. } else {
  1298. $result .= $this->HeaderLine('Return-Path', '<'.trim($this->Sender).'>');
  1299. }
  1300. // To be created automatically by mail()
  1301. if($this->Mailer != 'mail') {
  1302. if ($this->SingleTo === true) {
  1303. foreach($this->to as $t) {
  1304. $this->SingleToArray[] = $this->AddrFormat($t);
  1305. }
  1306. } else {
  1307. if(count($this->to) > 0) {
  1308. $result .= $this->AddrAppend('To', $this->to);
  1309. } elseif (count($this->cc) == 0) {
  1310. $result .= $this->HeaderLine('To', 'undisclosed-recipients:;');
  1311. }
  1312. }
  1313. }
  1314. $from = array();
  1315. $from[0][0] = trim($this->From);
  1316. $from[0][1] = $this->FromName;
  1317. $result .= $this->AddrAppend('From', $from);
  1318. // sendmail and mail() extract Cc from the header before sending
  1319. if(count($this->cc) > 0) {
  1320. $result .= $this->AddrAppend('Cc', $this->cc);
  1321. }
  1322. // sendmail and mail() extract Bcc from the header before sending
  1323. if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) {
  1324. $result .= $this->AddrAppend('Bcc', $this->bcc);
  1325. }
  1326. if(count($this->ReplyTo) > 0) {
  1327. $result .= $this->AddrAppend('Reply-To', $this->ReplyTo);
  1328. }
  1329. // mail() sets the subject itself
  1330. if($this->Mailer != 'mail') {
  1331. $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject)));
  1332. }
  1333. if($this->MessageID != '') {
  1334. $result .= $this->HeaderLine('Message-ID', $this->MessageID);
  1335. } else {
  1336. $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);
  1337. }
  1338. $result .= $this->HeaderLine('X-Priority', $this->Priority);
  1339. if ($this->XMailer == '') {
  1340. $result .= $this->HeaderLine('X-Mailer', 'PHPMailer '.$this->Version.' (https://github.com/PHPMailer/PHPMailer/)');
  1341. } else {
  1342. $myXmailer = trim($this->XMailer);
  1343. if ($myXmailer) {
  1344. $result .= $this->HeaderLine('X-Mailer', $myXmailer);
  1345. }
  1346. }
  1347. if($this->ConfirmReadingTo != '') {
  1348. $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>');
  1349. }
  1350. // Add custom headers
  1351. for($index = 0; $index < count($this->CustomHeader); $index++) {
  1352. $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1])));
  1353. }
  1354. if (!$this->sign_key_file) {
  1355. $result .= $this->HeaderLine('MIME-Version', '1.0');
  1356. $result .= $this->GetMailMIME();
  1357. }
  1358. return $result;
  1359. }
  1360. /**
  1361. * Returns the message MIME.
  1362. * @access public
  1363. * @return string
  1364. */
  1365. public function GetMailMIME() {
  1366. $result = '';
  1367. switch($this->message_type) {
  1368. case 'inline':
  1369. $result .= $this->HeaderLine('Content-Type', 'multipart/related;');
  1370. $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1].'"');
  1371. break;
  1372. case 'attach':
  1373. case 'inline_attach':
  1374. case 'alt_attach':
  1375. case 'alt_inline_attach':
  1376. $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;');
  1377. $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1].'"');
  1378. break;
  1379. case 'alt':
  1380. case 'alt_inline':
  1381. $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
  1382. $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1].'"');
  1383. break;
  1384. default:
  1385. // Catches case 'plain': and case '':
  1386. $result .= $this->TextLine('Content-Type: '.$this->ContentType.'; charset='.$this->CharSet);
  1387. break;
  1388. }
  1389. //RFC1341 part 5 says 7bit is assumed if not specified
  1390. if ($this->Encoding != '7bit') {
  1391. $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding);
  1392. }
  1393. if($this->Mailer != 'mail') {
  1394. $result .= $this->LE;
  1395. }
  1396. return $result;
  1397. }
  1398. /**
  1399. * Returns the MIME message (headers and body). Only really valid post PreSend().
  1400. * @access public
  1401. * @return string
  1402. */
  1403. public function GetSentMIMEMessage() {
  1404. return $this->MIMEHeader . $this->mailHeader . self::CRLF . $this->MIMEBody;
  1405. }
  1406. /**
  1407. * Assembles the message body. Returns an empty string on failure.
  1408. * @access public
  1409. * @throws phpmailerException
  1410. * @return string The assembled message body
  1411. */
  1412. public function CreateBody() {
  1413. $body = '';
  1414. if ($this->sign_key_file) {
  1415. $body .= $this->GetMailMIME().$this->LE;
  1416. }
  1417. $this->SetWordWrap();
  1418. switch($this->message_type) {
  1419. case 'inline':
  1420. $body .= $this->GetBoundary($this->boundary[1], '', '', '');
  1421. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1422. $body .= $this->LE.$this->LE;
  1423. $body .= $this->AttachAll('inline', $this->boundary[1]);
  1424. break;
  1425. case 'attach':
  1426. $body .= $this->GetBoundary($this->boundary[1], '', '', '');
  1427. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1428. $body .= $this->LE.$this->LE;
  1429. $body .= $this->AttachAll('attachment', $this->boundary[1]);
  1430. break;
  1431. case 'inline_attach':
  1432. $body .= $this->TextLine('--' . $this->boundary[1]);
  1433. $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
  1434. $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2].'"');
  1435. $body .= $this->LE;
  1436. $body .= $this->GetBoundary($this->boundary[2], '', '', '');
  1437. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1438. $body .= $this->LE.$this->LE;
  1439. $body .= $this->AttachAll('inline', $this->boundary[2]);
  1440. $body .= $this->LE;
  1441. $body .= $this->AttachAll('attachment', $this->boundary[1]);
  1442. break;
  1443. case 'alt':
  1444. $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
  1445. $body .= $this->EncodeString($this->AltBody, $this->Encoding);
  1446. $body .= $this->LE.$this->LE;
  1447. $body .= $this->GetBoundary($this->boundary[1], '', 'text/html', '');
  1448. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1449. $body .= $this->LE.$this->LE;
  1450. if(!empty($this->Ical)) {
  1451. $body .= $this->GetBoundary($this->boundary[1], '', 'text/calendar; method=REQUEST', '');
  1452. $body .= $this->EncodeString($this->Ical, $this->Encoding);
  1453. $body .= $this->LE.$this->LE;
  1454. }
  1455. $body .= $this->EndBoundary($this->boundary[1]);
  1456. break;
  1457. case 'alt_inline':
  1458. $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
  1459. $body .= $this->EncodeString($this->AltBody, $this->Encoding);
  1460. $body .= $this->LE.$this->LE;
  1461. $body .= $this->TextLine('--' . $this->boundary[1]);
  1462. $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
  1463. $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2].'"');
  1464. $body .= $this->LE;
  1465. $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '');
  1466. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1467. $body .= $this->LE.$this->LE;
  1468. $body .= $this->AttachAll('inline', $this->boundary[2]);
  1469. $body .= $this->LE;
  1470. $body .= $this->EndBoundary($this->boundary[1]);
  1471. break;
  1472. case 'alt_attach':
  1473. $body .= $this->TextLine('--' . $this->boundary[1]);
  1474. $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
  1475. $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2].'"');
  1476. $body .= $this->LE;
  1477. $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '');
  1478. $body .= $this->EncodeString($this->AltBody, $this->Encoding);
  1479. $body .= $this->LE.$this->LE;
  1480. $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '');
  1481. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1482. $body .= $this->LE.$this->LE;
  1483. $body .= $this->EndBoundary($this->boundary[2]);
  1484. $body .= $this->LE;
  1485. $body .= $this->AttachAll('attachment', $this->boundary[1]);
  1486. break;
  1487. case 'alt_inline_attach':
  1488. $body .= $this->TextLine('--' . $this->boundary[1]);
  1489. $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
  1490. $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2].'"');
  1491. $body .= $this->LE;
  1492. $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '');
  1493. $body .= $this->EncodeString($this->AltBody, $this->Encoding);
  1494. $body .= $this->LE.$this->LE;
  1495. $body .= $this->TextLine('--' . $this->boundary[2]);
  1496. $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
  1497. $body .= $this->TextLine("\tboundary=\"" . $this->boundary[3].'"');
  1498. $body .= $this->LE;
  1499. $body .= $this->GetBoundary($this->boundary[3], '', 'text/html', '');
  1500. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1501. $body .= $this->LE.$this->LE;
  1502. $body .= $this->AttachAll('inline', $this->boundary[3]);
  1503. $body .= $this->LE;
  1504. $body .= $this->EndBoundary($this->boundary[2]);
  1505. $body .= $this->LE;
  1506. $body .= $this->AttachAll('attachment', $this->boundary[1]);
  1507. break;
  1508. default:
  1509. // catch case 'plain' and case ''
  1510. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1511. break;
  1512. }
  1513. if ($this->IsError()) {
  1514. $body = '';
  1515. } elseif ($this->sign_key_file) {
  1516. try {
  1517. if (!defined('PKCS7_TEXT')) {
  1518. throw new phpmailerException($this->Lang('signing').' OpenSSL extension missing.');
  1519. }
  1520. $file = tempnam(sys_get_temp_dir(), 'mail');
  1521. file_put_contents($file, $body); //TODO check this worked
  1522. $signed = tempnam(sys_get_temp_dir(), 'signed');
  1523. if (@openssl_pkcs7_sign($file, $signed, 'file://'.realpath($this->sign_cert_file), array('file://'.realpath($this->sign_key_file), $this->sign_key_pass), null)) {
  1524. @unlink($file);
  1525. $body = file_get_contents($signed);
  1526. @unlink($signed);
  1527. } else {
  1528. @unlink($file);
  1529. @unlink($signed);
  1530. throw new phpmailerException($this->Lang('signing').openssl_error_string());
  1531. }
  1532. } catch (phpmailerException $e) {
  1533. $body = '';
  1534. if ($this->exceptions) {
  1535. throw $e;
  1536. }
  1537. }
  1538. }
  1539. return $body;
  1540. }
  1541. /**
  1542. * Returns the start of a message boundary.
  1543. * @access protected
  1544. * @param string $boundary
  1545. * @param string $charSet
  1546. * @param string $contentType
  1547. * @param string $encoding
  1548. * @return string
  1549. */
  1550. protected function GetBoundary($boundary, $charSet, $contentType, $encoding) {
  1551. $result = '';
  1552. if($charSet == '') {
  1553. $charSet = $this->CharSet;
  1554. }
  1555. if($contentType == '') {
  1556. $contentType = $this->ContentType;
  1557. }
  1558. if($encoding == '') {
  1559. $encoding = $this->Encoding;
  1560. }
  1561. $result .= $this->TextLine('--' . $boundary);
  1562. $result .= sprintf("Content-Type: %s; charset=%s", $contentType, $charSet);
  1563. $result .= $this->LE;
  1564. $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding);
  1565. $result .= $this->LE;
  1566. return $result;
  1567. }
  1568. /**
  1569. * Returns the end of a message boundary.
  1570. * @access protected
  1571. * @param string $boundary
  1572. * @return string
  1573. */
  1574. protected function EndBoundary($boundary) {
  1575. return $this->LE . '--' . $boundary . '--' . $this->LE;
  1576. }
  1577. /**
  1578. * Sets the message type.
  1579. * @access protected
  1580. * @return void
  1581. */
  1582. protected function SetMessageType() {
  1583. $this->message_type = array();
  1584. if($this->AlternativeExists()) $this->message_type[] = "alt";
  1585. if($this->InlineImageExists()) $this->message_type[] = "inline";
  1586. if($this->AttachmentExists()) $this->message_type[] = "attach";
  1587. $this->message_type = implode("_", $this->message_type);
  1588. if($this->message_type == "") $this->message_type = "plain";
  1589. }
  1590. /**
  1591. * Returns a formatted header line.
  1592. * @access public
  1593. * @param string $name
  1594. * @param string $value
  1595. * @return string
  1596. */
  1597. public function HeaderLine($name, $value) {
  1598. return $name . ': ' . $value . $this->LE;
  1599. }
  1600. /**
  1601. * Returns a formatted mail line.
  1602. * @access public
  1603. * @param string $value
  1604. * @return string
  1605. */
  1606. public function TextLine($value) {
  1607. return $value . $this->LE;
  1608. }
  1609. /////////////////////////////////////////////////
  1610. // CLASS METHODS, ATTACHMENTS
  1611. /////////////////////////////////////////////////
  1612. /**
  1613. * Adds an attachment from a path on the filesystem.
  1614. * Returns false if the file could not be found
  1615. * or accessed.
  1616. * @param string $path Path to the attachment.
  1617. * @param string $name Overrides the attachment name.
  1618. * @param string $encoding File encoding (see $Encoding).
  1619. * @param string $type File extension (MIME) type.
  1620. * @param string $disposition Disposition to use
  1621. * @throws phpmailerException
  1622. * @return bool
  1623. */
  1624. public function AddAttachment($path, $name = '', $encoding = 'base64', $type = '', $disposition = 'attachment') {
  1625. try {
  1626. if ( !@is_file($path) ) {
  1627. throw new phpmailerException($this->Lang('file_access') . $path, self::STOP_CONTINUE);
  1628. }
  1629. //If a MIME type is not specified, try to work it out from the file name
  1630. if ($type == '') {
  1631. $type = self::filenameToType($path);
  1632. }
  1633. $filename = basename($path);
  1634. if ( $name == '' ) {
  1635. $name = $filename;
  1636. }
  1637. $this->attachment[] = array(
  1638. 0 => $path,
  1639. 1 => $filename,
  1640. 2 => $name,
  1641. 3 => $encoding,
  1642. 4 => $type,
  1643. 5 => false, // isStringAttachment
  1644. 6 => $disposition,
  1645. 7 => 0
  1646. );
  1647. } catch (phpmailerException $e) {
  1648. $this->SetError($e->getMessage());
  1649. if ($this->exceptions) {
  1650. throw $e;
  1651. }
  1652. if ($this->SMTPDebug) {
  1653. $this->edebug($e->getMessage()."\n");
  1654. }
  1655. return false;
  1656. }
  1657. return true;
  1658. }
  1659. /**
  1660. * Return the current array of attachments
  1661. * @return array
  1662. */
  1663. public function GetAttachments() {
  1664. return $this->attachment;
  1665. }
  1666. /**
  1667. * Attaches all fs, string, and binary attachments to the message.
  1668. * Returns an empty string on failure.
  1669. * @access protected
  1670. * @param string $disposition_type
  1671. * @param string $boundary
  1672. * @return string
  1673. */
  1674. protected function AttachAll($disposition_type, $boundary) {
  1675. // Return text of body
  1676. $mime = array();
  1677. $cidUniq = array();
  1678. $incl = array();
  1679. // Add all attachments
  1680. foreach ($this->attachment as $attachment) {
  1681. // CHECK IF IT IS A VALID DISPOSITION_FILTER
  1682. if($attachment[6] == $disposition_type) {
  1683. // Check for string attachment
  1684. $string = '';
  1685. $path = '';
  1686. $bString = $attachment[5];
  1687. if ($bString) {
  1688. $string = $attachment[0];
  1689. } else {
  1690. $path = $attachment[0];
  1691. }
  1692. $inclhash = md5(serialize($attachment));
  1693. if (in_array($inclhash, $incl)) { continue; }
  1694. $incl[] = $inclhash;
  1695. $filename = $attachment[1];
  1696. $name = $attachment[2];
  1697. $encoding = $attachment[3];
  1698. $type = $attachment[4];
  1699. $disposition = $attachment[6];
  1700. $cid = $attachment[7];
  1701. if ( $disposition == 'inline' && isset($cidUniq[$cid]) ) { continue; }
  1702. $cidUniq[$cid] = true;
  1703. $mime[] = sprintf("--%s%s", $boundary, $this->LE);
  1704. $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $this->EncodeHeader($this->SecureHeader($name)), $this->LE);
  1705. $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE);
  1706. if($disposition == 'inline') {
  1707. $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE);
  1708. }
  1709. //If a filename contains any of these chars, it should be quoted, but not otherwise: RFC2183 & RFC2045 5.1
  1710. //Fixes a warning in IETF's msglint MIME checker
  1711. //
  1712. // Allow for bypassing the Content-Disposition header totally
  1713. if (!(empty($disposition))) {
  1714. if (preg_match('/[ \(\)<>@,;:\\"\/\[\]\?=]/', $name)) {
  1715. $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE);
  1716. } else {
  1717. $mime[] = sprintf("Content-Disposition: %s; filename=%s%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE);
  1718. }
  1719. } else {
  1720. $mime[] = $this->LE;
  1721. }
  1722. // Encode as string attachment
  1723. if($bString) {
  1724. $mime[] = $this->EncodeString($string, $encoding);
  1725. if($this->IsError()) {
  1726. return '';
  1727. }
  1728. $mime[] = $this->LE.$this->LE;
  1729. } else {
  1730. $mime[] = $this->EncodeFile($path, $encoding);
  1731. if($this->IsError()) {
  1732. return '';
  1733. }
  1734. $mime[] = $this->LE.$this->LE;
  1735. }
  1736. }
  1737. }
  1738. $mime[] = sprintf("--%s--%s", $boundary, $this->LE);
  1739. return implode("", $mime);
  1740. }
  1741. /**
  1742. * Encodes attachment in requested format.
  1743. * Returns an empty string on failure.
  1744. * @param string $path The full path to the file
  1745. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  1746. * @throws phpmailerException
  1747. * @see EncodeFile()
  1748. * @access protected
  1749. * @return string
  1750. */
  1751. protected function EncodeFile($path, $encoding = 'base64') {
  1752. try {
  1753. if (!is_readable($path)) {
  1754. throw new phpmailerException($this->Lang('file_open') . $path, self::STOP_CONTINUE);
  1755. }
  1756. $magic_quotes = get_magic_quotes_runtime();
  1757. if ($magic_quotes) {
  1758. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  1759. set_magic_quotes_runtime(0);
  1760. } else {
  1761. ini_set('magic_quotes_runtime', 0);
  1762. }
  1763. }
  1764. $file_buffer = file_get_contents($path);
  1765. $file_buffer = $this->EncodeString($file_buffer, $encoding);
  1766. if ($magic_quotes) {
  1767. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  1768. set_magic_quotes_runtime($magic_quotes);
  1769. } else {
  1770. ini_set('magic_quotes_runtime', $magic_quotes);
  1771. }
  1772. }
  1773. return $file_buffer;
  1774. } catch (Exception $e) {
  1775. $this->SetError($e->getMessage());
  1776. return '';
  1777. }
  1778. }
  1779. /**
  1780. * Encodes string to requested format.
  1781. * Returns an empty string on failure.
  1782. * @param string $str The text to encode
  1783. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  1784. * @access public
  1785. * @return string
  1786. */
  1787. public function EncodeString($str, $encoding = 'base64') {
  1788. $encoded = '';
  1789. switch(strtolower($encoding)) {
  1790. case 'base64':
  1791. $encoded = chunk_split(base64_encode($str), 76, $this->LE);
  1792. break;
  1793. case '7bit':
  1794. case '8bit':
  1795. $encoded = $this->FixEOL($str);
  1796. //Make sure it ends with a line break
  1797. if (substr($encoded, -(strlen($this->LE))) != $this->LE)
  1798. $encoded .= $this->LE;
  1799. break;
  1800. case 'binary':
  1801. $encoded = $str;
  1802. break;
  1803. case 'quoted-printable':
  1804. $encoded = $this->EncodeQP($str);
  1805. break;
  1806. default:
  1807. $this->SetError($this->Lang('encoding') . $encoding);
  1808. break;
  1809. }
  1810. return $encoded;
  1811. }
  1812. /**
  1813. * Encode a header string to best (shortest) of Q, B, quoted or none.
  1814. * @access public
  1815. * @param string $str
  1816. * @param string $position
  1817. * @return string
  1818. */
  1819. public function EncodeHeader($str, $position = 'text') {
  1820. $x = 0;
  1821. switch (strtolower($position)) {
  1822. case 'phrase':
  1823. if (!preg_match('/[\200-\377]/', $str)) {
  1824. // Can't use addslashes as we don't know what value has magic_quotes_sybase
  1825. $encoded = addcslashes($str, "\0..\37\177\\\"");
  1826. if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
  1827. return ($encoded);
  1828. } else {
  1829. return ("\"$encoded\"");
  1830. }
  1831. }
  1832. $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
  1833. break;
  1834. case 'comment':
  1835. $x = preg_match_all('/[()"]/', $str, $matches);
  1836. // Fall-through
  1837. case 'text':
  1838. default:
  1839. $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
  1840. break;
  1841. }
  1842. if ($x == 0) { //There are no chars that need encoding
  1843. return ($str);
  1844. }
  1845. $maxlen = 75 - 7 - strlen($this->CharSet);
  1846. // Try to select the encoding which should produce the shortest output
  1847. if ($x > strlen($str)/3) { //More than a third of the content will need encoding, so B encoding will be most efficient
  1848. $encoding = 'B';
  1849. if (function_exists('mb_strlen') && $this->HasMultiBytes($str)) {
  1850. // Use a custom function which correctly encodes and wraps long
  1851. // multibyte strings without breaking lines within a character
  1852. $encoded = $this->Base64EncodeWrapMB($str, "\n");
  1853. } else {
  1854. $encoded = base64_encode($str);
  1855. $maxlen -= $maxlen % 4;
  1856. $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
  1857. }
  1858. } else {
  1859. $encoding = 'Q';
  1860. $encoded = $this->EncodeQ($str, $position);
  1861. $encoded = $this->WrapText($encoded, $maxlen, true);
  1862. $encoded = str_replace('='.self::CRLF, "\n", trim($encoded));
  1863. }
  1864. $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded);
  1865. $encoded = trim(str_replace("\n", $this->LE, $encoded));
  1866. return $encoded;
  1867. }
  1868. /**
  1869. * Checks if a string contains multibyte characters.
  1870. * @access public
  1871. * @param string $str multi-byte text to wrap encode
  1872. * @return bool
  1873. */
  1874. public function HasMultiBytes($str) {
  1875. if (function_exists('mb_strlen')) {
  1876. return (strlen($str) > mb_strlen($str, $this->CharSet));
  1877. } else { // Assume no multibytes (we can't handle without mbstring functions anyway)
  1878. return false;
  1879. }
  1880. }
  1881. /**
  1882. * Correctly encodes and wraps long multibyte strings for mail headers
  1883. * without breaking lines within a character.
  1884. * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php
  1885. * @access public
  1886. * @param string $str multi-byte text to wrap encode
  1887. * @param string $lf string to use as linefeed/end-of-line
  1888. * @return string
  1889. */
  1890. public function Base64EncodeWrapMB($str, $lf=null) {
  1891. $start = "=?".$this->CharSet."?B?";
  1892. $end = "?=";
  1893. $encoded = "";
  1894. if ($lf === null) {
  1895. $lf = $this->LE;
  1896. }
  1897. $mb_length = mb_strlen($str, $this->CharSet);
  1898. // Each line must have length <= 75, including $start and $end
  1899. $length = 75 - strlen($start) - strlen($end);
  1900. // Average multi-byte ratio
  1901. $ratio = $mb_length / strlen($str);
  1902. // Base64 has a 4:3 ratio
  1903. $offset = $avgLength = floor($length * $ratio * .75);
  1904. for ($i = 0; $i < $mb_length; $i += $offset) {
  1905. $lookBack = 0;
  1906. do {
  1907. $offset = $avgLength - $lookBack;
  1908. $chunk = mb_substr($str, $i, $offset, $this->CharSet);
  1909. $chunk = base64_encode($chunk);
  1910. $lookBack++;
  1911. }
  1912. while (strlen($chunk) > $length);
  1913. $encoded .= $chunk . $lf;
  1914. }
  1915. // Chomp the last linefeed
  1916. $encoded = substr($encoded, 0, -strlen($lf));
  1917. return $encoded;
  1918. }
  1919. /**
  1920. * Encode string to RFC2045 (6.7) quoted-printable format
  1921. * @access public
  1922. * @param string $string The text to encode
  1923. * @param integer $line_max Number of chars allowed on a line before wrapping
  1924. * @return string
  1925. * @link PHP version adapted from http://www.php.net/manual/en/function.quoted-printable-decode.php#89417
  1926. */
  1927. public function EncodeQP($string, $line_max = 76) {
  1928. if (function_exists('quoted_printable_encode')) { //Use native function if it's available (>= PHP5.3)
  1929. return quoted_printable_encode($string);
  1930. }
  1931. //Fall back to a pure PHP implementation
  1932. $string = str_replace(array('%20', '%0D%0A.', '%0D%0A', '%'), array(' ', "\r\n=2E", "\r\n", '='), rawurlencode($string));
  1933. $string = preg_replace('/[^\r\n]{'.($line_max - 3).'}[^=\r\n]{2}/', "$0=\r\n", $string);
  1934. return $string;
  1935. }
  1936. /**
  1937. * Wrapper to preserve BC for old QP encoding function that was removed
  1938. * @see EncodeQP()
  1939. * @access public
  1940. * @param string $string
  1941. * @param integer $line_max
  1942. * @param bool $space_conv
  1943. * @return string
  1944. */
  1945. public function EncodeQPphp($string, $line_max = 76, $space_conv = false) {
  1946. return $this->EncodeQP($string, $line_max);
  1947. }
  1948. /**
  1949. * Encode string to q encoding.
  1950. * @link http://tools.ietf.org/html/rfc2047
  1951. * @param string $str the text to encode
  1952. * @param string $position Where the text is going to be used, see the RFC for what that means
  1953. * @access public
  1954. * @return string
  1955. */
  1956. public function EncodeQ($str, $position = 'text') {
  1957. //There should not be any EOL in the string
  1958. $pattern = '';
  1959. $encoded = str_replace(array("\r", "\n"), '', $str);
  1960. switch (strtolower($position)) {
  1961. case 'phrase':
  1962. $pattern = '^A-Za-z0-9!*+\/ -';
  1963. break;
  1964. case 'comment':
  1965. $pattern = '\(\)"';
  1966. //note that we don't break here!
  1967. //for this reason we build the $pattern without including delimiters and []
  1968. case 'text':
  1969. default:
  1970. //Replace every high ascii, control =, ? and _ characters
  1971. //We put \075 (=) as first value to make sure it's the first one in being converted, preventing double encode
  1972. $pattern = '\075\000-\011\013\014\016-\037\077\137\177-\377' . $pattern;
  1973. break;
  1974. }
  1975. if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
  1976. foreach (array_unique($matches[0]) as $char) {
  1977. $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
  1978. }
  1979. }
  1980. //Replace every spaces to _ (more readable than =20)
  1981. return str_replace(' ', '_', $encoded);
  1982. }
  1983. /**
  1984. * Adds a string or binary attachment (non-filesystem) to the list.
  1985. * This method can be used to attach ascii or binary data,
  1986. * such as a BLOB record from a database.
  1987. * @param string $string String attachment data.
  1988. * @param string $filename Name of the attachment.
  1989. * @param string $encoding File encoding (see $Encoding).
  1990. * @param string $type File extension (MIME) type.
  1991. * @param string $disposition Disposition to use
  1992. * @return void
  1993. */
  1994. public function AddStringAttachment($string, $filename, $encoding = 'base64', $type = '', $disposition = 'attachment') {
  1995. //If a MIME type is not specified, try to work it out from the file name
  1996. if ($type == '') {
  1997. $type = self::filenameToType($filename);
  1998. }
  1999. // Append to $attachment array
  2000. $this->attachment[] = array(
  2001. 0 => $string,
  2002. 1 => $filename,
  2003. 2 => basename($filename),
  2004. 3 => $encoding,
  2005. 4 => $type,
  2006. 5 => true, // isStringAttachment
  2007. 6 => $disposition,
  2008. 7 => 0
  2009. );
  2010. }
  2011. /**
  2012. * Add an embedded attachment from a file.
  2013. * This can include images, sounds, and just about any other document type.
  2014. * @param string $path Path to the attachment.
  2015. * @param string $cid Content ID of the attachment; Use this to reference
  2016. * the content when using an embedded image in HTML.
  2017. * @param string $name Overrides the attachment name.
  2018. * @param string $encoding File encoding (see $Encoding).
  2019. * @param string $type File MIME type.
  2020. * @param string $disposition Disposition to use
  2021. * @return bool True on successfully adding an attachment
  2022. */
  2023. public function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline') {
  2024. if ( !@is_file($path) ) {
  2025. $this->SetError($this->Lang('file_access') . $path);
  2026. return false;
  2027. }
  2028. //If a MIME type is not specified, try to work it out from the file name
  2029. if ($type == '') {
  2030. $type = self::filenameToType($path);
  2031. }
  2032. $filename = basename($path);
  2033. if ( $name == '' ) {
  2034. $name = $filename;
  2035. }
  2036. // Append to $attachment array
  2037. $this->attachment[] = array(
  2038. 0 => $path,
  2039. 1 => $filename,
  2040. 2 => $name,
  2041. 3 => $encoding,
  2042. 4 => $type,
  2043. 5 => false, // isStringAttachment
  2044. 6 => $disposition,
  2045. 7 => $cid
  2046. );
  2047. return true;
  2048. }
  2049. /**
  2050. * Add an embedded stringified attachment.
  2051. * This can include images, sounds, and just about any other document type.
  2052. * Be sure to set the $type to an image type for images:
  2053. * JPEG images use 'image/jpeg', GIF uses 'image/gif', PNG uses 'image/png'.
  2054. * @param string $string The attachment binary data.
  2055. * @param string $cid Content ID of the attachment; Use this to reference
  2056. * the content when using an embedded image in HTML.
  2057. * @param string $name
  2058. * @param string $encoding File encoding (see $Encoding).
  2059. * @param string $type MIME type.
  2060. * @param string $disposition Disposition to use
  2061. * @return bool True on successfully adding an attachment
  2062. */
  2063. public function AddStringEmbeddedImage($string, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline') {
  2064. //If a MIME type is not specified, try to work it out from the name
  2065. if ($type == '') {
  2066. $type = self::filenameToType($name);
  2067. }
  2068. // Append to $attachment array
  2069. $this->attachment[] = array(
  2070. 0 => $string,
  2071. 1 => $name,
  2072. 2 => $name,
  2073. 3 => $encoding,
  2074. 4 => $type,
  2075. 5 => true, // isStringAttachment
  2076. 6 => $disposition,
  2077. 7 => $cid
  2078. );
  2079. return true;
  2080. }
  2081. /**
  2082. * Returns true if an inline attachment is present.
  2083. * @access public
  2084. * @return bool
  2085. */
  2086. public function InlineImageExists() {
  2087. foreach($this->attachment as $attachment) {
  2088. if ($attachment[6] == 'inline') {
  2089. return true;
  2090. }
  2091. }
  2092. return false;
  2093. }
  2094. /**
  2095. * Returns true if an attachment (non-inline) is present.
  2096. * @return bool
  2097. */
  2098. public function AttachmentExists() {
  2099. foreach($this->attachment as $attachment) {
  2100. if ($attachment[6] == 'attachment') {
  2101. return true;
  2102. }
  2103. }
  2104. return false;
  2105. }
  2106. /**
  2107. * Does this message have an alternative body set?
  2108. * @return bool
  2109. */
  2110. public function AlternativeExists() {
  2111. return !empty($this->AltBody);
  2112. }
  2113. /////////////////////////////////////////////////
  2114. // CLASS METHODS, MESSAGE RESET
  2115. /////////////////////////////////////////////////
  2116. /**
  2117. * Clears all recipients assigned in the TO array. Returns void.
  2118. * @return void
  2119. */
  2120. public function ClearAddresses() {
  2121. foreach($this->to as $to) {
  2122. unset($this->all_recipients[strtolower($to[0])]);
  2123. }
  2124. $this->to = array();
  2125. }
  2126. /**
  2127. * Clears all recipients assigned in the CC array. Returns void.
  2128. * @return void
  2129. */
  2130. public function ClearCCs() {
  2131. foreach($this->cc as $cc) {
  2132. unset($this->all_recipients[strtolower($cc[0])]);
  2133. }
  2134. $this->cc = array();
  2135. }
  2136. /**
  2137. * Clears all recipients assigned in the BCC array. Returns void.
  2138. * @return void
  2139. */
  2140. public function ClearBCCs() {
  2141. foreach($this->bcc as $bcc) {
  2142. unset($this->all_recipients[strtolower($bcc[0])]);
  2143. }
  2144. $this->bcc = array();
  2145. }
  2146. /**
  2147. * Clears all recipients assigned in the ReplyTo array. Returns void.
  2148. * @return void
  2149. */
  2150. public function ClearReplyTos() {
  2151. $this->ReplyTo = array();
  2152. }
  2153. /**
  2154. * Clears all recipients assigned in the TO, CC and BCC
  2155. * array. Returns void.
  2156. * @return void
  2157. */
  2158. public function ClearAllRecipients() {
  2159. $this->to = array();
  2160. $this->cc = array();
  2161. $this->bcc = array();
  2162. $this->all_recipients = array();
  2163. }
  2164. /**
  2165. * Clears all previously set filesystem, string, and binary
  2166. * attachments. Returns void.
  2167. * @return void
  2168. */
  2169. public function ClearAttachments() {
  2170. $this->attachment = array();
  2171. }
  2172. /**
  2173. * Clears all custom headers. Returns void.
  2174. * @return void
  2175. */
  2176. public function ClearCustomHeaders() {
  2177. $this->CustomHeader = array();
  2178. }
  2179. /////////////////////////////////////////////////
  2180. // CLASS METHODS, MISCELLANEOUS
  2181. /////////////////////////////////////////////////
  2182. /**
  2183. * Adds the error message to the error container.
  2184. * @access protected
  2185. * @param string $msg
  2186. * @return void
  2187. */
  2188. protected function SetError($msg) {
  2189. $this->error_count++;
  2190. if ($this->Mailer == 'smtp' and !is_null($this->smtp)) {
  2191. $lasterror = $this->smtp->getError();
  2192. if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) {
  2193. $msg .= '<p>' . $this->Lang('smtp_error') . $lasterror['smtp_msg'] . "</p>\n";
  2194. }
  2195. }
  2196. $this->ErrorInfo = $msg;
  2197. }
  2198. /**
  2199. * Returns the proper RFC 822 formatted date.
  2200. * @access public
  2201. * @return string
  2202. * @static
  2203. */
  2204. public static function RFCDate() {
  2205. //Set the time zone to whatever the default is to avoid 500 errors
  2206. //Will default to UTC if it's not set properly in php.ini
  2207. date_default_timezone_set(@date_default_timezone_get());
  2208. return date('D, j M Y H:i:s O');
  2209. }
  2210. /**
  2211. * Returns the server hostname or 'localhost.localdomain' if unknown.
  2212. * @access protected
  2213. * @return string
  2214. */
  2215. protected function ServerHostname() {
  2216. if (!empty($this->Hostname)) {
  2217. $result = $this->Hostname;
  2218. } elseif (isset($_SERVER['SERVER_NAME'])) {
  2219. $result = $_SERVER['SERVER_NAME'];
  2220. } else {
  2221. $result = 'localhost.localdomain';
  2222. }
  2223. return $result;
  2224. }
  2225. /**
  2226. * Returns a message in the appropriate language.
  2227. * @access protected
  2228. * @param string $key
  2229. * @return string
  2230. */
  2231. protected function Lang($key) {
  2232. if(count($this->language) < 1) {
  2233. $this->SetLanguage('en'); // set the default language
  2234. }
  2235. if(isset($this->language[$key])) {
  2236. return $this->language[$key];
  2237. } else {
  2238. return 'Language string failed to load: ' . $key;
  2239. }
  2240. }
  2241. /**
  2242. * Returns true if an error occurred.
  2243. * @access public
  2244. * @return bool
  2245. */
  2246. public function IsError() {
  2247. return ($this->error_count > 0);
  2248. }
  2249. /**
  2250. * Changes every end of line from CRLF, CR or LF to $this->LE.
  2251. * @access public
  2252. * @param string $str String to FixEOL
  2253. * @return string
  2254. */
  2255. public function FixEOL($str) {
  2256. // condense down to \n
  2257. $nstr = str_replace(array("\r\n", "\r"), "\n", $str);
  2258. // Now convert LE as needed
  2259. if ($this->LE !== "\n") {
  2260. $nstr = str_replace("\n", $this->LE, $nstr);
  2261. }
  2262. return $nstr;
  2263. }
  2264. /**
  2265. * Adds a custom header. $name value can be overloaded to contain
  2266. * both header name and value (name:value)
  2267. * @access public
  2268. * @param string $name custom header name
  2269. * @param string $value header value
  2270. * @return void
  2271. */
  2272. public function AddCustomHeader($name, $value=null) {
  2273. if ($value === null) {
  2274. // Value passed in as name:value
  2275. $this->CustomHeader[] = explode(':', $name, 2);
  2276. } else {
  2277. $this->CustomHeader[] = array($name, $value);
  2278. }
  2279. }
  2280. /**
  2281. * Creates a message from an HTML string, making modifications for inline images and backgrounds
  2282. * and creates a plain-text version by converting the HTML
  2283. * Overwrites any existing values in $this->Body and $this->AltBody
  2284. * @access public
  2285. * @param string $message HTML message string
  2286. * @param string $basedir baseline directory for path
  2287. * @param bool $advanced Whether to use the advanced HTML to text converter
  2288. * @return string $message
  2289. */
  2290. public function MsgHTML($message, $basedir = '', $advanced = false) {
  2291. preg_match_all("/(src|background)=[\"'](.*)[\"']/Ui", $message, $images);
  2292. if (isset($images[2])) {
  2293. foreach ($images[2] as $i => $url) {
  2294. // do not change urls for absolute images (thanks to corvuscorax)
  2295. if (!preg_match('#^[A-z]+://#', $url)) {
  2296. $filename = basename($url);
  2297. $directory = dirname($url);
  2298. if ($directory == '.') {
  2299. $directory = '';
  2300. }
  2301. $cid = md5($url).'@phpmailer.0'; //RFC2392 S 2
  2302. if (strlen($basedir) > 1 && substr($basedir, -1) != '/') {
  2303. $basedir .= '/';
  2304. }
  2305. if (strlen($directory) > 1 && substr($directory, -1) != '/') {
  2306. $directory .= '/';
  2307. }
  2308. if ($this->AddEmbeddedImage($basedir.$directory.$filename, $cid, $filename, 'base64', self::_mime_types(self::mb_pathinfo($filename, PATHINFO_EXTENSION)))) {
  2309. $message = preg_replace("/".$images[1][$i]."=[\"']".preg_quote($url, '/')."[\"']/Ui", $images[1][$i]."=\"cid:".$cid."\"", $message);
  2310. }
  2311. }
  2312. }
  2313. }
  2314. $this->IsHTML(true);
  2315. if (empty($this->AltBody)) {
  2316. $this->AltBody = 'To view this email message, open it in a program that understands HTML!' . "\n\n";
  2317. }
  2318. //Convert all message body line breaks to CRLF, makes quoted-printable encoding work much better
  2319. $this->Body = $this->NormalizeBreaks($message);
  2320. $this->AltBody = $this->NormalizeBreaks($this->html2text($message, $advanced));
  2321. return $this->Body;
  2322. }
  2323. /**
  2324. * Convert an HTML string into a plain text version
  2325. * @param string $html The HTML text to convert
  2326. * @param bool $advanced Should this use the more complex html2text converter or just a simple one?
  2327. * @return string
  2328. */
  2329. public function html2text($html, $advanced = false) {
  2330. if ($advanced) {
  2331. require_once 'extras/class.html2text.php';
  2332. $h = new html2text($html);
  2333. return $h->get_text();
  2334. }
  2335. return html_entity_decode(trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))), ENT_QUOTES, $this->CharSet);
  2336. }
  2337. /**
  2338. * Gets the MIME type of the embedded or inline image
  2339. * @param string $ext File extension
  2340. * @access public
  2341. * @return string MIME type of ext
  2342. * @static
  2343. */
  2344. public static function _mime_types($ext = '') {
  2345. $mimes = array(
  2346. 'xl' => 'application/excel',
  2347. 'hqx' => 'application/mac-binhex40',
  2348. 'cpt' => 'application/mac-compactpro',
  2349. 'bin' => 'application/macbinary',
  2350. 'doc' => 'application/msword',
  2351. 'word' => 'application/msword',
  2352. 'class' => 'application/octet-stream',
  2353. 'dll' => 'application/octet-stream',
  2354. 'dms' => 'application/octet-stream',
  2355. 'exe' => 'application/octet-stream',
  2356. 'lha' => 'application/octet-stream',
  2357. 'lzh' => 'application/octet-stream',
  2358. 'psd' => 'application/octet-stream',
  2359. 'sea' => 'application/octet-stream',
  2360. 'so' => 'application/octet-stream',
  2361. 'oda' => 'application/oda',
  2362. 'pdf' => 'application/pdf',
  2363. 'ai' => 'application/postscript',
  2364. 'eps' => 'application/postscript',
  2365. 'ps' => 'application/postscript',
  2366. 'smi' => 'application/smil',
  2367. 'smil' => 'application/smil',
  2368. 'mif' => 'application/vnd.mif',
  2369. 'xls' => 'application/vnd.ms-excel',
  2370. 'ppt' => 'application/vnd.ms-powerpoint',
  2371. 'wbxml' => 'application/vnd.wap.wbxml',
  2372. 'wmlc' => 'application/vnd.wap.wmlc',
  2373. 'dcr' => 'application/x-director',
  2374. 'dir' => 'application/x-director',
  2375. 'dxr' => 'application/x-director',
  2376. 'dvi' => 'application/x-dvi',
  2377. 'gtar' => 'application/x-gtar',
  2378. 'php3' => 'application/x-httpd-php',
  2379. 'php4' => 'application/x-httpd-php',
  2380. 'php' => 'application/x-httpd-php',
  2381. 'phtml' => 'application/x-httpd-php',
  2382. 'phps' => 'application/x-httpd-php-source',
  2383. 'js' => 'application/x-javascript',
  2384. 'swf' => 'application/x-shockwave-flash',
  2385. 'sit' => 'application/x-stuffit',
  2386. 'tar' => 'application/x-tar',
  2387. 'tgz' => 'application/x-tar',
  2388. 'xht' => 'application/xhtml+xml',
  2389. 'xhtml' => 'application/xhtml+xml',
  2390. 'zip' => 'application/zip',
  2391. 'mid' => 'audio/midi',
  2392. 'midi' => 'audio/midi',
  2393. 'mp2' => 'audio/mpeg',
  2394. 'mp3' => 'audio/mpeg',
  2395. 'mpga' => 'audio/mpeg',
  2396. 'aif' => 'audio/x-aiff',
  2397. 'aifc' => 'audio/x-aiff',
  2398. 'aiff' => 'audio/x-aiff',
  2399. 'ram' => 'audio/x-pn-realaudio',
  2400. 'rm' => 'audio/x-pn-realaudio',
  2401. 'rpm' => 'audio/x-pn-realaudio-plugin',
  2402. 'ra' => 'audio/x-realaudio',
  2403. 'wav' => 'audio/x-wav',
  2404. 'bmp' => 'image/bmp',
  2405. 'gif' => 'image/gif',
  2406. 'jpeg' => 'image/jpeg',
  2407. 'jpe' => 'image/jpeg',
  2408. 'jpg' => 'image/jpeg',
  2409. 'png' => 'image/png',
  2410. 'tiff' => 'image/tiff',
  2411. 'tif' => 'image/tiff',
  2412. 'eml' => 'message/rfc822',
  2413. 'css' => 'text/css',
  2414. 'html' => 'text/html',
  2415. 'htm' => 'text/html',
  2416. 'shtml' => 'text/html',
  2417. 'log' => 'text/plain',
  2418. 'text' => 'text/plain',
  2419. 'txt' => 'text/plain',
  2420. 'rtx' => 'text/richtext',
  2421. 'rtf' => 'text/rtf',
  2422. 'xml' => 'text/xml',
  2423. 'xsl' => 'text/xml',
  2424. 'mpeg' => 'video/mpeg',
  2425. 'mpe' => 'video/mpeg',
  2426. 'mpg' => 'video/mpeg',
  2427. 'mov' => 'video/quicktime',
  2428. 'qt' => 'video/quicktime',
  2429. 'rv' => 'video/vnd.rn-realvideo',
  2430. 'avi' => 'video/x-msvideo',
  2431. 'movie' => 'video/x-sgi-movie'
  2432. );
  2433. return (!isset($mimes[strtolower($ext)])) ? 'application/octet-stream' : $mimes[strtolower($ext)];
  2434. }
  2435. /**
  2436. * Try to map a file name to a MIME type, default to application/octet-stream
  2437. * @param string $filename A file name or full path, does not need to exist as a file
  2438. * @return string
  2439. * @static
  2440. */
  2441. public static function filenameToType($filename) {
  2442. //In case the path is a URL, strip any query string before getting extension
  2443. $qpos = strpos($filename, '?');
  2444. if ($qpos !== false) {
  2445. $filename = substr($filename, 0, $qpos);
  2446. }
  2447. $pathinfo = self::mb_pathinfo($filename);
  2448. return self::_mime_types($pathinfo['extension']);
  2449. }
  2450. /**
  2451. * Drop-in replacement for pathinfo(), but multibyte-safe, cross-platform-safe, old-version-safe.
  2452. * Works similarly to the one in PHP >= 5.2.0
  2453. * @link http://www.php.net/manual/en/function.pathinfo.php#107461
  2454. * @param string $path A filename or path, does not need to exist as a file
  2455. * @param integer|string $options Either a PATHINFO_* constant, or a string name to return only the specified piece, allows 'filename' to work on PHP < 5.2
  2456. * @return string|array
  2457. * @static
  2458. */
  2459. public static function mb_pathinfo($path, $options = null) {
  2460. $ret = array('dirname' => '', 'basename' => '', 'extension' => '', 'filename' => '');
  2461. $m = array();
  2462. preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', $path, $m);
  2463. if(array_key_exists(1, $m)) {
  2464. $ret['dirname'] = $m[1];
  2465. }
  2466. if(array_key_exists(2, $m)) {
  2467. $ret['basename'] = $m[2];
  2468. }
  2469. if(array_key_exists(5, $m)) {
  2470. $ret['extension'] = $m[5];
  2471. }
  2472. if(array_key_exists(3, $m)) {
  2473. $ret['filename'] = $m[3];
  2474. }
  2475. switch($options) {
  2476. case PATHINFO_DIRNAME:
  2477. case 'dirname':
  2478. return $ret['dirname'];
  2479. break;
  2480. case PATHINFO_BASENAME:
  2481. case 'basename':
  2482. return $ret['basename'];
  2483. break;
  2484. case PATHINFO_EXTENSION:
  2485. case 'extension':
  2486. return $ret['extension'];
  2487. break;
  2488. case PATHINFO_FILENAME:
  2489. case 'filename':
  2490. return $ret['filename'];
  2491. break;
  2492. default:
  2493. return $ret;
  2494. }
  2495. }
  2496. /**
  2497. * Set (or reset) Class Objects (variables)
  2498. *
  2499. * Usage Example:
  2500. * $page->set('X-Priority', '3');
  2501. *
  2502. * @access public
  2503. * @param string $name
  2504. * @param mixed $value
  2505. * NOTE: will not work with arrays, there are no arrays to set/reset
  2506. * @throws phpmailerException
  2507. * @return bool
  2508. * @todo Should this not be using __set() magic function?
  2509. */
  2510. public function set($name, $value = '') {
  2511. try {
  2512. if (isset($this->$name) ) {
  2513. $this->$name = $value;
  2514. } else {
  2515. throw new phpmailerException($this->Lang('variable_set') . $name, self::STOP_CRITICAL);
  2516. }
  2517. } catch (Exception $e) {
  2518. $this->SetError($e->getMessage());
  2519. if ($e->getCode() == self::STOP_CRITICAL) {
  2520. return false;
  2521. }
  2522. }
  2523. return true;
  2524. }
  2525. /**
  2526. * Strips newlines to prevent header injection.
  2527. * @access public
  2528. * @param string $str
  2529. * @return string
  2530. */
  2531. public function SecureHeader($str) {
  2532. return trim(str_replace(array("\r", "\n"), '', $str));
  2533. }
  2534. /**
  2535. * Normalize UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format
  2536. * Defaults to CRLF (for message bodies) and preserves consecutive breaks
  2537. * @param string $text
  2538. * @param string $breaktype What kind of line break to use, defaults to CRLF
  2539. * @return string
  2540. * @access public
  2541. * @static
  2542. */
  2543. public static function NormalizeBreaks($text, $breaktype = "\r\n") {
  2544. return preg_replace('/(\r\n|\r|\n)/ms', $breaktype, $text);
  2545. }
  2546. /**
  2547. * Set the private key file and password to sign the message.
  2548. *
  2549. * @access public
  2550. * @param string $cert_filename
  2551. * @param string $key_filename
  2552. * @param string $key_pass Password for private key
  2553. */
  2554. public function Sign($cert_filename, $key_filename, $key_pass) {
  2555. $this->sign_cert_file = $cert_filename;
  2556. $this->sign_key_file = $key_filename;
  2557. $this->sign_key_pass = $key_pass;
  2558. }
  2559. /**
  2560. * Set the private key file and password to sign the message.
  2561. *
  2562. * @access public
  2563. * @param string $txt
  2564. * @return string
  2565. */
  2566. public function DKIM_QP($txt) {
  2567. $line = '';
  2568. for ($i = 0; $i < strlen($txt); $i++) {
  2569. $ord = ord($txt[$i]);
  2570. if ( ((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E)) ) {
  2571. $line .= $txt[$i];
  2572. } else {
  2573. $line .= "=".sprintf("%02X", $ord);
  2574. }
  2575. }
  2576. return $line;
  2577. }
  2578. /**
  2579. * Generate DKIM signature
  2580. *
  2581. * @access public
  2582. * @param string $s Header
  2583. * @throws phpmailerException
  2584. * @return string
  2585. */
  2586. public function DKIM_Sign($s) {
  2587. if (!defined('PKCS7_TEXT')) {
  2588. if ($this->exceptions) {
  2589. throw new phpmailerException($this->Lang("signing").' OpenSSL extension missing.');
  2590. }
  2591. return '';
  2592. }
  2593. $privKeyStr = file_get_contents($this->DKIM_private);
  2594. if ($this->DKIM_passphrase != '') {
  2595. $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
  2596. } else {
  2597. $privKey = $privKeyStr;
  2598. }
  2599. if (openssl_sign($s, $signature, $privKey)) {
  2600. return base64_encode($signature);
  2601. }
  2602. return '';
  2603. }
  2604. /**
  2605. * Generate DKIM Canonicalization Header
  2606. *
  2607. * @access public
  2608. * @param string $s Header
  2609. * @return string
  2610. */
  2611. public function DKIM_HeaderC($s) {
  2612. $s = preg_replace("/\r\n\s+/", " ", $s);
  2613. $lines = explode("\r\n", $s);
  2614. foreach ($lines as $key => $line) {
  2615. list($heading, $value) = explode(":", $line, 2);
  2616. $heading = strtolower($heading);
  2617. $value = preg_replace("/\s+/", " ", $value) ; // Compress useless spaces
  2618. $lines[$key] = $heading.":".trim($value) ; // Don't forget to remove WSP around the value
  2619. }
  2620. $s = implode("\r\n", $lines);
  2621. return $s;
  2622. }
  2623. /**
  2624. * Generate DKIM Canonicalization Body
  2625. *
  2626. * @access public
  2627. * @param string $body Message Body
  2628. * @return string
  2629. */
  2630. public function DKIM_BodyC($body) {
  2631. if ($body == '') return "\r\n";
  2632. // stabilize line endings
  2633. $body = str_replace("\r\n", "\n", $body);
  2634. $body = str_replace("\n", "\r\n", $body);
  2635. // END stabilize line endings
  2636. while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") {
  2637. $body = substr($body, 0, strlen($body) - 2);
  2638. }
  2639. return $body;
  2640. }
  2641. /**
  2642. * Create the DKIM header, body, as new header
  2643. *
  2644. * @access public
  2645. * @param string $headers_line Header lines
  2646. * @param string $subject Subject
  2647. * @param string $body Body
  2648. * @return string
  2649. */
  2650. public function DKIM_Add($headers_line, $subject, $body) {
  2651. $DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms
  2652. $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
  2653. $DKIMquery = 'dns/txt'; // Query method
  2654. $DKIMtime = time() ; // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
  2655. $subject_header = "Subject: $subject";
  2656. $headers = explode($this->LE, $headers_line);
  2657. $from_header = '';
  2658. $to_header = '';
  2659. $current = '';
  2660. foreach($headers as $header) {
  2661. if (strpos($header, 'From:') === 0) {
  2662. $from_header = $header;
  2663. $current = 'from_header';
  2664. } elseif (strpos($header, 'To:') === 0) {
  2665. $to_header = $header;
  2666. $current = 'to_header';
  2667. } else {
  2668. if($current && strpos($header, ' =?') === 0){
  2669. $current .= $header;
  2670. } else {
  2671. $current = '';
  2672. }
  2673. }
  2674. }
  2675. $from = str_replace('|', '=7C', $this->DKIM_QP($from_header));
  2676. $to = str_replace('|', '=7C', $this->DKIM_QP($to_header));
  2677. $subject = str_replace('|', '=7C', $this->DKIM_QP($subject_header)) ; // Copied header fields (dkim-quoted-printable
  2678. $body = $this->DKIM_BodyC($body);
  2679. $DKIMlen = strlen($body) ; // Length of body
  2680. $DKIMb64 = base64_encode(pack("H*", sha1($body))) ; // Base64 of packed binary SHA-1 hash of body
  2681. $ident = ($this->DKIM_identity == '')? '' : " i=" . $this->DKIM_identity . ";";
  2682. $dkimhdrs = "DKIM-Signature: v=1; a=" . $DKIMsignatureType . "; q=" . $DKIMquery . "; l=" . $DKIMlen . "; s=" . $this->DKIM_selector . ";\r\n".
  2683. "\tt=" . $DKIMtime . "; c=" . $DKIMcanonicalization . ";\r\n".
  2684. "\th=From:To:Subject;\r\n".
  2685. "\td=" . $this->DKIM_domain . ";" . $ident . "\r\n".
  2686. "\tz=$from\r\n".
  2687. "\t|$to\r\n".
  2688. "\t|$subject;\r\n".
  2689. "\tbh=" . $DKIMb64 . ";\r\n".
  2690. "\tb=";
  2691. $toSign = $this->DKIM_HeaderC($from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs);
  2692. $signed = $this->DKIM_Sign($toSign);
  2693. return $dkimhdrs.$signed."\r\n";
  2694. }
  2695. /**
  2696. * Perform callback
  2697. * @param boolean $isSent
  2698. * @param string $to
  2699. * @param string $cc
  2700. * @param string $bcc
  2701. * @param string $subject
  2702. * @param string $body
  2703. * @param string $from
  2704. */
  2705. protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from = null) {
  2706. if (!empty($this->action_function) && is_callable($this->action_function)) {
  2707. $params = array($isSent, $to, $cc, $bcc, $subject, $body, $from);
  2708. call_user_func_array($this->action_function, $params);
  2709. }
  2710. }
  2711. }
  2712. /**
  2713. * Exception handler for PHPMailer
  2714. * @package PHPMailer
  2715. */
  2716. class phpmailerException extends \Exception {
  2717. /**
  2718. * Prettify error message output
  2719. * @return string
  2720. */
  2721. public function errorMessage() {
  2722. $errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n";
  2723. return $errorMsg;
  2724. }
  2725. }