class.phpmailer.php 75 KB

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