class.phpmailer.php 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536
  1. <?php
  2. /*~ class.phpmailer.php
  3. .---------------------------------------------------------------------------.
  4. | Software: PHPMailer - PHP email class |
  5. | Version: 5.1 |
  6. | Contact: via sourceforge.net support pages (also www.worxware.com) |
  7. | Info: http://phpmailer.sourceforge.net |
  8. | Support: http://sourceforge.net/projects/phpmailer/ |
  9. | ------------------------------------------------------------------------- |
  10. | Admin: Andy Prevost (project admininistrator) |
  11. | Authors: Andy Prevost (codeworxtech) codeworxtech@users.sourceforge.net |
  12. | : Marcus Bointon (coolbru) coolbru@users.sourceforge.net |
  13. | Founder: Brent R. Matzelle (original founder) |
  14. | Copyright (c) 2004-2009, Andy Prevost. All Rights Reserved. |
  15. | Copyright (c) 2001-2003, Brent R. Matzelle |
  16. | ------------------------------------------------------------------------- |
  17. | License: Distributed under the Lesser General Public License (LGPL) |
  18. | http://www.gnu.org/copyleft/lesser.html |
  19. | This program is distributed in the hope that it will be useful - WITHOUT |
  20. | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
  21. | FITNESS FOR A PARTICULAR PURPOSE. |
  22. | ------------------------------------------------------------------------- |
  23. | We offer a number of paid services (www.worxware.com): |
  24. | - Web Hosting on highly optimized fast and secure servers |
  25. | - Technology Consulting |
  26. | - Oursourcing (highly qualified programmers and graphic designers) |
  27. '---------------------------------------------------------------------------'
  28. */
  29. /**
  30. * PHPMailer - PHP email transport class
  31. * NOTE: Requires PHP version 5 or later.
  32. *
  33. * @package PHPMailer
  34. *
  35. * @author Andy Prevost
  36. * @author Marcus Bointon
  37. * @copyright 2004 - 2009 Andy Prevost
  38. *
  39. * @version $Id: class.phpmailer.php 447 2009-05-25 01:36:38Z codeworxtech $
  40. *
  41. * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
  42. */
  43. if (version_compare(PHP_VERSION, '5.0.0', '<')) {
  44. exit("Sorry, this version of PHPMailer will only run on PHP version 5 or greater!\n");
  45. }
  46. class PHPMailer
  47. {
  48. /////////////////////////////////////////////////
  49. // CONSTANTS
  50. /////////////////////////////////////////////////
  51. const STOP_MESSAGE = 0; // message only, continue processing
  52. const STOP_CONTINUE = 1; // message?, likely ok to continue processing
  53. const STOP_CRITICAL = 2; // message, plus full stop, critical error reached
  54. /////////////////////////////////////////////////
  55. // PROPERTIES, PUBLIC
  56. /////////////////////////////////////////////////
  57. /**
  58. * Email priority (1 = High, 3 = Normal, 5 = low).
  59. *
  60. * @var int
  61. */
  62. public $Priority = 3;
  63. /**
  64. * Sets the CharSet of the message.
  65. *
  66. * @var string
  67. */
  68. public $CharSet = 'iso-8859-1';
  69. /**
  70. * Sets the Content-type of the message.
  71. *
  72. * @var string
  73. */
  74. public $ContentType = 'text/plain';
  75. /**
  76. * Sets the Encoding of the message. Options for this are
  77. * "8bit", "7bit", "binary", "base64", and "quoted-printable".
  78. *
  79. * @var string
  80. */
  81. public $Encoding = '8bit';
  82. /**
  83. * Holds the most recent mailer error message.
  84. *
  85. * @var string
  86. */
  87. public $ErrorInfo = '';
  88. /**
  89. * Sets the From email address for the message.
  90. *
  91. * @var string
  92. */
  93. public $From = 'root@localhost';
  94. /**
  95. * Sets the From name of the message.
  96. *
  97. * @var string
  98. */
  99. public $FromName = 'Root User';
  100. /**
  101. * Sets the Sender email (Return-Path) of the message. If not empty,
  102. * will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
  103. *
  104. * @var string
  105. */
  106. public $Sender = '';
  107. /**
  108. * Sets the Subject of the message.
  109. *
  110. * @var string
  111. */
  112. public $Subject = '';
  113. /**
  114. * Sets the Body of the message. This can be either an HTML or text body.
  115. * If HTML then run IsHTML(true).
  116. *
  117. * @var string
  118. */
  119. public $Body = '';
  120. /**
  121. * Sets the text-only body of the message. This automatically sets the
  122. * email to multipart/alternative. This body can be read by mail
  123. * clients that do not have HTML email capability such as mutt. Clients
  124. * that can read HTML will view the normal Body.
  125. *
  126. * @var string
  127. */
  128. public $AltBody = '';
  129. /**
  130. * Sets word wrapping on the body of the message to a given number of
  131. * characters.
  132. *
  133. * @var int
  134. */
  135. public $WordWrap = 0;
  136. /**
  137. * Method to send mail: ("mail", "sendmail", or "smtp").
  138. *
  139. * @var string
  140. */
  141. public $Mailer = 'mail';
  142. /**
  143. * Sets the path of the sendmail program.
  144. *
  145. * @var string
  146. */
  147. public $Sendmail = '/usr/sbin/sendmail';
  148. /**
  149. * Path to PHPMailer plugins. Useful if the SMTP class
  150. * is in a different directory than the PHP include path.
  151. *
  152. * @var string
  153. */
  154. public $PluginDir = '';
  155. /**
  156. * Sets the email address that a reading confirmation will be sent.
  157. *
  158. * @var string
  159. */
  160. public $ConfirmReadingTo = '';
  161. /**
  162. * Sets the hostname to use in Message-Id and Received headers
  163. * and as default HELO string. If empty, the value returned
  164. * by SERVER_NAME is used or 'localhost.localdomain'.
  165. *
  166. * @var string
  167. */
  168. public $Hostname = '';
  169. /**
  170. * Sets the message ID to be used in the Message-Id header.
  171. * If empty, a unique id will be generated.
  172. *
  173. * @var string
  174. */
  175. public $MessageID = '';
  176. /////////////////////////////////////////////////
  177. // PROPERTIES FOR SMTP
  178. /////////////////////////////////////////////////
  179. /**
  180. * Sets the SMTP hosts. All hosts must be separated by a
  181. * semicolon. You can also specify a different port
  182. * for each host by using this format: [hostname:port]
  183. * (e.g. "smtp1.example.com:25;smtp2.example.com").
  184. * Hosts will be tried in order.
  185. *
  186. * @var string
  187. */
  188. public $Host = 'localhost';
  189. /**
  190. * Sets the default SMTP server port.
  191. *
  192. * @var int
  193. */
  194. public $Port = 25;
  195. /**
  196. * Sets the SMTP HELO of the message (Default is $Hostname).
  197. *
  198. * @var string
  199. */
  200. public $Helo = '';
  201. /**
  202. * Sets connection prefix.
  203. * Options are "", "ssl" or "tls".
  204. *
  205. * @var string
  206. */
  207. public $SMTPSecure = '';
  208. /**
  209. * Sets SMTP authentication. Utilizes the Username and Password variables.
  210. *
  211. * @var bool
  212. */
  213. public $SMTPAuth = false;
  214. /**
  215. * Sets SMTP username.
  216. *
  217. * @var string
  218. */
  219. public $Username = '';
  220. /**
  221. * Sets SMTP password.
  222. *
  223. * @var string
  224. */
  225. public $Password = '';
  226. /**
  227. * Sets the SMTP server timeout in seconds.
  228. * This function will not work with the win32 version.
  229. *
  230. * @var int
  231. */
  232. public $Timeout = 10;
  233. /**
  234. * Sets SMTP class debugging on or off.
  235. *
  236. * @var bool
  237. */
  238. public $SMTPDebug = false;
  239. /**
  240. * Prevents the SMTP connection from being closed after each mail
  241. * sending. If this is set to true then to close the connection
  242. * requires an explicit call to SmtpClose().
  243. *
  244. * @var bool
  245. */
  246. public $SMTPKeepAlive = false;
  247. /**
  248. * Provides the ability to have the TO field process individual
  249. * emails, instead of sending to entire TO addresses.
  250. *
  251. * @var bool
  252. */
  253. public $SingleTo = false;
  254. /**
  255. * If SingleTo is true, this provides the array to hold the email addresses.
  256. *
  257. * @var bool
  258. */
  259. public $SingleToArray = [];
  260. /**
  261. * Provides the ability to change the line ending.
  262. *
  263. * @var string
  264. */
  265. public $LE = "\n";
  266. /**
  267. * Used with DKIM DNS Resource Record.
  268. *
  269. * @var string
  270. */
  271. public $DKIM_selector = 'phpmailer';
  272. /**
  273. * Used with DKIM DNS Resource Record
  274. * optional, in format of email address 'you@yourdomain.com'.
  275. *
  276. * @var string
  277. */
  278. public $DKIM_identity = '';
  279. /**
  280. * Used with DKIM DNS Resource Record
  281. * optional, in format of email address 'you@yourdomain.com'.
  282. *
  283. * @var string
  284. */
  285. public $DKIM_domain = '';
  286. /**
  287. * Used with DKIM DNS Resource Record
  288. * optional, in format of email address 'you@yourdomain.com'.
  289. *
  290. * @var string
  291. */
  292. public $DKIM_private = '';
  293. /**
  294. * Callback Action function name
  295. * the function that handles the result of the send email action. Parameters:
  296. * bool $result result of the send action
  297. * string $to email address of the recipient
  298. * string $cc cc email addresses
  299. * string $bcc bcc email addresses
  300. * string $subject the subject
  301. * string $body the email body.
  302. *
  303. * @var string
  304. */
  305. public $action_function = ''; //'callbackAction';
  306. /**
  307. * Sets the PHPMailer Version number.
  308. *
  309. * @var string
  310. */
  311. public $Version = '5.1';
  312. protected $language = [];
  313. /////////////////////////////////////////////////
  314. // PROPERTIES, PRIVATE AND PROTECTED
  315. /////////////////////////////////////////////////
  316. private $smtp = null;
  317. private $to = [];
  318. private $cc = [];
  319. private $bcc = [];
  320. private $ReplyTo = [];
  321. private $all_recipients = [];
  322. private $attachment = [];
  323. private $CustomHeader = [];
  324. private $message_type = '';
  325. private $boundary = [];
  326. private $error_count = 0;
  327. private $sign_cert_file = "";
  328. private $sign_key_file = "";
  329. private $sign_key_pass = "";
  330. private $exceptions = false;
  331. /////////////////////////////////////////////////
  332. // METHODS, VARIABLES
  333. /////////////////////////////////////////////////
  334. /**
  335. * Constructor.
  336. *
  337. * @param bool $exceptions Should we throw external exceptions?
  338. */
  339. public function __construct($exceptions = false)
  340. {
  341. $this->exceptions = ($exceptions == true);
  342. }
  343. /**
  344. * Sets message type to HTML.
  345. *
  346. * @param bool $ishtml
  347. */
  348. public function IsHTML($ishtml = true)
  349. {
  350. if ($ishtml) {
  351. $this->ContentType = 'text/html';
  352. } else {
  353. $this->ContentType = 'text/plain';
  354. }
  355. }
  356. /**
  357. * Sets Mailer to send message using SMTP.
  358. */
  359. public function IsSMTP()
  360. {
  361. $this->Mailer = 'smtp';
  362. }
  363. /**
  364. * Sets Mailer to send message using PHP mail() function.
  365. */
  366. public function IsMail()
  367. {
  368. $this->Mailer = 'mail';
  369. }
  370. /**
  371. * Sets Mailer to send message using the $Sendmail program.
  372. */
  373. public function IsSendmail()
  374. {
  375. if (!stristr(ini_get('sendmail_path'), 'sendmail')) {
  376. $this->Sendmail = '/var/qmail/bin/sendmail';
  377. }
  378. $this->Mailer = 'sendmail';
  379. }
  380. /**
  381. * Sets Mailer to send message using the qmail MTA.
  382. */
  383. public function IsQmail()
  384. {
  385. if (stristr(ini_get('sendmail_path'), 'qmail')) {
  386. $this->Sendmail = '/var/qmail/bin/sendmail';
  387. }
  388. $this->Mailer = 'sendmail';
  389. }
  390. /////////////////////////////////////////////////
  391. // METHODS, RECIPIENTS
  392. /////////////////////////////////////////////////
  393. /**
  394. * Adds a "To" address.
  395. *
  396. * @param string $address
  397. * @param string $name
  398. *
  399. * @return bool true on success, false if address already used
  400. */
  401. public function AddAddress($address, $name = '')
  402. {
  403. return $this->AddAnAddress('to', $address, $name);
  404. }
  405. /**
  406. * Adds a "Cc" address.
  407. * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
  408. *
  409. * @param string $address
  410. * @param string $name
  411. *
  412. * @return bool true on success, false if address already used
  413. */
  414. public function AddCC($address, $name = '')
  415. {
  416. return $this->AddAnAddress('cc', $address, $name);
  417. }
  418. /**
  419. * Adds a "Bcc" address.
  420. * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
  421. *
  422. * @param string $address
  423. * @param string $name
  424. *
  425. * @return bool true on success, false if address already used
  426. */
  427. public function AddBCC($address, $name = '')
  428. {
  429. return $this->AddAnAddress('bcc', $address, $name);
  430. }
  431. /**
  432. * Adds a "Reply-to" address.
  433. *
  434. * @param string $address
  435. * @param string $name
  436. *
  437. * @return bool
  438. */
  439. public function AddReplyTo($address, $name = '')
  440. {
  441. return $this->AddAnAddress('ReplyTo', $address, $name);
  442. }
  443. /**
  444. * Set the From and FromName properties.
  445. *
  446. * @param string $address
  447. * @param string $name
  448. *
  449. * @return bool
  450. */
  451. public function SetFrom($address, $name = '', $auto = 1)
  452. {
  453. $address = trim($address);
  454. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  455. if (!self::ValidateAddress($address)) {
  456. $this->SetError($this->Lang('invalid_address').': '.$address);
  457. if ($this->exceptions) {
  458. throw new phpmailerException($this->Lang('invalid_address').': '.$address);
  459. }
  460. error_log($this->Lang('invalid_address').': '.$address);
  461. return false;
  462. }
  463. $this->From = $address;
  464. $this->FromName = $name;
  465. if ($auto) {
  466. if (empty($this->ReplyTo)) {
  467. $this->AddAnAddress('ReplyTo', $address, $name);
  468. }
  469. if (empty($this->Sender)) {
  470. $this->Sender = $address;
  471. }
  472. }
  473. return true;
  474. }
  475. /**
  476. * Check that a string looks roughly like an email address should
  477. * Static so it can be used without instantiation
  478. * Tries to use PHP built-in validator in the filter extension (from PHP 5.2), falls back to a reasonably competent regex validator
  479. * Conforms approximately to RFC2822.
  480. *
  481. * @see http://www.hexillion.com/samples/#Regex Original pattern found here
  482. *
  483. * @param string $address The email address to check
  484. *
  485. * @return bool
  486. * @static
  487. */
  488. public static function ValidateAddress($address)
  489. {
  490. if (function_exists('filter_var')) { //Introduced in PHP 5.2
  491. if (filter_var($address, FILTER_VALIDATE_EMAIL) === false) {
  492. return false;
  493. } else {
  494. return true;
  495. }
  496. } else {
  497. return preg_match('/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!\.)){0,61}[a-zA-Z0-9_-]?\.)+[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!$)){0,61}[a-zA-Z0-9_]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/', $address);
  498. }
  499. }
  500. /////////////////////////////////////////////////
  501. // METHODS, MAIL SENDING
  502. /////////////////////////////////////////////////
  503. /**
  504. * Creates message and assigns Mailer. If the message is
  505. * not sent successfully then it returns false. Use the ErrorInfo
  506. * variable to view description of the error.
  507. *
  508. * @return bool
  509. */
  510. public function Send()
  511. {
  512. try {
  513. if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
  514. throw new phpmailerException($this->Lang('provide_address'), self::STOP_CRITICAL);
  515. }
  516. // Set whether the message is multipart/alternative
  517. if (!empty($this->AltBody)) {
  518. $this->ContentType = 'multipart/alternative';
  519. }
  520. $this->error_count = 0; // reset errors
  521. $this->SetMessageType();
  522. $header = $this->CreateHeader();
  523. $body = $this->CreateBody();
  524. if (empty($this->Body)) {
  525. throw new phpmailerException($this->Lang('empty_message'), self::STOP_CRITICAL);
  526. }
  527. // digitally sign with DKIM if enabled
  528. if ($this->DKIM_domain && $this->DKIM_private) {
  529. $header_dkim = $this->DKIM_Add($header, $this->Subject, $body);
  530. $header = str_replace("\r\n", "\n", $header_dkim).$header;
  531. }
  532. // Choose the mailer and send through it
  533. switch ($this->Mailer) {
  534. case 'sendmail':
  535. return $this->SendmailSend($header, $body);
  536. case 'smtp':
  537. return $this->SmtpSend($header, $body);
  538. default:
  539. return $this->MailSend($header, $body);
  540. }
  541. } catch (phpmailerException $e) {
  542. $this->SetError($e->getMessage());
  543. if ($this->exceptions) {
  544. throw $e;
  545. }
  546. return false;
  547. }
  548. }
  549. /**
  550. * Initiates a connection to an SMTP server.
  551. * Returns false if the operation failed.
  552. *
  553. * @uses \SMTP
  554. *
  555. * @return bool
  556. */
  557. public function SmtpConnect()
  558. {
  559. if (is_null($this->smtp)) {
  560. $this->smtp = new SMTP();
  561. }
  562. $this->smtp->do_debug = $this->SMTPDebug;
  563. $hosts = explode(';', $this->Host);
  564. $index = 0;
  565. $connection = $this->smtp->Connected();
  566. // Retry while there is no connection
  567. try {
  568. while ($index < count($hosts) && !$connection) {
  569. $hostinfo = [];
  570. if (preg_match('/^(.+):([0-9]+)$/', $hosts[$index], $hostinfo)) {
  571. $host = $hostinfo[1];
  572. $port = $hostinfo[2];
  573. } else {
  574. $host = $hosts[$index];
  575. $port = $this->Port;
  576. }
  577. $tls = ($this->SMTPSecure == 'tls');
  578. $ssl = ($this->SMTPSecure == 'ssl');
  579. if ($this->smtp->Connect(($ssl ? 'ssl://' : '').$host, $port, $this->Timeout)) {
  580. $hello = ($this->Helo != '' ? $this->Helo : $this->ServerHostname());
  581. $this->smtp->Hello($hello);
  582. if ($tls) {
  583. if (!$this->smtp->StartTLS()) {
  584. throw new phpmailerException($this->Lang('tls'));
  585. }
  586. //We must resend HELO after tls negotiation
  587. $this->smtp->Hello($hello);
  588. }
  589. $connection = true;
  590. if ($this->SMTPAuth) {
  591. if (!$this->smtp->Authenticate($this->Username, $this->Password)) {
  592. throw new phpmailerException($this->Lang('authenticate'));
  593. }
  594. }
  595. }
  596. $index++;
  597. if (!$connection) {
  598. throw new phpmailerException($this->Lang('connect_host'));
  599. }
  600. }
  601. } catch (phpmailerException $e) {
  602. $this->smtp->Reset();
  603. throw $e;
  604. }
  605. return true;
  606. }
  607. /**
  608. * Closes the active SMTP session if one exists.
  609. */
  610. public function SmtpClose()
  611. {
  612. if (!is_null($this->smtp)) {
  613. if ($this->smtp->Connected()) {
  614. $this->smtp->Quit();
  615. $this->smtp->Close();
  616. }
  617. }
  618. }
  619. /**
  620. * Sets the language for all class error messages.
  621. * Returns false if it cannot load the language file. The default language is English.
  622. *
  623. * @param string $langcode ISO 639-1 2-character language code (e.g. Portuguese: "br")
  624. * @param string $lang_path Path to the language file directory
  625. */
  626. public function SetLanguage($langcode = 'en', $lang_path = 'language/')
  627. {
  628. //Define full set of translatable strings
  629. $PHPMAILER_LANG = [
  630. 'provide_address' => 'You must provide at least one recipient email address.',
  631. 'mailer_not_supported' => ' mailer is not supported.',
  632. 'execute' => 'Could not execute: ',
  633. 'instantiate' => 'Could not instantiate mail function.',
  634. 'authenticate' => 'SMTP Error: Could not authenticate.',
  635. 'from_failed' => 'The following From address failed: ',
  636. 'recipients_failed' => 'SMTP Error: The following recipients failed: ',
  637. 'data_not_accepted' => 'SMTP Error: Data not accepted.',
  638. 'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
  639. 'file_access' => 'Could not access file: ',
  640. 'file_open' => 'File Error: Could not open file: ',
  641. 'encoding' => 'Unknown encoding: ',
  642. 'signing' => 'Signing Error: ',
  643. 'smtp_error' => 'SMTP server error: ',
  644. 'empty_message' => 'Message body empty',
  645. 'invalid_address' => 'Invalid address',
  646. 'variable_set' => 'Cannot set or reset variable: ',
  647. ];
  648. //Overwrite language-specific strings. This way we'll never have missing translations - no more "language string failed to load"!
  649. $l = true;
  650. if ($langcode != 'en') { //There is no English translation file
  651. $l = @include $lang_path.'phpmailer.lang-'.$langcode.'.php';
  652. }
  653. $this->language = $PHPMAILER_LANG;
  654. return $l == true; //Returns false if language not found
  655. }
  656. /**
  657. * Return the current array of language strings.
  658. *
  659. * @return array
  660. */
  661. public function GetTranslations()
  662. {
  663. return $this->language;
  664. }
  665. /////////////////////////////////////////////////
  666. // METHODS, MESSAGE CREATION
  667. /////////////////////////////////////////////////
  668. /**
  669. * Creates recipient headers.
  670. *
  671. * @return string
  672. */
  673. public function AddrAppend($type, $addr)
  674. {
  675. $addr_str = $type.': ';
  676. $addresses = [];
  677. foreach ($addr as $a) {
  678. $addresses[] = $this->AddrFormat($a);
  679. }
  680. $addr_str .= implode(', ', $addresses);
  681. $addr_str .= $this->LE;
  682. return $addr_str;
  683. }
  684. /**
  685. * Formats an address correctly.
  686. *
  687. * @return string
  688. */
  689. public function AddrFormat($addr)
  690. {
  691. if (empty($addr[1])) {
  692. return $this->SecureHeader($addr[0]);
  693. } else {
  694. return $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase')." <".$this->SecureHeader($addr[0]).">";
  695. }
  696. }
  697. /**
  698. * Wraps message for use with mailers that do not
  699. * automatically perform wrapping and for quoted-printable.
  700. * Original written by philippe.
  701. *
  702. * @param string $message The message to wrap
  703. * @param int $length The line length to wrap to
  704. * @param bool $qp_mode Whether to run in Quoted-Printable mode
  705. *
  706. * @return string
  707. */
  708. public function WrapText($message, $length, $qp_mode = false)
  709. {
  710. $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE;
  711. // If utf-8 encoding is used, we will need to make sure we don't
  712. // split multibyte characters when we wrap
  713. $is_utf8 = (strtolower($this->CharSet) == "utf-8");
  714. $message = $this->FixEOL($message);
  715. if (substr($message, -1) == $this->LE) {
  716. $message = substr($message, 0, -1);
  717. }
  718. $line = explode($this->LE, $message);
  719. $message = '';
  720. for ($i = 0; $i < count($line); $i++) {
  721. $line_part = explode(' ', $line[$i]);
  722. $buf = '';
  723. for ($e = 0; $e < count($line_part); $e++) {
  724. $word = $line_part[$e];
  725. if ($qp_mode and (strlen($word) > $length)) {
  726. $space_left = $length - strlen($buf) - 1;
  727. if ($e != 0) {
  728. if ($space_left > 20) {
  729. $len = $space_left;
  730. if ($is_utf8) {
  731. $len = $this->UTF8CharBoundary($word, $len);
  732. } elseif (substr($word, $len - 1, 1) == "=") {
  733. $len--;
  734. } elseif (substr($word, $len - 2, 1) == "=") {
  735. $len -= 2;
  736. }
  737. $part = substr($word, 0, $len);
  738. $word = substr($word, $len);
  739. $buf .= ' '.$part;
  740. $message .= $buf.sprintf("=%s", $this->LE);
  741. } else {
  742. $message .= $buf.$soft_break;
  743. }
  744. $buf = '';
  745. }
  746. while (strlen($word) > 0) {
  747. $len = $length;
  748. if ($is_utf8) {
  749. $len = $this->UTF8CharBoundary($word, $len);
  750. } elseif (substr($word, $len - 1, 1) == "=") {
  751. $len--;
  752. } elseif (substr($word, $len - 2, 1) == "=") {
  753. $len -= 2;
  754. }
  755. $part = substr($word, 0, $len);
  756. $word = substr($word, $len);
  757. if (strlen($word) > 0) {
  758. $message .= $part.sprintf("=%s", $this->LE);
  759. } else {
  760. $buf = $part;
  761. }
  762. }
  763. } else {
  764. $buf_o = $buf;
  765. $buf .= ($e == 0) ? $word : (' '.$word);
  766. if (strlen($buf) > $length and $buf_o != '') {
  767. $message .= $buf_o.$soft_break;
  768. $buf = $word;
  769. }
  770. }
  771. }
  772. $message .= $buf.$this->LE;
  773. }
  774. return $message;
  775. }
  776. /**
  777. * Finds last character boundary prior to maxLength in a utf-8
  778. * quoted (printable) encoded string.
  779. * Original written by Colin Brown.
  780. *
  781. * @param string $encodedText utf-8 QP text
  782. * @param int $maxLength find last character boundary prior to this length
  783. *
  784. * @return int
  785. */
  786. public function UTF8CharBoundary($encodedText, $maxLength)
  787. {
  788. $foundSplitPos = false;
  789. $lookBack = 3;
  790. while (!$foundSplitPos) {
  791. $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
  792. $encodedCharPos = strpos($lastChunk, "=");
  793. if ($encodedCharPos !== false) {
  794. // Found start of encoded character byte within $lookBack block.
  795. // Check the encoded byte value (the 2 chars after the '=')
  796. $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
  797. $dec = hexdec($hex);
  798. if ($dec < 128) { // Single byte character.
  799. // If the encoded char was found at pos 0, it will fit
  800. // otherwise reduce maxLength to start of the encoded char
  801. $maxLength = ($encodedCharPos == 0) ? $maxLength :
  802. $maxLength - ($lookBack - $encodedCharPos);
  803. $foundSplitPos = true;
  804. } elseif ($dec >= 192) { // First byte of a multi byte character
  805. // Reduce maxLength to split at start of character
  806. $maxLength = $maxLength - ($lookBack - $encodedCharPos);
  807. $foundSplitPos = true;
  808. } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back
  809. $lookBack += 3;
  810. }
  811. } else {
  812. // No encoded character found
  813. $foundSplitPos = true;
  814. }
  815. }
  816. return $maxLength;
  817. }
  818. /**
  819. * Set the body wrapping.
  820. */
  821. public function SetWordWrap()
  822. {
  823. if ($this->WordWrap < 1) {
  824. return;
  825. }
  826. switch ($this->message_type) {
  827. case 'alt':
  828. case 'alt_attachments':
  829. $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap);
  830. break;
  831. default:
  832. $this->Body = $this->WrapText($this->Body, $this->WordWrap);
  833. break;
  834. }
  835. }
  836. /**
  837. * Assembles message header.
  838. *
  839. * @return string The assembled header
  840. */
  841. public function CreateHeader()
  842. {
  843. $result = '';
  844. // Set the boundaries
  845. $uniq_id = md5(uniqid(time()));
  846. $this->boundary[1] = 'b1_'.$uniq_id;
  847. $this->boundary[2] = 'b2_'.$uniq_id;
  848. $result .= $this->HeaderLine('Date', self::RFCDate());
  849. if ($this->Sender == '') {
  850. $result .= $this->HeaderLine('Return-Path', trim($this->From));
  851. } else {
  852. $result .= $this->HeaderLine('Return-Path', trim($this->Sender));
  853. }
  854. // To be created automatically by mail()
  855. if ($this->Mailer != 'mail') {
  856. if ($this->SingleTo === true) {
  857. foreach ($this->to as $t) {
  858. $this->SingleToArray[] = $this->AddrFormat($t);
  859. }
  860. } else {
  861. if (count($this->to) > 0) {
  862. $result .= $this->AddrAppend('To', $this->to);
  863. } elseif (count($this->cc) == 0) {
  864. $result .= $this->HeaderLine('To', 'undisclosed-recipients:;');
  865. }
  866. }
  867. }
  868. $from = [];
  869. $from[0][0] = trim($this->From);
  870. $from[0][1] = $this->FromName;
  871. $result .= $this->AddrAppend('From', $from);
  872. // sendmail and mail() extract Cc from the header before sending
  873. if (count($this->cc) > 0) {
  874. $result .= $this->AddrAppend('Cc', $this->cc);
  875. }
  876. // sendmail and mail() extract Bcc from the header before sending
  877. if ((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) {
  878. $result .= $this->AddrAppend('Bcc', $this->bcc);
  879. }
  880. if (count($this->ReplyTo) > 0) {
  881. $result .= $this->AddrAppend('Reply-to', $this->ReplyTo);
  882. }
  883. // mail() sets the subject itself
  884. if ($this->Mailer != 'mail') {
  885. $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject)));
  886. }
  887. if ($this->MessageID != '') {
  888. $result .= $this->HeaderLine('Message-ID', $this->MessageID);
  889. } else {
  890. $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);
  891. }
  892. $result .= $this->HeaderLine('X-Priority', $this->Priority);
  893. $result .= $this->HeaderLine('X-Mailer', 'PHPMailer '.$this->Version.' (phpmailer.sourceforge.net)');
  894. if ($this->ConfirmReadingTo != '') {
  895. $result .= $this->HeaderLine('Disposition-Notification-To', '<'.trim($this->ConfirmReadingTo).'>');
  896. }
  897. // Add custom headers
  898. for ($index = 0; $index < count($this->CustomHeader); $index++) {
  899. $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1])));
  900. }
  901. if (!$this->sign_key_file) {
  902. $result .= $this->HeaderLine('MIME-Version', '1.0');
  903. $result .= $this->GetMailMIME();
  904. }
  905. return $result;
  906. }
  907. /**
  908. * Returns the message MIME.
  909. *
  910. * @return string
  911. */
  912. public function GetMailMIME()
  913. {
  914. $result = '';
  915. switch ($this->message_type) {
  916. case 'plain':
  917. $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding);
  918. $result .= sprintf("Content-Type: %s; charset=\"%s\"", $this->ContentType, $this->CharSet);
  919. break;
  920. case 'attachments':
  921. case 'alt_attachments':
  922. if ($this->InlineImageExists()) {
  923. $result .= sprintf("Content-Type: %s;%s\ttype=\"text/html\";%s\tboundary=\"%s\"%s", 'multipart/related', $this->LE, $this->LE, $this->boundary[1], $this->LE);
  924. } else {
  925. $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;');
  926. $result .= $this->TextLine("\tboundary=\"".$this->boundary[1].'"');
  927. }
  928. break;
  929. case 'alt':
  930. $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
  931. $result .= $this->TextLine("\tboundary=\"".$this->boundary[1].'"');
  932. break;
  933. }
  934. if ($this->Mailer != 'mail') {
  935. $result .= $this->LE.$this->LE;
  936. }
  937. return $result;
  938. }
  939. /**
  940. * Assembles the message body. Returns an empty string on failure.
  941. *
  942. * @return string The assembled message body
  943. */
  944. public function CreateBody()
  945. {
  946. $body = '';
  947. if ($this->sign_key_file) {
  948. $body .= $this->GetMailMIME();
  949. }
  950. $this->SetWordWrap();
  951. switch ($this->message_type) {
  952. case 'alt':
  953. $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
  954. $body .= $this->EncodeString($this->AltBody, $this->Encoding);
  955. $body .= $this->LE.$this->LE;
  956. $body .= $this->GetBoundary($this->boundary[1], '', 'text/html', '');
  957. $body .= $this->EncodeString($this->Body, $this->Encoding);
  958. $body .= $this->LE.$this->LE;
  959. $body .= $this->EndBoundary($this->boundary[1]);
  960. break;
  961. case 'plain':
  962. $body .= $this->EncodeString($this->Body, $this->Encoding);
  963. break;
  964. case 'attachments':
  965. $body .= $this->GetBoundary($this->boundary[1], '', '', '');
  966. $body .= $this->EncodeString($this->Body, $this->Encoding);
  967. $body .= $this->LE;
  968. $body .= $this->AttachAll();
  969. break;
  970. case 'alt_attachments':
  971. $body .= sprintf("--%s%s", $this->boundary[1], $this->LE);
  972. $body .= sprintf("Content-Type: %s;%s"."\tboundary=\"%s\"%s", 'multipart/alternative', $this->LE, $this->boundary[2], $this->LE.$this->LE);
  973. $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '').$this->LE; // Create text body
  974. $body .= $this->EncodeString($this->AltBody, $this->Encoding);
  975. $body .= $this->LE.$this->LE;
  976. $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '').$this->LE; // Create the HTML body
  977. $body .= $this->EncodeString($this->Body, $this->Encoding);
  978. $body .= $this->LE.$this->LE;
  979. $body .= $this->EndBoundary($this->boundary[2]);
  980. $body .= $this->AttachAll();
  981. break;
  982. }
  983. if ($this->IsError()) {
  984. $body = '';
  985. } elseif ($this->sign_key_file) {
  986. try {
  987. $file = tempnam('', 'mail');
  988. file_put_contents($file, $body); //TODO check this worked
  989. $signed = tempnam("", "signed");
  990. if (@openssl_pkcs7_sign($file, $signed, "file://".$this->sign_cert_file, ["file://".$this->sign_key_file, $this->sign_key_pass], null)) {
  991. @unlink($file);
  992. @unlink($signed);
  993. $body = file_get_contents($signed);
  994. } else {
  995. @unlink($file);
  996. @unlink($signed);
  997. throw new phpmailerException($this->Lang("signing").openssl_error_string());
  998. }
  999. } catch (phpmailerException $e) {
  1000. $body = '';
  1001. if ($this->exceptions) {
  1002. throw $e;
  1003. }
  1004. }
  1005. }
  1006. return $body;
  1007. }
  1008. /**
  1009. * Returns a formatted header line.
  1010. *
  1011. * @return string
  1012. */
  1013. public function HeaderLine($name, $value)
  1014. {
  1015. return $name.': '.$value.$this->LE;
  1016. }
  1017. /**
  1018. * Returns a formatted mail line.
  1019. *
  1020. * @return string
  1021. */
  1022. public function TextLine($value)
  1023. {
  1024. return $value.$this->LE;
  1025. }
  1026. /////////////////////////////////////////////////
  1027. // CLASS METHODS, ATTACHMENTS
  1028. /////////////////////////////////////////////////
  1029. /**
  1030. * Adds an attachment from a path on the filesystem.
  1031. * Returns false if the file could not be found
  1032. * or accessed.
  1033. *
  1034. * @param string $path path to the attachment
  1035. * @param string $name overrides the attachment name
  1036. * @param string $encoding file encoding (see $Encoding)
  1037. * @param string $type file extension (MIME) type
  1038. *
  1039. * @return bool
  1040. */
  1041. public function AddAttachment($path, $name = '', $encoding = 'base64', $type = 'application/octet-stream')
  1042. {
  1043. try {
  1044. if (!@is_file($path)) {
  1045. throw new phpmailerException($this->Lang('file_access').$path, self::STOP_CONTINUE);
  1046. }
  1047. $filename = basename($path);
  1048. if ($name == '') {
  1049. $name = $filename;
  1050. }
  1051. $this->attachment[] = [
  1052. 0 => $path,
  1053. 1 => $filename,
  1054. 2 => $name,
  1055. 3 => $encoding,
  1056. 4 => $type,
  1057. 5 => false, // isStringAttachment
  1058. 6 => 'attachment',
  1059. 7 => 0,
  1060. ];
  1061. } catch (phpmailerException $e) {
  1062. $this->SetError($e->getMessage());
  1063. if ($this->exceptions) {
  1064. throw $e;
  1065. }
  1066. error_log($e->getMessage()."\n");
  1067. if ($e->getCode() == self::STOP_CRITICAL) {
  1068. return false;
  1069. }
  1070. }
  1071. return true;
  1072. }
  1073. /**
  1074. * Return the current array of attachments.
  1075. *
  1076. * @return array
  1077. */
  1078. public function GetAttachments()
  1079. {
  1080. return $this->attachment;
  1081. }
  1082. /**
  1083. * Encodes string to requested format.
  1084. * Returns an empty string on failure.
  1085. *
  1086. * @param string $str The text to encode
  1087. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  1088. *
  1089. * @return string
  1090. */
  1091. public function EncodeString($str, $encoding = 'base64')
  1092. {
  1093. $encoded = '';
  1094. switch (strtolower($encoding)) {
  1095. case 'base64':
  1096. $encoded = chunk_split(base64_encode($str), 76, $this->LE);
  1097. break;
  1098. case '7bit':
  1099. case '8bit':
  1100. $encoded = $this->FixEOL($str);
  1101. //Make sure it ends with a line break
  1102. if (substr($encoded, -(strlen($this->LE))) != $this->LE) {
  1103. $encoded .= $this->LE;
  1104. }
  1105. break;
  1106. case 'binary':
  1107. $encoded = $str;
  1108. break;
  1109. case 'quoted-printable':
  1110. $encoded = $this->EncodeQP($str);
  1111. break;
  1112. default:
  1113. $this->SetError($this->Lang('encoding').$encoding);
  1114. break;
  1115. }
  1116. return $encoded;
  1117. }
  1118. /**
  1119. * Encode a header string to best (shortest) of Q, B, quoted or none.
  1120. *
  1121. * @return string
  1122. */
  1123. public function EncodeHeader($str, $position = 'text')
  1124. {
  1125. $x = 0;
  1126. switch (strtolower($position)) {
  1127. case 'phrase':
  1128. if (!preg_match('/[\200-\377]/', $str)) {
  1129. // Can't use addslashes as we don't know what value has magic_quotes_sybase
  1130. $encoded = addcslashes($str, "\0..\37\177\\\"");
  1131. if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
  1132. return $encoded;
  1133. } else {
  1134. return "\"$encoded\"";
  1135. }
  1136. }
  1137. $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
  1138. break;
  1139. case 'comment':
  1140. $x = preg_match_all('/[()"]/', $str, $matches);
  1141. // Fall-through
  1142. // no break
  1143. case 'text':
  1144. default:
  1145. $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
  1146. break;
  1147. }
  1148. if ($x == 0) {
  1149. return $str;
  1150. }
  1151. $maxlen = 75 - 7 - strlen($this->CharSet);
  1152. // Try to select the encoding which should produce the shortest output
  1153. if (strlen($str) / 3 < $x) {
  1154. $encoding = 'B';
  1155. // Modified by Ivan Tcholakov, 24-JAN-2010.
  1156. //if (function_exists('mb_strlen') && $this->HasMultiBytes($str))
  1157. if ($this->HasMultiBytes($str)) {
  1158. //
  1159. // Use a custom function which correctly encodes and wraps long
  1160. // multibyte strings without breaking lines within a character
  1161. $encoded = $this->Base64EncodeWrapMB($str);
  1162. } else {
  1163. $encoded = base64_encode($str);
  1164. $maxlen -= $maxlen % 4;
  1165. $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
  1166. }
  1167. } else {
  1168. if ($this->HasMultiBytes($str)) {
  1169. // Although the string might be long, processing UTF-8 long strings with the Q encoding
  1170. // generates issues which can be avoided encoding in Base64
  1171. $encoding = 'B';
  1172. $encoded = $this->Base64EncodeWrapMB($str);
  1173. } else {
  1174. $encoding = 'Q';
  1175. $encoded = $this->EncodeQ($str, $position);
  1176. $encoded = $this->WrapText($encoded, $maxlen, true);
  1177. $encoded = str_replace('='.$this->LE, "\n", trim($encoded));
  1178. }
  1179. }
  1180. $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded);
  1181. $encoded = trim(str_replace("\n", $this->LE, $encoded));
  1182. return $encoded;
  1183. }
  1184. /**
  1185. * Checks if a string contains multibyte characters.
  1186. *
  1187. * @param string $str multi-byte text to wrap encode
  1188. *
  1189. * @return bool
  1190. */
  1191. public function HasMultiBytes($str)
  1192. {
  1193. if (function_exists('mb_strlen')) {
  1194. return strlen($str) > mb_strlen($str, $this->CharSet);
  1195. } else { // Assume no multibytes (we can't handle without mbstring functions anyway)
  1196. return false;
  1197. }
  1198. }
  1199. /**
  1200. * Correctly encodes and wraps long multibyte strings for mail headers
  1201. * without breaking lines within a character.
  1202. * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php.
  1203. *
  1204. * @param string $str multi-byte text to wrap encode
  1205. *
  1206. * @return string
  1207. */
  1208. public function Base64EncodeWrapMB($str)
  1209. {
  1210. $start = "=?".$this->CharSet."?B?";
  1211. $end = "?=";
  1212. $encoded = "";
  1213. // Modified by Ivan Tcholakov, 24-JAN-2010.
  1214. //$mb_length = mb_strlen($str, $this->CharSet);
  1215. $mb_length = api_strlen($str, $this->CharSet);
  1216. //
  1217. // Each line must have length <= 75, including $start and $end
  1218. $length = 75 - strlen($start) - strlen($end);
  1219. // Average multi-byte ratio
  1220. $ratio = $mb_length / strlen($str);
  1221. // Base64 has a 4:3 ratio
  1222. $offset = $avgLength = floor($length * $ratio * .75);
  1223. for ($i = 0; $i < $mb_length; $i += $offset) {
  1224. $lookBack = 0;
  1225. do {
  1226. $offset = $avgLength - $lookBack;
  1227. // Modified by Ivan Tcholakov, 24-JAN-2010.
  1228. //$chunk = mb_substr($str, $i, $offset, $this->CharSet);
  1229. $chunk = api_substr($str, $i, $offset, $this->CharSet);
  1230. $chunk = base64_encode($chunk);
  1231. $lookBack++;
  1232. } while (strlen($chunk) > $length);
  1233. $encoded .= $chunk.$this->LE;
  1234. }
  1235. // Chomp the last linefeed
  1236. $encoded = substr($encoded, 0, -strlen($this->LE));
  1237. return $encoded;
  1238. }
  1239. /**
  1240. * Encode string to quoted-printable.
  1241. * Only uses standard PHP, slow, but will always work.
  1242. *
  1243. * @param string $string the text to encode
  1244. * @param int $line_max Number of chars allowed on a line before wrapping
  1245. *
  1246. * @return string
  1247. */
  1248. public function EncodeQPphp($input = '', $line_max = 76, $space_conv = false)
  1249. {
  1250. $hex = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];
  1251. $lines = preg_split('/(?:\r\n|\r|\n)/', $input);
  1252. $eol = "\r\n";
  1253. $escape = '=';
  1254. $output = '';
  1255. while (list(, $line) = each($lines)) {
  1256. $linlen = strlen($line);
  1257. $newline = '';
  1258. for ($i = 0; $i < $linlen; $i++) {
  1259. $c = substr($line, $i, 1);
  1260. $dec = ord($c);
  1261. if (($i == 0) && ($dec == 46)) { // convert first point in the line into =2E
  1262. $c = '=2E';
  1263. }
  1264. if ($dec == 32) {
  1265. if ($i == ($linlen - 1)) { // convert space at eol only
  1266. $c = '=20';
  1267. } elseif ($space_conv) {
  1268. $c = '=20';
  1269. }
  1270. } elseif (($dec == 61) || ($dec < 32) || ($dec > 126)) { // always encode "\t", which is *not* required
  1271. $h2 = floor($dec / 16);
  1272. $h1 = floor($dec % 16);
  1273. $c = $escape.$hex[$h2].$hex[$h1];
  1274. }
  1275. if ((strlen($newline) + strlen($c)) >= $line_max) { // CRLF is not counted
  1276. $output .= $newline.$escape.$eol; // soft line break; " =\r\n" is okay
  1277. $newline = '';
  1278. // check if newline first character will be point or not
  1279. if ($dec == 46) {
  1280. $c = '=2E';
  1281. }
  1282. }
  1283. $newline .= $c;
  1284. } // end of for
  1285. $output .= $newline.$eol;
  1286. } // end of while
  1287. return $output;
  1288. }
  1289. /**
  1290. * Encode string to RFC2045 (6.7) quoted-printable format
  1291. * Uses a PHP5 stream filter to do the encoding about 64x faster than the old version
  1292. * Also results in same content as you started with after decoding.
  1293. *
  1294. * @see EncodeQPphp()
  1295. *
  1296. * @param string $string the text to encode
  1297. * @param int $line_max Number of chars allowed on a line before wrapping
  1298. * @param bool $space_conv Dummy param for compatibility with existing EncodeQP function
  1299. *
  1300. * @return string
  1301. *
  1302. * @author Marcus Bointon
  1303. */
  1304. public function EncodeQP($string, $line_max = 76, $space_conv = false)
  1305. {
  1306. if (function_exists('quoted_printable_encode')) { //Use native function if it's available (>= PHP5.3)
  1307. return quoted_printable_encode($string);
  1308. }
  1309. $filters = stream_get_filters();
  1310. if (!in_array('convert.*', $filters)) { //Got convert stream filter?
  1311. return $this->EncodeQPphp($string, $line_max, $space_conv); //Fall back to old implementation
  1312. }
  1313. $fp = fopen('php://temp/', 'r+');
  1314. $string = preg_replace('/\r\n?/', $this->LE, $string); //Normalise line breaks
  1315. $params = ['line-length' => $line_max, 'line-break-chars' => $this->LE];
  1316. $s = stream_filter_append($fp, 'convert.quoted-printable-encode', STREAM_FILTER_READ, $params);
  1317. fputs($fp, $string);
  1318. rewind($fp);
  1319. $out = stream_get_contents($fp);
  1320. stream_filter_remove($s);
  1321. $out = preg_replace('/^\./m', '=2E', $out); //Encode . if it is first char on a line, workaround for bug in Exchange
  1322. fclose($fp);
  1323. return $out;
  1324. }
  1325. /**
  1326. * Encode string to q encoding.
  1327. *
  1328. * @see http://tools.ietf.org/html/rfc2047
  1329. *
  1330. * @param string $str the text to encode
  1331. * @param string $position Where the text is going to be used, see the RFC for what that means
  1332. *
  1333. * @return string
  1334. */
  1335. public function EncodeQ($str, $position = 'text')
  1336. {
  1337. // There should not be any EOL in the string
  1338. $encoded = preg_replace('/[\r\n]*/', '', $str);
  1339. switch (strtolower($position)) {
  1340. case 'phrase':
  1341. $encoded = @preg_replace("/([^A-Za-z0-9!*+\/ -])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
  1342. break;
  1343. case 'comment':
  1344. $encoded = @preg_replace("/([\(\)\"])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
  1345. // no break
  1346. case 'text':
  1347. default:
  1348. // Replace every high ascii, control =, ? and _ characters
  1349. //TODO using /e (equivalent to eval()) is probably not a good idea
  1350. $encoded = @preg_replace(
  1351. '/([\000-\011\013\014\016-\037\075\077\137\177-\377])/e',
  1352. "'='.sprintf('%02X', ord('\\1'))",
  1353. $encoded
  1354. );
  1355. break;
  1356. }
  1357. // Replace every spaces to _ (more readable than =20)
  1358. $encoded = str_replace(' ', '_', $encoded);
  1359. return $encoded;
  1360. }
  1361. /**
  1362. * Adds a string or binary attachment (non-filesystem) to the list.
  1363. * This method can be used to attach ascii or binary data,
  1364. * such as a BLOB record from a database.
  1365. *
  1366. * @param string $string string attachment data
  1367. * @param string $filename name of the attachment
  1368. * @param string $encoding file encoding (see $Encoding)
  1369. * @param string $type file extension (MIME) type
  1370. */
  1371. public function AddStringAttachment($string, $filename, $encoding = 'base64', $type = 'application/octet-stream')
  1372. {
  1373. // Append to $attachment array
  1374. $this->attachment[] = [
  1375. 0 => $string,
  1376. 1 => $filename,
  1377. 2 => basename($filename),
  1378. 3 => $encoding,
  1379. 4 => $type,
  1380. 5 => true, // isStringAttachment
  1381. 6 => 'attachment',
  1382. 7 => 0,
  1383. ];
  1384. }
  1385. /**
  1386. * Adds an embedded attachment. This can include images, sounds, and
  1387. * just about any other document. Make sure to set the $type to an
  1388. * image type. For JPEG images use "image/jpeg" and for GIF images
  1389. * use "image/gif".
  1390. *
  1391. * @param string $path path to the attachment
  1392. * @param string $cid Content ID of the attachment. Use this to identify
  1393. * the Id for accessing the image in an HTML form.
  1394. * @param string $name overrides the attachment name
  1395. * @param string $encoding file encoding (see $Encoding)
  1396. * @param string $type file extension (MIME) type
  1397. *
  1398. * @return bool
  1399. */
  1400. public function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream')
  1401. {
  1402. if (!@is_file($path)) {
  1403. $this->SetError($this->Lang('file_access').$path);
  1404. return false;
  1405. }
  1406. $filename = basename($path);
  1407. if ($name == '') {
  1408. $name = $filename;
  1409. }
  1410. // Append to $attachment array
  1411. $this->attachment[] = [
  1412. 0 => $path,
  1413. 1 => $filename,
  1414. 2 => $name,
  1415. 3 => $encoding,
  1416. 4 => $type,
  1417. 5 => false, // isStringAttachment
  1418. 6 => 'inline',
  1419. 7 => $cid,
  1420. ];
  1421. return true;
  1422. }
  1423. /**
  1424. * Returns true if an inline attachment is present.
  1425. *
  1426. * @return bool
  1427. */
  1428. public function InlineImageExists()
  1429. {
  1430. foreach ($this->attachment as $attachment) {
  1431. if ($attachment[6] == 'inline') {
  1432. return true;
  1433. }
  1434. }
  1435. return false;
  1436. }
  1437. /////////////////////////////////////////////////
  1438. // CLASS METHODS, MESSAGE RESET
  1439. /////////////////////////////////////////////////
  1440. /**
  1441. * Clears all recipients assigned in the TO array. Returns void.
  1442. */
  1443. public function ClearAddresses()
  1444. {
  1445. foreach ($this->to as $to) {
  1446. unset($this->all_recipients[strtolower($to[0])]);
  1447. }
  1448. $this->to = [];
  1449. }
  1450. /**
  1451. * Clears all recipients assigned in the CC array. Returns void.
  1452. */
  1453. public function ClearCCs()
  1454. {
  1455. foreach ($this->cc as $cc) {
  1456. unset($this->all_recipients[strtolower($cc[0])]);
  1457. }
  1458. $this->cc = [];
  1459. }
  1460. /**
  1461. * Clears all recipients assigned in the BCC array. Returns void.
  1462. */
  1463. public function ClearBCCs()
  1464. {
  1465. foreach ($this->bcc as $bcc) {
  1466. unset($this->all_recipients[strtolower($bcc[0])]);
  1467. }
  1468. $this->bcc = [];
  1469. }
  1470. /**
  1471. * Clears all recipients assigned in the ReplyTo array. Returns void.
  1472. */
  1473. public function ClearReplyTos()
  1474. {
  1475. $this->ReplyTo = [];
  1476. }
  1477. /**
  1478. * Clears all recipients assigned in the TO, CC and BCC
  1479. * array. Returns void.
  1480. */
  1481. public function ClearAllRecipients()
  1482. {
  1483. $this->to = [];
  1484. $this->cc = [];
  1485. $this->bcc = [];
  1486. $this->all_recipients = [];
  1487. }
  1488. /**
  1489. * Clears all previously set filesystem, string, and binary
  1490. * attachments. Returns void.
  1491. */
  1492. public function ClearAttachments()
  1493. {
  1494. $this->attachment = [];
  1495. }
  1496. /**
  1497. * Clears all custom headers. Returns void.
  1498. */
  1499. public function ClearCustomHeaders()
  1500. {
  1501. $this->CustomHeader = [];
  1502. }
  1503. /**
  1504. * Returns the proper RFC 822 formatted date.
  1505. *
  1506. * @return string
  1507. * @static
  1508. */
  1509. public static function RFCDate()
  1510. {
  1511. $tz = date('Z');
  1512. $tzs = ($tz < 0) ? '-' : '+';
  1513. $tz = abs($tz);
  1514. $tz = (int) ($tz / 3600) * 100 + ($tz % 3600) / 60;
  1515. $result = sprintf("%s %s%04d", date('D, j M Y H:i:s'), $tzs, $tz);
  1516. return $result;
  1517. }
  1518. /**
  1519. * Returns true if an error occurred.
  1520. *
  1521. * @return bool
  1522. */
  1523. public function IsError()
  1524. {
  1525. return $this->error_count > 0;
  1526. }
  1527. /**
  1528. * Adds a custom header.
  1529. */
  1530. public function AddCustomHeader($custom_header)
  1531. {
  1532. $this->CustomHeader[] = explode(':', $custom_header, 2);
  1533. }
  1534. /**
  1535. * Evaluates the message and returns modifications for inline images and backgrounds.
  1536. *
  1537. * @return $message
  1538. */
  1539. public function MsgHTML($message, $basedir = '')
  1540. {
  1541. preg_match_all("/(src|background)=\"(.*)\"/Ui", $message, $images);
  1542. if (isset($images[2])) {
  1543. foreach ($images[2] as $i => $url) {
  1544. // do not change urls for absolute images (thanks to corvuscorax)
  1545. if (!preg_match('#^[A-z]+://#', $url)) {
  1546. $filename = basename($url);
  1547. $directory = dirname($url);
  1548. ($directory == '.') ? $directory = '' : '';
  1549. $cid = 'cid:'.md5($filename);
  1550. $ext = pathinfo($filename, PATHINFO_EXTENSION);
  1551. $mimeType = self::_mime_types($ext);
  1552. if (strlen($basedir) > 1 && substr($basedir, -1) != '/') {
  1553. $basedir .= '/';
  1554. }
  1555. if (strlen($directory) > 1 && substr($directory, -1) != '/') {
  1556. $directory .= '/';
  1557. }
  1558. if ($this->AddEmbeddedImage($basedir.$directory.$filename, md5($filename), $filename, 'base64', $mimeType)) {
  1559. $message = preg_replace("/".$images[1][$i]."=\"".preg_quote($url, '/')."\"/Ui", $images[1][$i]."=\"".$cid."\"", $message);
  1560. }
  1561. }
  1562. }
  1563. }
  1564. $this->IsHTML(true);
  1565. $this->Body = $message;
  1566. $textMsg = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s', '', $message)));
  1567. if (!empty($textMsg) && empty($this->AltBody)) {
  1568. $this->AltBody = html_entity_decode($textMsg);
  1569. }
  1570. if (empty($this->AltBody)) {
  1571. $this->AltBody = 'To view this email message, open it in a program that understands HTML!'."\n\n";
  1572. }
  1573. }
  1574. /**
  1575. * Gets the MIME type of the embedded or inline image.
  1576. *
  1577. * @param string File extension
  1578. *
  1579. * @return string MIME type of ext
  1580. * @static
  1581. */
  1582. public static function _mime_types($ext = '')
  1583. {
  1584. $mimes = [
  1585. 'hqx' => 'application/mac-binhex40',
  1586. 'cpt' => 'application/mac-compactpro',
  1587. 'doc' => 'application/msword',
  1588. 'bin' => 'application/macbinary',
  1589. 'dms' => 'application/octet-stream',
  1590. 'lha' => 'application/octet-stream',
  1591. 'lzh' => 'application/octet-stream',
  1592. 'exe' => 'application/octet-stream',
  1593. 'class' => 'application/octet-stream',
  1594. 'psd' => 'application/octet-stream',
  1595. 'so' => 'application/octet-stream',
  1596. 'sea' => 'application/octet-stream',
  1597. 'dll' => 'application/octet-stream',
  1598. 'oda' => 'application/oda',
  1599. 'pdf' => 'application/pdf',
  1600. 'ai' => 'application/postscript',
  1601. 'eps' => 'application/postscript',
  1602. 'ps' => 'application/postscript',
  1603. 'smi' => 'application/smil',
  1604. 'smil' => 'application/smil',
  1605. 'mif' => 'application/vnd.mif',
  1606. 'xls' => 'application/vnd.ms-excel',
  1607. 'ppt' => 'application/vnd.ms-powerpoint',
  1608. 'wbxml' => 'application/vnd.wap.wbxml',
  1609. 'wmlc' => 'application/vnd.wap.wmlc',
  1610. 'dcr' => 'application/x-director',
  1611. 'dir' => 'application/x-director',
  1612. 'dxr' => 'application/x-director',
  1613. 'dvi' => 'application/x-dvi',
  1614. 'gtar' => 'application/x-gtar',
  1615. 'php' => 'application/x-httpd-php',
  1616. 'php4' => 'application/x-httpd-php',
  1617. 'php3' => 'application/x-httpd-php',
  1618. 'phtml' => 'application/x-httpd-php',
  1619. 'phps' => 'application/x-httpd-php-source',
  1620. 'js' => 'application/x-javascript',
  1621. 'swf' => 'application/x-shockwave-flash',
  1622. 'sit' => 'application/x-stuffit',
  1623. 'tar' => 'application/x-tar',
  1624. 'tgz' => 'application/x-tar',
  1625. 'xhtml' => 'application/xhtml+xml',
  1626. 'xht' => 'application/xhtml+xml',
  1627. 'zip' => 'application/zip',
  1628. 'mid' => 'audio/midi',
  1629. 'midi' => 'audio/midi',
  1630. 'mpga' => 'audio/mpeg',
  1631. 'mp2' => 'audio/mpeg',
  1632. 'mp3' => 'audio/mpeg',
  1633. 'aif' => 'audio/x-aiff',
  1634. 'aiff' => 'audio/x-aiff',
  1635. 'aifc' => 'audio/x-aiff',
  1636. 'ram' => 'audio/x-pn-realaudio',
  1637. 'rm' => 'audio/x-pn-realaudio',
  1638. 'rpm' => 'audio/x-pn-realaudio-plugin',
  1639. 'ra' => 'audio/x-realaudio',
  1640. 'rv' => 'video/vnd.rn-realvideo',
  1641. 'wav' => 'audio/x-wav',
  1642. 'bmp' => 'image/bmp',
  1643. 'gif' => 'image/gif',
  1644. 'jpeg' => 'image/jpeg',
  1645. 'jpg' => 'image/jpeg',
  1646. 'jpe' => 'image/jpeg',
  1647. 'png' => 'image/png',
  1648. 'tiff' => 'image/tiff',
  1649. 'tif' => 'image/tiff',
  1650. 'css' => 'text/css',
  1651. 'html' => 'text/html',
  1652. 'htm' => 'text/html',
  1653. 'shtml' => 'text/html',
  1654. 'txt' => 'text/plain',
  1655. 'text' => 'text/plain',
  1656. 'log' => 'text/plain',
  1657. 'rtx' => 'text/richtext',
  1658. 'rtf' => 'text/rtf',
  1659. 'xml' => 'text/xml',
  1660. 'xsl' => 'text/xml',
  1661. 'mpeg' => 'video/mpeg',
  1662. 'mpg' => 'video/mpeg',
  1663. 'mpe' => 'video/mpeg',
  1664. 'qt' => 'video/quicktime',
  1665. 'mov' => 'video/quicktime',
  1666. 'avi' => 'video/x-msvideo',
  1667. 'movie' => 'video/x-sgi-movie',
  1668. 'doc' => 'application/msword',
  1669. 'word' => 'application/msword',
  1670. 'xl' => 'application/excel',
  1671. 'eml' => 'message/rfc822',
  1672. ];
  1673. return (!isset($mimes[strtolower($ext)])) ? 'application/octet-stream' : $mimes[strtolower($ext)];
  1674. }
  1675. /**
  1676. * Set (or reset) Class Objects (variables).
  1677. *
  1678. * Usage Example:
  1679. * $page->set('X-Priority', '3');
  1680. *
  1681. * @param string $name Parameter Name
  1682. * @param mixed $value Parameter Value
  1683. * NOTE: will not work with arrays, there are no arrays to set/reset
  1684. *
  1685. * @todo Should this not be using __set() magic function?
  1686. */
  1687. public function set($name, $value = '')
  1688. {
  1689. try {
  1690. if (isset($this->$name)) {
  1691. $this->$name = $value;
  1692. } else {
  1693. throw new phpmailerException($this->Lang('variable_set').$name, self::STOP_CRITICAL);
  1694. }
  1695. } catch (Exception $e) {
  1696. $this->SetError($e->getMessage());
  1697. if ($e->getCode() == self::STOP_CRITICAL) {
  1698. return false;
  1699. }
  1700. }
  1701. return true;
  1702. }
  1703. /**
  1704. * Strips newlines to prevent header injection.
  1705. *
  1706. * @param string $str String
  1707. *
  1708. * @return string
  1709. */
  1710. public function SecureHeader($str)
  1711. {
  1712. $str = str_replace("\r", '', $str);
  1713. $str = str_replace("\n", '', $str);
  1714. return trim($str);
  1715. }
  1716. /**
  1717. * Set the private key file and password to sign the message.
  1718. *
  1719. * @param string $key_filename Parameter File Name
  1720. * @param string $key_pass Password for private key
  1721. */
  1722. public function Sign($cert_filename, $key_filename, $key_pass)
  1723. {
  1724. $this->sign_cert_file = $cert_filename;
  1725. $this->sign_key_file = $key_filename;
  1726. $this->sign_key_pass = $key_pass;
  1727. }
  1728. /**
  1729. * Set the private key file and password to sign the message.
  1730. *
  1731. * @param string $key_filename Parameter File Name
  1732. * @param string $key_pass Password for private key
  1733. */
  1734. public function DKIM_QP($txt)
  1735. {
  1736. $tmp = "";
  1737. $line = "";
  1738. for ($i = 0; $i < strlen($txt); $i++) {
  1739. $ord = ord($txt[$i]);
  1740. if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) {
  1741. $line .= $txt[$i];
  1742. } else {
  1743. $line .= "=".sprintf("%02X", $ord);
  1744. }
  1745. }
  1746. return $line;
  1747. }
  1748. /**
  1749. * Generate DKIM signature.
  1750. *
  1751. * @param string $s Header
  1752. */
  1753. public function DKIM_Sign($s)
  1754. {
  1755. $privKeyStr = file_get_contents($this->DKIM_private);
  1756. if ($this->DKIM_passphrase != '') {
  1757. $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
  1758. } else {
  1759. $privKey = $privKeyStr;
  1760. }
  1761. if (openssl_sign($s, $signature, $privKey)) {
  1762. return base64_encode($signature);
  1763. }
  1764. }
  1765. /**
  1766. * Generate DKIM Canonicalization Header.
  1767. *
  1768. * @param string $s Header
  1769. */
  1770. public function DKIM_HeaderC($s)
  1771. {
  1772. $s = preg_replace("/\r\n\s+/", " ", $s);
  1773. $lines = explode("\r\n", $s);
  1774. foreach ($lines as $key => $line) {
  1775. list($heading, $value) = explode(":", $line, 2);
  1776. $heading = strtolower($heading);
  1777. $value = preg_replace("/\s+/", " ", $value); // Compress useless spaces
  1778. $lines[$key] = $heading.":".trim($value); // Don't forget to remove WSP around the value
  1779. }
  1780. $s = implode("\r\n", $lines);
  1781. return $s;
  1782. }
  1783. /**
  1784. * Generate DKIM Canonicalization Body.
  1785. *
  1786. * @param string $body Message Body
  1787. */
  1788. public function DKIM_BodyC($body)
  1789. {
  1790. if ($body == '') {
  1791. return "\r\n";
  1792. }
  1793. // stabilize line endings
  1794. $body = str_replace("\r\n", "\n", $body);
  1795. $body = str_replace("\n", "\r\n", $body);
  1796. // END stabilize line endings
  1797. while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") {
  1798. $body = substr($body, 0, strlen($body) - 2);
  1799. }
  1800. return $body;
  1801. }
  1802. /**
  1803. * Create the DKIM header, body, as new header.
  1804. *
  1805. * @param string $headers_line Header lines
  1806. * @param string $subject Subject
  1807. * @param string $body Body
  1808. */
  1809. public function DKIM_Add($headers_line, $subject, $body)
  1810. {
  1811. $DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms
  1812. $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
  1813. $DKIMquery = 'dns/txt'; // Query method
  1814. $DKIMtime = time(); // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
  1815. $subject_header = "Subject: $subject";
  1816. $headers = explode("\r\n", $headers_line);
  1817. foreach ($headers as $header) {
  1818. if (strpos($header, 'From:') === 0) {
  1819. $from_header = $header;
  1820. } elseif (strpos($header, 'To:') === 0) {
  1821. $to_header = $header;
  1822. }
  1823. }
  1824. $from = str_replace('|', '=7C', $this->DKIM_QP($from_header));
  1825. $to = str_replace('|', '=7C', $this->DKIM_QP($to_header));
  1826. $subject = str_replace('|', '=7C', $this->DKIM_QP($subject_header)); // Copied header fields (dkim-quoted-printable
  1827. $body = $this->DKIM_BodyC($body);
  1828. $DKIMlen = strlen($body); // Length of body
  1829. $DKIMb64 = base64_encode(pack("H*", sha1($body))); // Base64 of packed binary SHA-1 hash of body
  1830. $ident = ($this->DKIM_identity == '') ? '' : " i=".$this->DKIM_identity.";";
  1831. $dkimhdrs = "DKIM-Signature: v=1; a=".$DKIMsignatureType."; q=".$DKIMquery."; l=".$DKIMlen."; s=".$this->DKIM_selector.";\r\n".
  1832. "\tt=".$DKIMtime."; c=".$DKIMcanonicalization.";\r\n".
  1833. "\th=From:To:Subject;\r\n".
  1834. "\td=".$this->DKIM_domain.";".$ident."\r\n".
  1835. "\tz=$from\r\n".
  1836. "\t|$to\r\n".
  1837. "\t|$subject;\r\n".
  1838. "\tbh=".$DKIMb64.";\r\n".
  1839. "\tb=";
  1840. $toSign = $this->DKIM_HeaderC($from_header."\r\n".$to_header."\r\n".$subject_header."\r\n".$dkimhdrs);
  1841. $signed = $this->DKIM_Sign($toSign);
  1842. return "X-PHPMAILER-DKIM: phpmailer.worxware.com\r\n".$dkimhdrs.$signed."\r\n";
  1843. }
  1844. /**
  1845. * Sends mail using the $Sendmail program.
  1846. *
  1847. * @param string $header The message headers
  1848. * @param string $body The message body
  1849. *
  1850. * @return bool
  1851. */
  1852. protected function SendmailSend($header, $body)
  1853. {
  1854. if (!(is_file($this->Sendmail) and is_executable($this->Sendmail))) {
  1855. throw new phpmailerException(
  1856. $this->lang('execute').$this->Sendmail,
  1857. self::STOP_CRITICAL
  1858. );
  1859. }
  1860. if (!empty($this->Sender) and $this->validateAddress($this->Sender)) {
  1861. if ($this->Mailer == 'qmail') {
  1862. $sendmail = sprintf(
  1863. '%s -f%s',
  1864. escapeshellcmd($this->Sendmail),
  1865. escapeshellarg($this->Sender)
  1866. );
  1867. } else {
  1868. $sendmail = sprintf(
  1869. '%s -oi -f%s -t',
  1870. escapeshellcmd($this->Sendmail),
  1871. escapeshellarg($this->Sender)
  1872. );
  1873. }
  1874. } else {
  1875. if ($this->Mailer == 'qmail') {
  1876. $sendmail = sprintf('%s', escapeshellcmd($this->Sendmail));
  1877. } else {
  1878. $sendmail = sprintf('%s -oi -t', escapeshellcmd($this->Sendmail));
  1879. }
  1880. }
  1881. if ($this->SingleTo === true) {
  1882. foreach ($this->SingleToArray as $key => $val) {
  1883. if (!@$mail = popen($sendmail, 'w')) {
  1884. throw new phpmailerException($this->Lang('execute').$this->Sendmail, self::STOP_CRITICAL);
  1885. }
  1886. fputs($mail, "To: ".$val."\n");
  1887. fputs($mail, $header);
  1888. fputs($mail, $body);
  1889. $result = pclose($mail);
  1890. // implement call back function if it exists
  1891. $isSent = ($result == 0) ? 1 : 0;
  1892. $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
  1893. if ($result != 0) {
  1894. throw new phpmailerException($this->Lang('execute').$this->Sendmail, self::STOP_CRITICAL);
  1895. }
  1896. }
  1897. } else {
  1898. if (!@$mail = popen($sendmail, 'w')) {
  1899. throw new phpmailerException($this->Lang('execute').$this->Sendmail, self::STOP_CRITICAL);
  1900. }
  1901. fputs($mail, $header);
  1902. fputs($mail, $body);
  1903. $result = pclose($mail);
  1904. // implement call back function if it exists
  1905. $isSent = ($result == 0) ? 1 : 0;
  1906. $this->doCallback($isSent, $this->to, $this->cc, $this->bcc, $this->Subject, $body);
  1907. if ($result != 0) {
  1908. throw new phpmailerException($this->Lang('execute').$this->Sendmail, self::STOP_CRITICAL);
  1909. }
  1910. }
  1911. return true;
  1912. }
  1913. /**
  1914. * Sends mail using the PHP mail() function.
  1915. *
  1916. * @param string $header The message headers
  1917. * @param string $body The message body
  1918. *
  1919. * @return bool
  1920. */
  1921. protected function MailSend($header, $body)
  1922. {
  1923. $toArr = [];
  1924. foreach ($this->to as $t) {
  1925. $toArr[] = $this->AddrFormat($t);
  1926. }
  1927. $to = implode(', ', $toArr);
  1928. $params = sprintf("-oi -f %s", $this->Sender);
  1929. if (!empty($this->Sender) and !ini_get('safe_mode') and $this->validateAddress($this->Sender)) {
  1930. $old_from = ini_get('sendmail_from');
  1931. ini_set('sendmail_from', $this->Sender);
  1932. if ($this->SingleTo === true && count($toArr) > 1) {
  1933. foreach ($toArr as $key => $val) {
  1934. $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
  1935. // implement call back function if it exists
  1936. $isSent = ($rt == 1) ? 1 : 0;
  1937. $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
  1938. }
  1939. } else {
  1940. $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
  1941. // implement call back function if it exists
  1942. $isSent = ($rt == 1) ? 1 : 0;
  1943. $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body);
  1944. }
  1945. } else {
  1946. if ($this->SingleTo === true && count($toArr) > 1) {
  1947. foreach ($toArr as $key => $val) {
  1948. $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
  1949. // implement call back function if it exists
  1950. $isSent = ($rt == 1) ? 1 : 0;
  1951. $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
  1952. }
  1953. } else {
  1954. $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header);
  1955. // implement call back function if it exists
  1956. $isSent = ($rt == 1) ? 1 : 0;
  1957. $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body);
  1958. }
  1959. }
  1960. if (isset($old_from)) {
  1961. ini_set('sendmail_from', $old_from);
  1962. }
  1963. if (!$rt) {
  1964. throw new phpmailerException($this->Lang('instantiate'), self::STOP_CRITICAL);
  1965. }
  1966. return true;
  1967. }
  1968. /**
  1969. * Sends mail via SMTP using PhpSMTP
  1970. * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
  1971. *
  1972. * @param string $header The message headers
  1973. * @param string $body The message body
  1974. *
  1975. * @uses \SMTP
  1976. *
  1977. * @return bool
  1978. */
  1979. protected function SmtpSend($header, $body)
  1980. {
  1981. require_once $this->PluginDir.'class.smtp.php';
  1982. $bad_rcpt = [];
  1983. if (!$this->SmtpConnect()) {
  1984. throw new phpmailerException($this->Lang('smtp_connect_failed'), self::STOP_CRITICAL);
  1985. }
  1986. if (!empty($this->Sender) and $this->validateAddress($this->Sender)) {
  1987. $smtp_from = $this->Sender;
  1988. } else {
  1989. $smtp_from = $this->From;
  1990. }
  1991. if (!$this->smtp->Mail($smtp_from)) {
  1992. throw new phpmailerException($this->Lang('from_failed').$smtp_from, self::STOP_CRITICAL);
  1993. }
  1994. // Attempt to send attach all recipients
  1995. foreach ($this->to as $to) {
  1996. if (!$this->smtp->Recipient($to[0])) {
  1997. $bad_rcpt[] = $to[0];
  1998. // implement call back function if it exists
  1999. $isSent = 0;
  2000. $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body);
  2001. } else {
  2002. // implement call back function if it exists
  2003. $isSent = 1;
  2004. $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body);
  2005. }
  2006. }
  2007. foreach ($this->cc as $cc) {
  2008. if (!$this->smtp->Recipient($cc[0])) {
  2009. $bad_rcpt[] = $cc[0];
  2010. // implement call back function if it exists
  2011. $isSent = 0;
  2012. $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body);
  2013. } else {
  2014. // implement call back function if it exists
  2015. $isSent = 1;
  2016. $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body);
  2017. }
  2018. }
  2019. foreach ($this->bcc as $bcc) {
  2020. if (!$this->smtp->Recipient($bcc[0])) {
  2021. $bad_rcpt[] = $bcc[0];
  2022. // implement call back function if it exists
  2023. $isSent = 0;
  2024. $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body);
  2025. } else {
  2026. // implement call back function if it exists
  2027. $isSent = 1;
  2028. $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body);
  2029. }
  2030. }
  2031. if (count($bad_rcpt) > 0) { //Create error message for any bad addresses
  2032. $badaddresses = implode(', ', $bad_rcpt);
  2033. throw new phpmailerException($this->Lang('recipients_failed').$badaddresses);
  2034. }
  2035. if (!$this->smtp->Data($header.$body)) {
  2036. throw new phpmailerException($this->Lang('data_not_accepted'), self::STOP_CRITICAL);
  2037. }
  2038. if ($this->SMTPKeepAlive == true) {
  2039. $this->smtp->Reset();
  2040. }
  2041. return true;
  2042. }
  2043. /////////////////////////////////////////////////
  2044. // CLASS METHODS, MISCELLANEOUS
  2045. /////////////////////////////////////////////////
  2046. /**
  2047. * Adds the error message to the error container.
  2048. */
  2049. protected function SetError($msg)
  2050. {
  2051. $this->error_count++;
  2052. if ($this->Mailer == 'smtp' and !is_null($this->smtp)) {
  2053. $lasterror = $this->smtp->getError();
  2054. if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) {
  2055. $msg .= '<p>'.$this->Lang('smtp_error').$lasterror['smtp_msg']."</p>\n";
  2056. }
  2057. }
  2058. $this->ErrorInfo = $msg;
  2059. }
  2060. protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body)
  2061. {
  2062. if (!empty($this->action_function) && function_exists($this->action_function)) {
  2063. $params = [$isSent, $to, $cc, $bcc, $subject, $body];
  2064. call_user_func_array($this->action_function, $params);
  2065. }
  2066. }
  2067. /**
  2068. * Adds an address to one of the recipient arrays
  2069. * Addresses that have been added already return false, but do not throw exceptions.
  2070. *
  2071. * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo'
  2072. * @param string $address The email address to send to
  2073. * @param string $name
  2074. *
  2075. * @return bool true on success, false if address already used or invalid in some way
  2076. */
  2077. private function AddAnAddress($kind, $address, $name = '')
  2078. {
  2079. if (!preg_match('/^(to|cc|bcc|ReplyTo)$/', $kind)) {
  2080. error_log('Invalid recipient array: '.$kind);
  2081. return false;
  2082. }
  2083. $address = trim($address);
  2084. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  2085. if (!self::ValidateAddress($address)) {
  2086. $this->SetError($this->Lang('invalid_address').': '.$address);
  2087. if ($this->exceptions) {
  2088. throw new phpmailerException($this->Lang('invalid_address').': '.$address);
  2089. }
  2090. error_log($this->Lang('invalid_address').': '.$address);
  2091. return false;
  2092. }
  2093. if ($kind != 'ReplyTo') {
  2094. if (!isset($this->all_recipients[strtolower($address)])) {
  2095. array_push($this->$kind, [$address, $name]);
  2096. $this->all_recipients[strtolower($address)] = true;
  2097. return true;
  2098. }
  2099. } else {
  2100. if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
  2101. $this->ReplyTo[strtolower($address)] = [$address, $name];
  2102. return true;
  2103. }
  2104. }
  2105. return false;
  2106. }
  2107. /**
  2108. * Returns the start of a message boundary.
  2109. */
  2110. private function GetBoundary($boundary, $charSet, $contentType, $encoding)
  2111. {
  2112. $result = '';
  2113. if ($charSet == '') {
  2114. $charSet = $this->CharSet;
  2115. }
  2116. if ($contentType == '') {
  2117. $contentType = $this->ContentType;
  2118. }
  2119. if ($encoding == '') {
  2120. $encoding = $this->Encoding;
  2121. }
  2122. $result .= $this->TextLine('--'.$boundary);
  2123. $result .= sprintf("Content-Type: %s; charset = \"%s\"", $contentType, $charSet);
  2124. $result .= $this->LE;
  2125. $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding);
  2126. $result .= $this->LE;
  2127. return $result;
  2128. }
  2129. /**
  2130. * Returns the end of a message boundary.
  2131. */
  2132. private function EndBoundary($boundary)
  2133. {
  2134. return $this->LE.'--'.$boundary.'--'.$this->LE;
  2135. }
  2136. /**
  2137. * Sets the message type.
  2138. */
  2139. private function SetMessageType()
  2140. {
  2141. if (count($this->attachment) < 1 && strlen($this->AltBody) < 1) {
  2142. $this->message_type = 'plain';
  2143. } else {
  2144. if (count($this->attachment) > 0) {
  2145. $this->message_type = 'attachments';
  2146. }
  2147. if (strlen($this->AltBody) > 0 && count($this->attachment) < 1) {
  2148. $this->message_type = 'alt';
  2149. }
  2150. if (strlen($this->AltBody) > 0 && count($this->attachment) > 0) {
  2151. $this->message_type = 'alt_attachments';
  2152. }
  2153. }
  2154. }
  2155. /**
  2156. * Attaches all fs, string, and binary attachments to the message.
  2157. * Returns an empty string on failure.
  2158. *
  2159. * @return string
  2160. */
  2161. private function AttachAll()
  2162. {
  2163. // Return text of body
  2164. $mime = [];
  2165. $cidUniq = [];
  2166. $incl = [];
  2167. // Add all attachments
  2168. foreach ($this->attachment as $attachment) {
  2169. // Check for string attachment
  2170. $bString = $attachment[5];
  2171. if ($bString) {
  2172. $string = $attachment[0];
  2173. } else {
  2174. $path = $attachment[0];
  2175. }
  2176. if (in_array($attachment[0], $incl)) {
  2177. continue;
  2178. }
  2179. $filename = $attachment[1];
  2180. $name = $attachment[2];
  2181. $encoding = $attachment[3];
  2182. $type = $attachment[4];
  2183. $disposition = $attachment[6];
  2184. $cid = $attachment[7];
  2185. $incl[] = $attachment[0];
  2186. if ($disposition == 'inline' && isset($cidUniq[$cid])) {
  2187. continue;
  2188. }
  2189. $cidUniq[$cid] = true;
  2190. $mime[] = sprintf("--%s%s", $this->boundary[1], $this->LE);
  2191. $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $this->EncodeHeader($this->SecureHeader($name)), $this->LE);
  2192. $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE);
  2193. if ($disposition == 'inline') {
  2194. $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE);
  2195. }
  2196. $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE);
  2197. // Encode as string attachment
  2198. if ($bString) {
  2199. $mime[] = $this->EncodeString($string, $encoding);
  2200. if ($this->IsError()) {
  2201. return '';
  2202. }
  2203. $mime[] = $this->LE.$this->LE;
  2204. } else {
  2205. $mime[] = $this->EncodeFile($path, $encoding);
  2206. if ($this->IsError()) {
  2207. return '';
  2208. }
  2209. $mime[] = $this->LE.$this->LE;
  2210. }
  2211. }
  2212. $mime[] = sprintf("--%s--%s", $this->boundary[1], $this->LE);
  2213. return join('', $mime);
  2214. }
  2215. /**
  2216. * Encodes attachment in requested format.
  2217. * Returns an empty string on failure.
  2218. *
  2219. * @param string $path The full path to the file
  2220. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  2221. *
  2222. * @see EncodeFile()
  2223. *
  2224. * @return string
  2225. */
  2226. private function EncodeFile($path, $encoding = 'base64')
  2227. {
  2228. try {
  2229. if (!is_readable($path)) {
  2230. throw new phpmailerException($this->Lang('file_open').$path, self::STOP_CONTINUE);
  2231. }
  2232. $magic_quotes = get_magic_quotes_runtime();
  2233. if ($magic_quotes) {
  2234. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  2235. set_magic_quotes_runtime(0);
  2236. } else {
  2237. ini_set('magic_quotes_runtime', 0);
  2238. }
  2239. }
  2240. $file_buffer = file_get_contents($path);
  2241. $file_buffer = $this->EncodeString($file_buffer, $encoding);
  2242. if ($magic_quotes) {
  2243. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  2244. set_magic_quotes_runtime($magic_quotes);
  2245. } else {
  2246. ini_set('magic_quotes_runtime', $magic_quotes);
  2247. }
  2248. }
  2249. return $file_buffer;
  2250. } catch (Exception $e) {
  2251. $this->SetError($e->getMessage());
  2252. return '';
  2253. }
  2254. }
  2255. /**
  2256. * Returns the server hostname or 'localhost.localdomain' if unknown.
  2257. *
  2258. * @return string
  2259. */
  2260. private function ServerHostname()
  2261. {
  2262. if (!empty($this->Hostname)) {
  2263. $result = $this->Hostname;
  2264. } elseif (isset($_SERVER['SERVER_NAME'])) {
  2265. $result = $_SERVER['SERVER_NAME'];
  2266. } else {
  2267. $result = 'localhost.localdomain';
  2268. }
  2269. return $result;
  2270. }
  2271. /**
  2272. * Returns a message in the appropriate language.
  2273. *
  2274. * @return string
  2275. */
  2276. private function Lang($key)
  2277. {
  2278. if (count($this->language) < 1) {
  2279. $this->SetLanguage('en'); // set the default language
  2280. }
  2281. if (isset($this->language[$key])) {
  2282. return $this->language[$key];
  2283. } else {
  2284. return 'Language string failed to load: '.$key;
  2285. }
  2286. }
  2287. /**
  2288. * Changes every end of line from CR or LF to CRLF.
  2289. *
  2290. * @return string
  2291. */
  2292. private function FixEOL($str)
  2293. {
  2294. $str = str_replace("\r\n", "\n", $str);
  2295. $str = str_replace("\r", "\n", $str);
  2296. $str = str_replace("\n", $this->LE, $str);
  2297. return $str;
  2298. }
  2299. }
  2300. class phpmailerException extends Exception
  2301. {
  2302. public function errorMessage()
  2303. {
  2304. $errorMsg = '<strong>'.$this->getMessage()."</strong><br />\n";
  2305. return $errorMsg;
  2306. }
  2307. }