Phpmailer.php 92 KB

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