class.phpmailer.php 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354
  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($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  531. }
  532. if (!empty($this->Sender) and $this->validateAddress($this->Sender)) {
  533. if ($this->Mailer == 'qmail') {
  534. $sendmail = sprintf('%s -f%s', escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
  535. } else {
  536. $sendmail = sprintf('%s -oi -f%s -t', escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
  537. }
  538. } else {
  539. if ($this->Mailer == 'qmail') {
  540. $sendmail = sprintf('%s', escapeshellcmd($this->Sendmail));
  541. } else {
  542. $sendmail = sprintf('%s -oi -t', escapeshellcmd($this->Sendmail));
  543. }
  544. }
  545. if ($this->SingleTo === true) {
  546. foreach ($this->SingleToArray as $key => $val) {
  547. if(!@$mail = popen($sendmail, 'w')) {
  548. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  549. }
  550. fputs($mail, "To: " . $val . "\n");
  551. fputs($mail, $header);
  552. fputs($mail, $body);
  553. $result = pclose($mail);
  554. // implement call back function if it exists
  555. $isSent = ($result == 0) ? 1 : 0;
  556. $this->doCallback($isSent,$val,$this->cc,$this->bcc,$this->Subject,$body);
  557. if($result != 0) {
  558. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  559. }
  560. }
  561. } else {
  562. if(!@$mail = popen($sendmail, 'w')) {
  563. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  564. }
  565. fputs($mail, $header);
  566. fputs($mail, $body);
  567. $result = pclose($mail);
  568. // implement call back function if it exists
  569. $isSent = ($result == 0) ? 1 : 0;
  570. $this->doCallback($isSent,$this->to,$this->cc,$this->bcc,$this->Subject,$body);
  571. if($result != 0) {
  572. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  573. }
  574. }
  575. return true;
  576. }
  577. /**
  578. * Sends mail using the PHP mail() function.
  579. * @param string $header The message headers
  580. * @param string $body The message body
  581. * @access protected
  582. * @return bool
  583. */
  584. protected function MailSend($header, $body) {
  585. $toArr = array();
  586. foreach($this->to as $t) {
  587. $toArr[] = $this->AddrFormat($t);
  588. }
  589. $to = implode(', ', $toArr);
  590. $params = sprintf("-oi -f %s", $this->Sender);
  591. if (!empty($this->Sender) and !ini_get('safe_mode') and $this->validateAddress($this->Sender)) {
  592. $old_from = ini_get('sendmail_from');
  593. ini_set('sendmail_from', $this->Sender);
  594. if ($this->SingleTo === true && count($toArr) > 1) {
  595. foreach ($toArr as $key => $val) {
  596. $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
  597. // implement call back function if it exists
  598. $isSent = ($rt == 1) ? 1 : 0;
  599. $this->doCallback($isSent,$val,$this->cc,$this->bcc,$this->Subject,$body);
  600. }
  601. } else {
  602. $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
  603. // implement call back function if it exists
  604. $isSent = ($rt == 1) ? 1 : 0;
  605. $this->doCallback($isSent,$to,$this->cc,$this->bcc,$this->Subject,$body);
  606. }
  607. } else {
  608. if ($this->SingleTo === true && count($toArr) > 1) {
  609. foreach ($toArr as $key => $val) {
  610. $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
  611. // implement call back function if it exists
  612. $isSent = ($rt == 1) ? 1 : 0;
  613. $this->doCallback($isSent,$val,$this->cc,$this->bcc,$this->Subject,$body);
  614. }
  615. } else {
  616. $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header);
  617. // implement call back function if it exists
  618. $isSent = ($rt == 1) ? 1 : 0;
  619. $this->doCallback($isSent,$to,$this->cc,$this->bcc,$this->Subject,$body);
  620. }
  621. }
  622. if (isset($old_from)) {
  623. ini_set('sendmail_from', $old_from);
  624. }
  625. if(!$rt) {
  626. throw new phpmailerException($this->Lang('instantiate'), self::STOP_CRITICAL);
  627. }
  628. return true;
  629. }
  630. /**
  631. * Sends mail via SMTP using PhpSMTP
  632. * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
  633. * @param string $header The message headers
  634. * @param string $body The message body
  635. * @uses SMTP
  636. * @access protected
  637. * @return bool
  638. */
  639. protected function SmtpSend($header, $body) {
  640. require_once $this->PluginDir . 'class.smtp.php';
  641. $bad_rcpt = array();
  642. if(!$this->SmtpConnect()) {
  643. throw new phpmailerException($this->Lang('smtp_connect_failed'), self::STOP_CRITICAL);
  644. }
  645. if (!empty($this->Sender) and $this->validateAddress($this->Sender)) {
  646. $smtp_from = $this->Sender;
  647. } else {
  648. $smtp_from = $this->From;
  649. }
  650. if(!$this->smtp->Mail($smtp_from)) {
  651. throw new phpmailerException($this->Lang('from_failed') . $smtp_from, self::STOP_CRITICAL);
  652. }
  653. // Attempt to send attach all recipients
  654. foreach($this->to as $to) {
  655. if (!$this->smtp->Recipient($to[0])) {
  656. $bad_rcpt[] = $to[0];
  657. // implement call back function if it exists
  658. $isSent = 0;
  659. $this->doCallback($isSent,$to[0],'','',$this->Subject,$body);
  660. } else {
  661. // implement call back function if it exists
  662. $isSent = 1;
  663. $this->doCallback($isSent,$to[0],'','',$this->Subject,$body);
  664. }
  665. }
  666. foreach($this->cc as $cc) {
  667. if (!$this->smtp->Recipient($cc[0])) {
  668. $bad_rcpt[] = $cc[0];
  669. // implement call back function if it exists
  670. $isSent = 0;
  671. $this->doCallback($isSent,'',$cc[0],'',$this->Subject,$body);
  672. } else {
  673. // implement call back function if it exists
  674. $isSent = 1;
  675. $this->doCallback($isSent,'',$cc[0],'',$this->Subject,$body);
  676. }
  677. }
  678. foreach($this->bcc as $bcc) {
  679. if (!$this->smtp->Recipient($bcc[0])) {
  680. $bad_rcpt[] = $bcc[0];
  681. // implement call back function if it exists
  682. $isSent = 0;
  683. $this->doCallback($isSent,'','',$bcc[0],$this->Subject,$body);
  684. } else {
  685. // implement call back function if it exists
  686. $isSent = 1;
  687. $this->doCallback($isSent,'','',$bcc[0],$this->Subject,$body);
  688. }
  689. }
  690. if (count($bad_rcpt) > 0 ) { //Create error message for any bad addresses
  691. $badaddresses = implode(', ', $bad_rcpt);
  692. throw new phpmailerException($this->Lang('recipients_failed') . $badaddresses);
  693. }
  694. if(!$this->smtp->Data($header . $body)) {
  695. throw new phpmailerException($this->Lang('data_not_accepted'), self::STOP_CRITICAL);
  696. }
  697. if($this->SMTPKeepAlive == true) {
  698. $this->smtp->Reset();
  699. }
  700. return true;
  701. }
  702. /**
  703. * Initiates a connection to an SMTP server.
  704. * Returns false if the operation failed.
  705. * @uses SMTP
  706. * @access public
  707. * @return bool
  708. */
  709. public function SmtpConnect() {
  710. if(is_null($this->smtp)) {
  711. $this->smtp = new SMTP();
  712. }
  713. $this->smtp->do_debug = $this->SMTPDebug;
  714. $hosts = explode(';', $this->Host);
  715. $index = 0;
  716. $connection = $this->smtp->Connected();
  717. // Retry while there is no connection
  718. try {
  719. while($index < count($hosts) && !$connection) {
  720. $hostinfo = array();
  721. if (preg_match('/^(.+):([0-9]+)$/', $hosts[$index], $hostinfo)) {
  722. $host = $hostinfo[1];
  723. $port = $hostinfo[2];
  724. } else {
  725. $host = $hosts[$index];
  726. $port = $this->Port;
  727. }
  728. $tls = ($this->SMTPSecure == 'tls');
  729. $ssl = ($this->SMTPSecure == 'ssl');
  730. if ($this->smtp->Connect(($ssl ? 'ssl://':'').$host, $port, $this->Timeout)) {
  731. $hello = ($this->Helo != '' ? $this->Helo : $this->ServerHostname());
  732. $this->smtp->Hello($hello);
  733. if ($tls) {
  734. if (!$this->smtp->StartTLS()) {
  735. throw new phpmailerException($this->Lang('tls'));
  736. }
  737. //We must resend HELO after tls negotiation
  738. $this->smtp->Hello($hello);
  739. }
  740. $connection = true;
  741. if ($this->SMTPAuth) {
  742. if (!$this->smtp->Authenticate($this->Username, $this->Password)) {
  743. throw new phpmailerException($this->Lang('authenticate'));
  744. }
  745. }
  746. }
  747. $index++;
  748. if (!$connection) {
  749. throw new phpmailerException($this->Lang('connect_host'));
  750. }
  751. }
  752. } catch (phpmailerException $e) {
  753. $this->smtp->Reset();
  754. throw $e;
  755. }
  756. return true;
  757. }
  758. /**
  759. * Closes the active SMTP session if one exists.
  760. * @return void
  761. */
  762. public function SmtpClose() {
  763. if(!is_null($this->smtp)) {
  764. if($this->smtp->Connected()) {
  765. $this->smtp->Quit();
  766. $this->smtp->Close();
  767. }
  768. }
  769. }
  770. /**
  771. * Sets the language for all class error messages.
  772. * Returns false if it cannot load the language file. The default language is English.
  773. * @param string $langcode ISO 639-1 2-character language code (e.g. Portuguese: "br")
  774. * @param string $lang_path Path to the language file directory
  775. * @access public
  776. */
  777. function SetLanguage($langcode = 'en', $lang_path = 'language/') {
  778. //Define full set of translatable strings
  779. $PHPMAILER_LANG = array(
  780. 'provide_address' => 'You must provide at least one recipient email address.',
  781. 'mailer_not_supported' => ' mailer is not supported.',
  782. 'execute' => 'Could not execute: ',
  783. 'instantiate' => 'Could not instantiate mail function.',
  784. 'authenticate' => 'SMTP Error: Could not authenticate.',
  785. 'from_failed' => 'The following From address failed: ',
  786. 'recipients_failed' => 'SMTP Error: The following recipients failed: ',
  787. 'data_not_accepted' => 'SMTP Error: Data not accepted.',
  788. 'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
  789. 'file_access' => 'Could not access file: ',
  790. 'file_open' => 'File Error: Could not open file: ',
  791. 'encoding' => 'Unknown encoding: ',
  792. 'signing' => 'Signing Error: ',
  793. 'smtp_error' => 'SMTP server error: ',
  794. 'empty_message' => 'Message body empty',
  795. 'invalid_address' => 'Invalid address',
  796. 'variable_set' => 'Cannot set or reset variable: '
  797. );
  798. //Overwrite language-specific strings. This way we'll never have missing translations - no more "language string failed to load"!
  799. $l = true;
  800. if ($langcode != 'en') { //There is no English translation file
  801. $l = @include $lang_path.'phpmailer.lang-'.$langcode.'.php';
  802. }
  803. $this->language = $PHPMAILER_LANG;
  804. return ($l == true); //Returns false if language not found
  805. }
  806. /**
  807. * Return the current array of language strings
  808. * @return array
  809. */
  810. public function GetTranslations() {
  811. return $this->language;
  812. }
  813. /////////////////////////////////////////////////
  814. // METHODS, MESSAGE CREATION
  815. /////////////////////////////////////////////////
  816. /**
  817. * Creates recipient headers.
  818. * @access public
  819. * @return string
  820. */
  821. public function AddrAppend($type, $addr) {
  822. $addr_str = $type . ': ';
  823. $addresses = array();
  824. foreach ($addr as $a) {
  825. $addresses[] = $this->AddrFormat($a);
  826. }
  827. $addr_str .= implode(', ', $addresses);
  828. $addr_str .= $this->LE;
  829. return $addr_str;
  830. }
  831. /**
  832. * Formats an address correctly.
  833. * @access public
  834. * @return string
  835. */
  836. public function AddrFormat($addr) {
  837. if (empty($addr[1])) {
  838. return $this->SecureHeader($addr[0]);
  839. } else {
  840. return $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">";
  841. }
  842. }
  843. /**
  844. * Wraps message for use with mailers that do not
  845. * automatically perform wrapping and for quoted-printable.
  846. * Original written by philippe.
  847. * @param string $message The message to wrap
  848. * @param integer $length The line length to wrap to
  849. * @param boolean $qp_mode Whether to run in Quoted-Printable mode
  850. * @access public
  851. * @return string
  852. */
  853. public function WrapText($message, $length, $qp_mode = false) {
  854. $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE;
  855. // If utf-8 encoding is used, we will need to make sure we don't
  856. // split multibyte characters when we wrap
  857. $is_utf8 = (strtolower($this->CharSet) == "utf-8");
  858. $message = $this->FixEOL($message);
  859. if (substr($message, -1) == $this->LE) {
  860. $message = substr($message, 0, -1);
  861. }
  862. $line = explode($this->LE, $message);
  863. $message = '';
  864. for ($i=0 ;$i < count($line); $i++) {
  865. $line_part = explode(' ', $line[$i]);
  866. $buf = '';
  867. for ($e = 0; $e<count($line_part); $e++) {
  868. $word = $line_part[$e];
  869. if ($qp_mode and (strlen($word) > $length)) {
  870. $space_left = $length - strlen($buf) - 1;
  871. if ($e != 0) {
  872. if ($space_left > 20) {
  873. $len = $space_left;
  874. if ($is_utf8) {
  875. $len = $this->UTF8CharBoundary($word, $len);
  876. } elseif (substr($word, $len - 1, 1) == "=") {
  877. $len--;
  878. } elseif (substr($word, $len - 2, 1) == "=") {
  879. $len -= 2;
  880. }
  881. $part = substr($word, 0, $len);
  882. $word = substr($word, $len);
  883. $buf .= ' ' . $part;
  884. $message .= $buf . sprintf("=%s", $this->LE);
  885. } else {
  886. $message .= $buf . $soft_break;
  887. }
  888. $buf = '';
  889. }
  890. while (strlen($word) > 0) {
  891. $len = $length;
  892. if ($is_utf8) {
  893. $len = $this->UTF8CharBoundary($word, $len);
  894. } elseif (substr($word, $len - 1, 1) == "=") {
  895. $len--;
  896. } elseif (substr($word, $len - 2, 1) == "=") {
  897. $len -= 2;
  898. }
  899. $part = substr($word, 0, $len);
  900. $word = substr($word, $len);
  901. if (strlen($word) > 0) {
  902. $message .= $part . sprintf("=%s", $this->LE);
  903. } else {
  904. $buf = $part;
  905. }
  906. }
  907. } else {
  908. $buf_o = $buf;
  909. $buf .= ($e == 0) ? $word : (' ' . $word);
  910. if (strlen($buf) > $length and $buf_o != '') {
  911. $message .= $buf_o . $soft_break;
  912. $buf = $word;
  913. }
  914. }
  915. }
  916. $message .= $buf . $this->LE;
  917. }
  918. return $message;
  919. }
  920. /**
  921. * Finds last character boundary prior to maxLength in a utf-8
  922. * quoted (printable) encoded string.
  923. * Original written by Colin Brown.
  924. * @access public
  925. * @param string $encodedText utf-8 QP text
  926. * @param int $maxLength find last character boundary prior to this length
  927. * @return int
  928. */
  929. public function UTF8CharBoundary($encodedText, $maxLength) {
  930. $foundSplitPos = false;
  931. $lookBack = 3;
  932. while (!$foundSplitPos) {
  933. $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
  934. $encodedCharPos = strpos($lastChunk, "=");
  935. if ($encodedCharPos !== false) {
  936. // Found start of encoded character byte within $lookBack block.
  937. // Check the encoded byte value (the 2 chars after the '=')
  938. $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
  939. $dec = hexdec($hex);
  940. if ($dec < 128) { // Single byte character.
  941. // If the encoded char was found at pos 0, it will fit
  942. // otherwise reduce maxLength to start of the encoded char
  943. $maxLength = ($encodedCharPos == 0) ? $maxLength :
  944. $maxLength - ($lookBack - $encodedCharPos);
  945. $foundSplitPos = true;
  946. } elseif ($dec >= 192) { // First byte of a multi byte character
  947. // Reduce maxLength to split at start of character
  948. $maxLength = $maxLength - ($lookBack - $encodedCharPos);
  949. $foundSplitPos = true;
  950. } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back
  951. $lookBack += 3;
  952. }
  953. } else {
  954. // No encoded character found
  955. $foundSplitPos = true;
  956. }
  957. }
  958. return $maxLength;
  959. }
  960. /**
  961. * Set the body wrapping.
  962. * @access public
  963. * @return void
  964. */
  965. public function SetWordWrap() {
  966. if($this->WordWrap < 1) {
  967. return;
  968. }
  969. switch($this->message_type) {
  970. case 'alt':
  971. case 'alt_attachments':
  972. $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap);
  973. break;
  974. default:
  975. $this->Body = $this->WrapText($this->Body, $this->WordWrap);
  976. break;
  977. }
  978. }
  979. /**
  980. * Assembles message header.
  981. * @access public
  982. * @return string The assembled header
  983. */
  984. public function CreateHeader() {
  985. $result = '';
  986. // Set the boundaries
  987. $uniq_id = md5(uniqid(time()));
  988. $this->boundary[1] = 'b1_' . $uniq_id;
  989. $this->boundary[2] = 'b2_' . $uniq_id;
  990. $result .= $this->HeaderLine('Date', self::RFCDate());
  991. if($this->Sender == '') {
  992. $result .= $this->HeaderLine('Return-Path', trim($this->From));
  993. } else {
  994. $result .= $this->HeaderLine('Return-Path', trim($this->Sender));
  995. }
  996. // To be created automatically by mail()
  997. if($this->Mailer != 'mail') {
  998. if ($this->SingleTo === true) {
  999. foreach($this->to as $t) {
  1000. $this->SingleToArray[] = $this->AddrFormat($t);
  1001. }
  1002. } else {
  1003. if(count($this->to) > 0) {
  1004. $result .= $this->AddrAppend('To', $this->to);
  1005. } elseif (count($this->cc) == 0) {
  1006. $result .= $this->HeaderLine('To', 'undisclosed-recipients:;');
  1007. }
  1008. }
  1009. }
  1010. $from = array();
  1011. $from[0][0] = trim($this->From);
  1012. $from[0][1] = $this->FromName;
  1013. $result .= $this->AddrAppend('From', $from);
  1014. // sendmail and mail() extract Cc from the header before sending
  1015. if(count($this->cc) > 0) {
  1016. $result .= $this->AddrAppend('Cc', $this->cc);
  1017. }
  1018. // sendmail and mail() extract Bcc from the header before sending
  1019. if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) {
  1020. $result .= $this->AddrAppend('Bcc', $this->bcc);
  1021. }
  1022. if(count($this->ReplyTo) > 0) {
  1023. $result .= $this->AddrAppend('Reply-to', $this->ReplyTo);
  1024. }
  1025. // mail() sets the subject itself
  1026. if($this->Mailer != 'mail') {
  1027. $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject)));
  1028. }
  1029. if($this->MessageID != '') {
  1030. $result .= $this->HeaderLine('Message-ID',$this->MessageID);
  1031. } else {
  1032. $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);
  1033. }
  1034. $result .= $this->HeaderLine('X-Priority', $this->Priority);
  1035. $result .= $this->HeaderLine('X-Mailer', 'PHPMailer '.$this->Version.' (phpmailer.sourceforge.net)');
  1036. if($this->ConfirmReadingTo != '') {
  1037. $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>');
  1038. }
  1039. // Add custom headers
  1040. for($index = 0; $index < count($this->CustomHeader); $index++) {
  1041. $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1])));
  1042. }
  1043. if (!$this->sign_key_file) {
  1044. $result .= $this->HeaderLine('MIME-Version', '1.0');
  1045. $result .= $this->GetMailMIME();
  1046. }
  1047. return $result;
  1048. }
  1049. /**
  1050. * Returns the message MIME.
  1051. * @access public
  1052. * @return string
  1053. */
  1054. public function GetMailMIME() {
  1055. $result = '';
  1056. switch($this->message_type) {
  1057. case 'plain':
  1058. $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding);
  1059. $result .= sprintf("Content-Type: %s; charset=\"%s\"", $this->ContentType, $this->CharSet);
  1060. break;
  1061. case 'attachments':
  1062. case 'alt_attachments':
  1063. if($this->InlineImageExists()){
  1064. $result .= sprintf("Content-Type: %s;%s\ttype=\"text/html\";%s\tboundary=\"%s\"%s", 'multipart/related', $this->LE, $this->LE, $this->boundary[1], $this->LE);
  1065. } else {
  1066. $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;');
  1067. $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
  1068. }
  1069. break;
  1070. case 'alt':
  1071. $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
  1072. $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
  1073. break;
  1074. }
  1075. if($this->Mailer != 'mail') {
  1076. $result .= $this->LE.$this->LE;
  1077. }
  1078. return $result;
  1079. }
  1080. /**
  1081. * Assembles the message body. Returns an empty string on failure.
  1082. * @access public
  1083. * @return string The assembled message body
  1084. */
  1085. public function CreateBody() {
  1086. $body = '';
  1087. if ($this->sign_key_file) {
  1088. $body .= $this->GetMailMIME();
  1089. }
  1090. $this->SetWordWrap();
  1091. switch($this->message_type) {
  1092. case 'alt':
  1093. $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
  1094. $body .= $this->EncodeString($this->AltBody, $this->Encoding);
  1095. $body .= $this->LE.$this->LE;
  1096. $body .= $this->GetBoundary($this->boundary[1], '', 'text/html', '');
  1097. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1098. $body .= $this->LE.$this->LE;
  1099. $body .= $this->EndBoundary($this->boundary[1]);
  1100. break;
  1101. case 'plain':
  1102. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1103. break;
  1104. case 'attachments':
  1105. $body .= $this->GetBoundary($this->boundary[1], '', '', '');
  1106. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1107. $body .= $this->LE;
  1108. $body .= $this->AttachAll();
  1109. break;
  1110. case 'alt_attachments':
  1111. $body .= sprintf("--%s%s", $this->boundary[1], $this->LE);
  1112. $body .= sprintf("Content-Type: %s;%s" . "\tboundary=\"%s\"%s", 'multipart/alternative', $this->LE, $this->boundary[2], $this->LE.$this->LE);
  1113. $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '') . $this->LE; // Create text body
  1114. $body .= $this->EncodeString($this->AltBody, $this->Encoding);
  1115. $body .= $this->LE.$this->LE;
  1116. $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '') . $this->LE; // Create the HTML body
  1117. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1118. $body .= $this->LE.$this->LE;
  1119. $body .= $this->EndBoundary($this->boundary[2]);
  1120. $body .= $this->AttachAll();
  1121. break;
  1122. }
  1123. if ($this->IsError()) {
  1124. $body = '';
  1125. } elseif ($this->sign_key_file) {
  1126. try {
  1127. $file = tempnam('', 'mail');
  1128. file_put_contents($file, $body); //TODO check this worked
  1129. $signed = tempnam("", "signed");
  1130. if (@openssl_pkcs7_sign($file, $signed, "file://".$this->sign_cert_file, array("file://".$this->sign_key_file, $this->sign_key_pass), NULL)) {
  1131. @unlink($file);
  1132. @unlink($signed);
  1133. $body = file_get_contents($signed);
  1134. } else {
  1135. @unlink($file);
  1136. @unlink($signed);
  1137. throw new phpmailerException($this->Lang("signing").openssl_error_string());
  1138. }
  1139. } catch (phpmailerException $e) {
  1140. $body = '';
  1141. if ($this->exceptions) {
  1142. throw $e;
  1143. }
  1144. }
  1145. }
  1146. return $body;
  1147. }
  1148. /**
  1149. * Returns the start of a message boundary.
  1150. * @access private
  1151. */
  1152. private function GetBoundary($boundary, $charSet, $contentType, $encoding) {
  1153. $result = '';
  1154. if($charSet == '') {
  1155. $charSet = $this->CharSet;
  1156. }
  1157. if($contentType == '') {
  1158. $contentType = $this->ContentType;
  1159. }
  1160. if($encoding == '') {
  1161. $encoding = $this->Encoding;
  1162. }
  1163. $result .= $this->TextLine('--' . $boundary);
  1164. $result .= sprintf("Content-Type: %s; charset = \"%s\"", $contentType, $charSet);
  1165. $result .= $this->LE;
  1166. $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding);
  1167. $result .= $this->LE;
  1168. return $result;
  1169. }
  1170. /**
  1171. * Returns the end of a message boundary.
  1172. * @access private
  1173. */
  1174. private function EndBoundary($boundary) {
  1175. return $this->LE . '--' . $boundary . '--' . $this->LE;
  1176. }
  1177. /**
  1178. * Sets the message type.
  1179. * @access private
  1180. * @return void
  1181. */
  1182. private function SetMessageType() {
  1183. if(count($this->attachment) < 1 && strlen($this->AltBody) < 1) {
  1184. $this->message_type = 'plain';
  1185. } else {
  1186. if(count($this->attachment) > 0) {
  1187. $this->message_type = 'attachments';
  1188. }
  1189. if(strlen($this->AltBody) > 0 && count($this->attachment) < 1) {
  1190. $this->message_type = 'alt';
  1191. }
  1192. if(strlen($this->AltBody) > 0 && count($this->attachment) > 0) {
  1193. $this->message_type = 'alt_attachments';
  1194. }
  1195. }
  1196. }
  1197. /**
  1198. * Returns a formatted header line.
  1199. * @access public
  1200. * @return string
  1201. */
  1202. public function HeaderLine($name, $value) {
  1203. return $name . ': ' . $value . $this->LE;
  1204. }
  1205. /**
  1206. * Returns a formatted mail line.
  1207. * @access public
  1208. * @return string
  1209. */
  1210. public function TextLine($value) {
  1211. return $value . $this->LE;
  1212. }
  1213. /////////////////////////////////////////////////
  1214. // CLASS METHODS, ATTACHMENTS
  1215. /////////////////////////////////////////////////
  1216. /**
  1217. * Adds an attachment from a path on the filesystem.
  1218. * Returns false if the file could not be found
  1219. * or accessed.
  1220. * @param string $path Path to the attachment.
  1221. * @param string $name Overrides the attachment name.
  1222. * @param string $encoding File encoding (see $Encoding).
  1223. * @param string $type File extension (MIME) type.
  1224. * @return bool
  1225. */
  1226. public function AddAttachment($path, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
  1227. try {
  1228. if ( !@is_file($path) ) {
  1229. throw new phpmailerException($this->Lang('file_access') . $path, self::STOP_CONTINUE);
  1230. }
  1231. $filename = basename($path);
  1232. if ( $name == '' ) {
  1233. $name = $filename;
  1234. }
  1235. $this->attachment[] = array(
  1236. 0 => $path,
  1237. 1 => $filename,
  1238. 2 => $name,
  1239. 3 => $encoding,
  1240. 4 => $type,
  1241. 5 => false, // isStringAttachment
  1242. 6 => 'attachment',
  1243. 7 => 0
  1244. );
  1245. } catch (phpmailerException $e) {
  1246. $this->SetError($e->getMessage());
  1247. if ($this->exceptions) {
  1248. throw $e;
  1249. }
  1250. error_log($e->getMessage()."\n");
  1251. if ( $e->getCode() == self::STOP_CRITICAL ) {
  1252. return false;
  1253. }
  1254. }
  1255. return true;
  1256. }
  1257. /**
  1258. * Return the current array of attachments
  1259. * @return array
  1260. */
  1261. public function GetAttachments() {
  1262. return $this->attachment;
  1263. }
  1264. /**
  1265. * Attaches all fs, string, and binary attachments to the message.
  1266. * Returns an empty string on failure.
  1267. * @access private
  1268. * @return string
  1269. */
  1270. private function AttachAll() {
  1271. // Return text of body
  1272. $mime = array();
  1273. $cidUniq = array();
  1274. $incl = array();
  1275. // Add all attachments
  1276. foreach ($this->attachment as $attachment) {
  1277. // Check for string attachment
  1278. $bString = $attachment[5];
  1279. if ($bString) {
  1280. $string = $attachment[0];
  1281. } else {
  1282. $path = $attachment[0];
  1283. }
  1284. if (in_array($attachment[0], $incl)) { continue; }
  1285. $filename = $attachment[1];
  1286. $name = $attachment[2];
  1287. $encoding = $attachment[3];
  1288. $type = $attachment[4];
  1289. $disposition = $attachment[6];
  1290. $cid = $attachment[7];
  1291. $incl[] = $attachment[0];
  1292. if ( $disposition == 'inline' && isset($cidUniq[$cid]) ) { continue; }
  1293. $cidUniq[$cid] = true;
  1294. $mime[] = sprintf("--%s%s", $this->boundary[1], $this->LE);
  1295. $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $this->EncodeHeader($this->SecureHeader($name)), $this->LE);
  1296. $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE);
  1297. if($disposition == 'inline') {
  1298. $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE);
  1299. }
  1300. $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE);
  1301. // Encode as string attachment
  1302. if($bString) {
  1303. $mime[] = $this->EncodeString($string, $encoding);
  1304. if($this->IsError()) {
  1305. return '';
  1306. }
  1307. $mime[] = $this->LE.$this->LE;
  1308. } else {
  1309. $mime[] = $this->EncodeFile($path, $encoding);
  1310. if($this->IsError()) {
  1311. return '';
  1312. }
  1313. $mime[] = $this->LE.$this->LE;
  1314. }
  1315. }
  1316. $mime[] = sprintf("--%s--%s", $this->boundary[1], $this->LE);
  1317. return join('', $mime);
  1318. }
  1319. /**
  1320. * Encodes attachment in requested format.
  1321. * Returns an empty string on failure.
  1322. * @param string $path The full path to the file
  1323. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  1324. * @see EncodeFile()
  1325. * @access private
  1326. * @return string
  1327. */
  1328. private function EncodeFile($path, $encoding = 'base64') {
  1329. try {
  1330. if (!is_readable($path)) {
  1331. throw new phpmailerException($this->Lang('file_open') . $path, self::STOP_CONTINUE);
  1332. }
  1333. $magic_quotes = get_magic_quotes_runtime();
  1334. if ($magic_quotes) {
  1335. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  1336. set_magic_quotes_runtime(0);
  1337. } else {
  1338. ini_set('magic_quotes_runtime', 0);
  1339. }
  1340. }
  1341. $file_buffer = file_get_contents($path);
  1342. $file_buffer = $this->EncodeString($file_buffer, $encoding);
  1343. if ($magic_quotes) {
  1344. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  1345. set_magic_quotes_runtime($magic_quotes);
  1346. } else {
  1347. ini_set('magic_quotes_runtime', $magic_quotes);
  1348. }
  1349. }
  1350. return $file_buffer;
  1351. } catch (Exception $e) {
  1352. $this->SetError($e->getMessage());
  1353. return '';
  1354. }
  1355. }
  1356. /**
  1357. * Encodes string to requested format.
  1358. * Returns an empty string on failure.
  1359. * @param string $str The text to encode
  1360. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  1361. * @access public
  1362. * @return string
  1363. */
  1364. public function EncodeString ($str, $encoding = 'base64') {
  1365. $encoded = '';
  1366. switch(strtolower($encoding)) {
  1367. case 'base64':
  1368. $encoded = chunk_split(base64_encode($str), 76, $this->LE);
  1369. break;
  1370. case '7bit':
  1371. case '8bit':
  1372. $encoded = $this->FixEOL($str);
  1373. //Make sure it ends with a line break
  1374. if (substr($encoded, -(strlen($this->LE))) != $this->LE)
  1375. $encoded .= $this->LE;
  1376. break;
  1377. case 'binary':
  1378. $encoded = $str;
  1379. break;
  1380. case 'quoted-printable':
  1381. $encoded = $this->EncodeQP($str);
  1382. break;
  1383. default:
  1384. $this->SetError($this->Lang('encoding') . $encoding);
  1385. break;
  1386. }
  1387. return $encoded;
  1388. }
  1389. /**
  1390. * Encode a header string to best (shortest) of Q, B, quoted or none.
  1391. * @access public
  1392. * @return string
  1393. */
  1394. public function EncodeHeader($str, $position = 'text') {
  1395. $x = 0;
  1396. switch (strtolower($position)) {
  1397. case 'phrase':
  1398. if (!preg_match('/[\200-\377]/', $str)) {
  1399. // Can't use addslashes as we don't know what value has magic_quotes_sybase
  1400. $encoded = addcslashes($str, "\0..\37\177\\\"");
  1401. if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
  1402. return ($encoded);
  1403. } else {
  1404. return ("\"$encoded\"");
  1405. }
  1406. }
  1407. $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
  1408. break;
  1409. case 'comment':
  1410. $x = preg_match_all('/[()"]/', $str, $matches);
  1411. // Fall-through
  1412. case 'text':
  1413. default:
  1414. $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
  1415. break;
  1416. }
  1417. if ($x == 0) {
  1418. return ($str);
  1419. }
  1420. $maxlen = 75 - 7 - strlen($this->CharSet);
  1421. // Try to select the encoding which should produce the shortest output
  1422. if (strlen($str)/3 < $x) {
  1423. $encoding = 'B';
  1424. // Modified by Ivan Tcholakov, 24-JAN-2010.
  1425. //if (function_exists('mb_strlen') && $this->HasMultiBytes($str)) {
  1426. if ($this->HasMultiBytes($str)) {
  1427. //
  1428. // Use a custom function which correctly encodes and wraps long
  1429. // multibyte strings without breaking lines within a character
  1430. $encoded = $this->Base64EncodeWrapMB($str);
  1431. } else {
  1432. $encoded = base64_encode($str);
  1433. $maxlen -= $maxlen % 4;
  1434. $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
  1435. }
  1436. } else {
  1437. $encoding = 'Q';
  1438. $encoded = $this->EncodeQ($str, $position);
  1439. $encoded = $this->WrapText($encoded, $maxlen, true);
  1440. $encoded = str_replace('='.$this->LE, "\n", trim($encoded));
  1441. }
  1442. $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded);
  1443. $encoded = trim(str_replace("\n", $this->LE, $encoded));
  1444. return $encoded;
  1445. }
  1446. /**
  1447. * Checks if a string contains multibyte characters.
  1448. * @access public
  1449. * @param string $str multi-byte text to wrap encode
  1450. * @return bool
  1451. */
  1452. public function HasMultiBytes($str) {
  1453. // Modified by Ivan Tcholakov, 24-JAN-2010.
  1454. // (function_exists('mb_strlen')) {
  1455. // return (strlen($str) > mb_strlen($str, $this->CharSet));
  1456. //} else { // Assume no multibytes (we can't handle without mbstring functions anyway)
  1457. // return false;
  1458. //}
  1459. return (api_byte_count($str) > api_strlen($str, $this->CharSet));
  1460. //
  1461. }
  1462. /**
  1463. * Correctly encodes and wraps long multibyte strings for mail headers
  1464. * without breaking lines within a character.
  1465. * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php
  1466. * @access public
  1467. * @param string $str multi-byte text to wrap encode
  1468. * @return string
  1469. */
  1470. public function Base64EncodeWrapMB($str) {
  1471. $start = "=?".$this->CharSet."?B?";
  1472. $end = "?=";
  1473. $encoded = "";
  1474. // Modified by Ivan Tcholakov, 24-JAN-2010.
  1475. //$mb_length = mb_strlen($str, $this->CharSet);
  1476. $mb_length = api_strlen($str, $this->CharSet);
  1477. //
  1478. // Each line must have length <= 75, including $start and $end
  1479. $length = 75 - strlen($start) - strlen($end);
  1480. // Average multi-byte ratio
  1481. $ratio = $mb_length / strlen($str);
  1482. // Base64 has a 4:3 ratio
  1483. $offset = $avgLength = floor($length * $ratio * .75);
  1484. for ($i = 0; $i < $mb_length; $i += $offset) {
  1485. $lookBack = 0;
  1486. do {
  1487. $offset = $avgLength - $lookBack;
  1488. // Modified by Ivan Tcholakov, 24-JAN-2010.
  1489. //$chunk = mb_substr($str, $i, $offset, $this->CharSet);
  1490. $chunk = api_substr($str, $i, $offset, $this->CharSet);
  1491. //
  1492. $chunk = base64_encode($chunk);
  1493. $lookBack++;
  1494. }
  1495. while (strlen($chunk) > $length);
  1496. $encoded .= $chunk . $this->LE;
  1497. }
  1498. // Chomp the last linefeed
  1499. $encoded = substr($encoded, 0, -strlen($this->LE));
  1500. return $encoded;
  1501. }
  1502. /**
  1503. * Encode string to quoted-printable.
  1504. * Only uses standard PHP, slow, but will always work
  1505. * @access public
  1506. * @param string $string the text to encode
  1507. * @param integer $line_max Number of chars allowed on a line before wrapping
  1508. * @return string
  1509. */
  1510. public function EncodeQPphp( $input = '', $line_max = 76, $space_conv = false) {
  1511. $hex = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
  1512. $lines = preg_split('/(?:\r\n|\r|\n)/', $input);
  1513. $eol = "\r\n";
  1514. $escape = '=';
  1515. $output = '';
  1516. while( list(, $line) = each($lines) ) {
  1517. $linlen = strlen($line);
  1518. $newline = '';
  1519. for($i = 0; $i < $linlen; $i++) {
  1520. $c = substr( $line, $i, 1 );
  1521. $dec = ord( $c );
  1522. if ( ( $i == 0 ) && ( $dec == 46 ) ) { // convert first point in the line into =2E
  1523. $c = '=2E';
  1524. }
  1525. if ( $dec == 32 ) {
  1526. if ( $i == ( $linlen - 1 ) ) { // convert space at eol only
  1527. $c = '=20';
  1528. } else if ( $space_conv ) {
  1529. $c = '=20';
  1530. }
  1531. } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) { // always encode "\t", which is *not* required
  1532. $h2 = floor($dec/16);
  1533. $h1 = floor($dec%16);
  1534. $c = $escape.$hex[$h2].$hex[$h1];
  1535. }
  1536. if ( (strlen($newline) + strlen($c)) >= $line_max ) { // CRLF is not counted
  1537. $output .= $newline.$escape.$eol; // soft line break; " =\r\n" is okay
  1538. $newline = '';
  1539. // check if newline first character will be point or not
  1540. if ( $dec == 46 ) {
  1541. $c = '=2E';
  1542. }
  1543. }
  1544. $newline .= $c;
  1545. } // end of for
  1546. $output .= $newline.$eol;
  1547. } // end of while
  1548. return $output;
  1549. }
  1550. /**
  1551. * Encode string to RFC2045 (6.7) quoted-printable format
  1552. * Uses a PHP5 stream filter to do the encoding about 64x faster than the old version
  1553. * Also results in same content as you started with after decoding
  1554. * @see EncodeQPphp()
  1555. * @access public
  1556. * @param string $string the text to encode
  1557. * @param integer $line_max Number of chars allowed on a line before wrapping
  1558. * @param boolean $space_conv Dummy param for compatibility with existing EncodeQP function
  1559. * @return string
  1560. * @author Marcus Bointon
  1561. */
  1562. public function EncodeQP($string, $line_max = 76, $space_conv = false) {
  1563. if (function_exists('quoted_printable_encode')) { //Use native function if it's available (>= PHP5.3)
  1564. return quoted_printable_encode($string);
  1565. }
  1566. $filters = stream_get_filters();
  1567. if (!in_array('convert.*', $filters)) { //Got convert stream filter?
  1568. return $this->EncodeQPphp($string, $line_max, $space_conv); //Fall back to old implementation
  1569. }
  1570. $fp = fopen('php://temp/', 'r+');
  1571. $string = preg_replace('/\r\n?/', $this->LE, $string); //Normalise line breaks
  1572. $params = array('line-length' => $line_max, 'line-break-chars' => $this->LE);
  1573. $s = stream_filter_append($fp, 'convert.quoted-printable-encode', STREAM_FILTER_READ, $params);
  1574. fputs($fp, $string);
  1575. rewind($fp);
  1576. $out = stream_get_contents($fp);
  1577. stream_filter_remove($s);
  1578. $out = preg_replace('/^\./m', '=2E', $out); //Encode . if it is first char on a line, workaround for bug in Exchange
  1579. fclose($fp);
  1580. return $out;
  1581. }
  1582. /**
  1583. * Encode string to q encoding.
  1584. * @link http://tools.ietf.org/html/rfc2047
  1585. * @param string $str the text to encode
  1586. * @param string $position Where the text is going to be used, see the RFC for what that means
  1587. * @access public
  1588. * @return string
  1589. */
  1590. public function EncodeQ ($str, $position = 'text') {
  1591. // There should not be any EOL in the string
  1592. $encoded = preg_replace('/[\r\n]*/', '', $str);
  1593. switch (strtolower($position)) {
  1594. case 'phrase':
  1595. $encoded = preg_replace("/([^A-Za-z0-9!*+\/ -])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
  1596. break;
  1597. case 'comment':
  1598. $encoded = preg_replace("/([\(\)\"])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
  1599. case 'text':
  1600. default:
  1601. // Replace every high ascii, control =, ? and _ characters
  1602. //TODO using /e (equivalent to eval()) is probably not a good idea
  1603. $encoded = preg_replace('/([\000-\011\013\014\016-\037\075\077\137\177-\377])/e',
  1604. "'='.sprintf('%02X', ord('\\1'))", $encoded);
  1605. break;
  1606. }
  1607. // Replace every spaces to _ (more readable than =20)
  1608. $encoded = str_replace(' ', '_', $encoded);
  1609. return $encoded;
  1610. }
  1611. /**
  1612. * Adds a string or binary attachment (non-filesystem) to the list.
  1613. * This method can be used to attach ascii or binary data,
  1614. * such as a BLOB record from a database.
  1615. * @param string $string String attachment data.
  1616. * @param string $filename Name of the attachment.
  1617. * @param string $encoding File encoding (see $Encoding).
  1618. * @param string $type File extension (MIME) type.
  1619. * @return void
  1620. */
  1621. public function AddStringAttachment($string, $filename, $encoding = 'base64', $type = 'application/octet-stream') {
  1622. // Append to $attachment array
  1623. $this->attachment[] = array(
  1624. 0 => $string,
  1625. 1 => $filename,
  1626. 2 => basename($filename),
  1627. 3 => $encoding,
  1628. 4 => $type,
  1629. 5 => true, // isStringAttachment
  1630. 6 => 'attachment',
  1631. 7 => 0
  1632. );
  1633. }
  1634. /**
  1635. * Adds an embedded attachment. This can include images, sounds, and
  1636. * just about any other document. Make sure to set the $type to an
  1637. * image type. For JPEG images use "image/jpeg" and for GIF images
  1638. * use "image/gif".
  1639. * @param string $path Path to the attachment.
  1640. * @param string $cid Content ID of the attachment. Use this to identify
  1641. * the Id for accessing the image in an HTML form.
  1642. * @param string $name Overrides the attachment name.
  1643. * @param string $encoding File encoding (see $Encoding).
  1644. * @param string $type File extension (MIME) type.
  1645. * @return bool
  1646. */
  1647. public function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
  1648. if ( !@is_file($path) ) {
  1649. $this->SetError($this->Lang('file_access') . $path);
  1650. return false;
  1651. }
  1652. $filename = basename($path);
  1653. if ( $name == '' ) {
  1654. $name = $filename;
  1655. }
  1656. // Append to $attachment array
  1657. $this->attachment[] = array(
  1658. 0 => $path,
  1659. 1 => $filename,
  1660. 2 => $name,
  1661. 3 => $encoding,
  1662. 4 => $type,
  1663. 5 => false, // isStringAttachment
  1664. 6 => 'inline',
  1665. 7 => $cid
  1666. );
  1667. return true;
  1668. }
  1669. /**
  1670. * Returns true if an inline attachment is present.
  1671. * @access public
  1672. * @return bool
  1673. */
  1674. public function InlineImageExists() {
  1675. foreach($this->attachment as $attachment) {
  1676. if ($attachment[6] == 'inline') {
  1677. return true;
  1678. }
  1679. }
  1680. return false;
  1681. }
  1682. /////////////////////////////////////////////////
  1683. // CLASS METHODS, MESSAGE RESET
  1684. /////////////////////////////////////////////////
  1685. /**
  1686. * Clears all recipients assigned in the TO array. Returns void.
  1687. * @return void
  1688. */
  1689. public function ClearAddresses() {
  1690. foreach($this->to as $to) {
  1691. unset($this->all_recipients[strtolower($to[0])]);
  1692. }
  1693. $this->to = array();
  1694. }
  1695. /**
  1696. * Clears all recipients assigned in the CC array. Returns void.
  1697. * @return void
  1698. */
  1699. public function ClearCCs() {
  1700. foreach($this->cc as $cc) {
  1701. unset($this->all_recipients[strtolower($cc[0])]);
  1702. }
  1703. $this->cc = array();
  1704. }
  1705. /**
  1706. * Clears all recipients assigned in the BCC array. Returns void.
  1707. * @return void
  1708. */
  1709. public function ClearBCCs() {
  1710. foreach($this->bcc as $bcc) {
  1711. unset($this->all_recipients[strtolower($bcc[0])]);
  1712. }
  1713. $this->bcc = array();
  1714. }
  1715. /**
  1716. * Clears all recipients assigned in the ReplyTo array. Returns void.
  1717. * @return void
  1718. */
  1719. public function ClearReplyTos() {
  1720. $this->ReplyTo = array();
  1721. }
  1722. /**
  1723. * Clears all recipients assigned in the TO, CC and BCC
  1724. * array. Returns void.
  1725. * @return void
  1726. */
  1727. public function ClearAllRecipients() {
  1728. $this->to = array();
  1729. $this->cc = array();
  1730. $this->bcc = array();
  1731. $this->all_recipients = array();
  1732. }
  1733. /**
  1734. * Clears all previously set filesystem, string, and binary
  1735. * attachments. Returns void.
  1736. * @return void
  1737. */
  1738. public function ClearAttachments() {
  1739. $this->attachment = array();
  1740. }
  1741. /**
  1742. * Clears all custom headers. Returns void.
  1743. * @return void
  1744. */
  1745. public function ClearCustomHeaders() {
  1746. $this->CustomHeader = array();
  1747. }
  1748. /////////////////////////////////////////////////
  1749. // CLASS METHODS, MISCELLANEOUS
  1750. /////////////////////////////////////////////////
  1751. /**
  1752. * Adds the error message to the error container.
  1753. * @access protected
  1754. * @return void
  1755. */
  1756. protected function SetError($msg) {
  1757. $this->error_count++;
  1758. if ($this->Mailer == 'smtp' and !is_null($this->smtp)) {
  1759. $lasterror = $this->smtp->getError();
  1760. if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) {
  1761. $msg .= '<p>' . $this->Lang('smtp_error') . $lasterror['smtp_msg'] . "</p>\n";
  1762. }
  1763. }
  1764. $this->ErrorInfo = $msg;
  1765. }
  1766. /**
  1767. * Returns the proper RFC 822 formatted date.
  1768. * @access public
  1769. * @return string
  1770. * @static
  1771. */
  1772. public static function RFCDate() {
  1773. $tz = date('Z');
  1774. $tzs = ($tz < 0) ? '-' : '+';
  1775. $tz = abs($tz);
  1776. $tz = (int)($tz/3600)*100 + ($tz%3600)/60;
  1777. $result = sprintf("%s %s%04d", date('D, j M Y H:i:s'), $tzs, $tz);
  1778. return $result;
  1779. }
  1780. /**
  1781. * Returns the server hostname or 'localhost.localdomain' if unknown.
  1782. * @access private
  1783. * @return string
  1784. */
  1785. private function ServerHostname() {
  1786. if (!empty($this->Hostname)) {
  1787. $result = $this->Hostname;
  1788. } elseif (isset($_SERVER['SERVER_NAME'])) {
  1789. $result = $_SERVER['SERVER_NAME'];
  1790. } else {
  1791. $result = 'localhost.localdomain';
  1792. }
  1793. return $result;
  1794. }
  1795. /**
  1796. * Returns a message in the appropriate language.
  1797. * @access private
  1798. * @return string
  1799. */
  1800. private function Lang($key) {
  1801. if(count($this->language) < 1) {
  1802. $this->SetLanguage('en'); // set the default language
  1803. }
  1804. if(isset($this->language[$key])) {
  1805. return $this->language[$key];
  1806. } else {
  1807. return 'Language string failed to load: ' . $key;
  1808. }
  1809. }
  1810. /**
  1811. * Returns true if an error occurred.
  1812. * @access public
  1813. * @return bool
  1814. */
  1815. public function IsError() {
  1816. return ($this->error_count > 0);
  1817. }
  1818. /**
  1819. * Changes every end of line from CR or LF to CRLF.
  1820. * @access private
  1821. * @return string
  1822. */
  1823. private function FixEOL($str) {
  1824. $str = str_replace("\r\n", "\n", $str);
  1825. $str = str_replace("\r", "\n", $str);
  1826. $str = str_replace("\n", $this->LE, $str);
  1827. return $str;
  1828. }
  1829. /**
  1830. * Adds a custom header.
  1831. * @access public
  1832. * @return void
  1833. */
  1834. public function AddCustomHeader($custom_header) {
  1835. $this->CustomHeader[] = explode(':', $custom_header, 2);
  1836. }
  1837. /**
  1838. * Evaluates the message and returns modifications for inline images and backgrounds
  1839. * @access public
  1840. * @return $message
  1841. */
  1842. public function MsgHTML($message, $basedir = '') {
  1843. preg_match_all("/(src|background)=\"(.*)\"/Ui", $message, $images);
  1844. if(isset($images[2])) {
  1845. foreach($images[2] as $i => $url) {
  1846. // do not change urls for absolute images (thanks to corvuscorax)
  1847. if (!preg_match('#^[A-z]+://#',$url)) {
  1848. $filename = basename($url);
  1849. $directory = dirname($url);
  1850. ($directory == '.')?$directory='':'';
  1851. $cid = 'cid:' . md5($filename);
  1852. $ext = pathinfo($filename, PATHINFO_EXTENSION);
  1853. $mimeType = self::_mime_types($ext);
  1854. if ( strlen($basedir) > 1 && substr($basedir,-1) != '/') { $basedir .= '/'; }
  1855. if ( strlen($directory) > 1 && substr($directory,-1) != '/') { $directory .= '/'; }
  1856. if ( $this->AddEmbeddedImage($basedir.$directory.$filename, md5($filename), $filename, 'base64',$mimeType) ) {
  1857. $message = preg_replace("/".$images[1][$i]."=\"".preg_quote($url, '/')."\"/Ui", $images[1][$i]."=\"".$cid."\"", $message);
  1858. }
  1859. }
  1860. }
  1861. }
  1862. $this->IsHTML(true);
  1863. $this->Body = $message;
  1864. $textMsg = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s','',$message)));
  1865. if (!empty($textMsg) && empty($this->AltBody)) {
  1866. $this->AltBody = html_entity_decode($textMsg);
  1867. }
  1868. if (empty($this->AltBody)) {
  1869. $this->AltBody = 'To view this email message, open it in a program that understands HTML!' . "\n\n";
  1870. }
  1871. }
  1872. /**
  1873. * Gets the MIME type of the embedded or inline image
  1874. * @param string File extension
  1875. * @access public
  1876. * @return string MIME type of ext
  1877. * @static
  1878. */
  1879. public static function _mime_types($ext = '') {
  1880. $mimes = array(
  1881. 'hqx' => 'application/mac-binhex40',
  1882. 'cpt' => 'application/mac-compactpro',
  1883. 'doc' => 'application/msword',
  1884. 'bin' => 'application/macbinary',
  1885. 'dms' => 'application/octet-stream',
  1886. 'lha' => 'application/octet-stream',
  1887. 'lzh' => 'application/octet-stream',
  1888. 'exe' => 'application/octet-stream',
  1889. 'class' => 'application/octet-stream',
  1890. 'psd' => 'application/octet-stream',
  1891. 'so' => 'application/octet-stream',
  1892. 'sea' => 'application/octet-stream',
  1893. 'dll' => 'application/octet-stream',
  1894. 'oda' => 'application/oda',
  1895. 'pdf' => 'application/pdf',
  1896. 'ai' => 'application/postscript',
  1897. 'eps' => 'application/postscript',
  1898. 'ps' => 'application/postscript',
  1899. 'smi' => 'application/smil',
  1900. 'smil' => 'application/smil',
  1901. 'mif' => 'application/vnd.mif',
  1902. 'xls' => 'application/vnd.ms-excel',
  1903. 'ppt' => 'application/vnd.ms-powerpoint',
  1904. 'wbxml' => 'application/vnd.wap.wbxml',
  1905. 'wmlc' => 'application/vnd.wap.wmlc',
  1906. 'dcr' => 'application/x-director',
  1907. 'dir' => 'application/x-director',
  1908. 'dxr' => 'application/x-director',
  1909. 'dvi' => 'application/x-dvi',
  1910. 'gtar' => 'application/x-gtar',
  1911. 'php' => 'application/x-httpd-php',
  1912. 'php4' => 'application/x-httpd-php',
  1913. 'php3' => 'application/x-httpd-php',
  1914. 'phtml' => 'application/x-httpd-php',
  1915. 'phps' => 'application/x-httpd-php-source',
  1916. 'js' => 'application/x-javascript',
  1917. 'swf' => 'application/x-shockwave-flash',
  1918. 'sit' => 'application/x-stuffit',
  1919. 'tar' => 'application/x-tar',
  1920. 'tgz' => 'application/x-tar',
  1921. 'xhtml' => 'application/xhtml+xml',
  1922. 'xht' => 'application/xhtml+xml',
  1923. 'zip' => 'application/zip',
  1924. 'mid' => 'audio/midi',
  1925. 'midi' => 'audio/midi',
  1926. 'mpga' => 'audio/mpeg',
  1927. 'mp2' => 'audio/mpeg',
  1928. 'mp3' => 'audio/mpeg',
  1929. 'aif' => 'audio/x-aiff',
  1930. 'aiff' => 'audio/x-aiff',
  1931. 'aifc' => 'audio/x-aiff',
  1932. 'ram' => 'audio/x-pn-realaudio',
  1933. 'rm' => 'audio/x-pn-realaudio',
  1934. 'rpm' => 'audio/x-pn-realaudio-plugin',
  1935. 'ra' => 'audio/x-realaudio',
  1936. 'rv' => 'video/vnd.rn-realvideo',
  1937. 'wav' => 'audio/x-wav',
  1938. 'bmp' => 'image/bmp',
  1939. 'gif' => 'image/gif',
  1940. 'jpeg' => 'image/jpeg',
  1941. 'jpg' => 'image/jpeg',
  1942. 'jpe' => 'image/jpeg',
  1943. 'png' => 'image/png',
  1944. 'tiff' => 'image/tiff',
  1945. 'tif' => 'image/tiff',
  1946. 'css' => 'text/css',
  1947. 'html' => 'text/html',
  1948. 'htm' => 'text/html',
  1949. 'shtml' => 'text/html',
  1950. 'txt' => 'text/plain',
  1951. 'text' => 'text/plain',
  1952. 'log' => 'text/plain',
  1953. 'rtx' => 'text/richtext',
  1954. 'rtf' => 'text/rtf',
  1955. 'xml' => 'text/xml',
  1956. 'xsl' => 'text/xml',
  1957. 'mpeg' => 'video/mpeg',
  1958. 'mpg' => 'video/mpeg',
  1959. 'mpe' => 'video/mpeg',
  1960. 'qt' => 'video/quicktime',
  1961. 'mov' => 'video/quicktime',
  1962. 'avi' => 'video/x-msvideo',
  1963. 'movie' => 'video/x-sgi-movie',
  1964. 'doc' => 'application/msword',
  1965. 'word' => 'application/msword',
  1966. 'xl' => 'application/excel',
  1967. 'eml' => 'message/rfc822'
  1968. );
  1969. return (!isset($mimes[strtolower($ext)])) ? 'application/octet-stream' : $mimes[strtolower($ext)];
  1970. }
  1971. /**
  1972. * Set (or reset) Class Objects (variables)
  1973. *
  1974. * Usage Example:
  1975. * $page->set('X-Priority', '3');
  1976. *
  1977. * @access public
  1978. * @param string $name Parameter Name
  1979. * @param mixed $value Parameter Value
  1980. * NOTE: will not work with arrays, there are no arrays to set/reset
  1981. * @todo Should this not be using __set() magic function?
  1982. */
  1983. public function set($name, $value = '') {
  1984. try {
  1985. if (isset($this->$name) ) {
  1986. $this->$name = $value;
  1987. } else {
  1988. throw new phpmailerException($this->Lang('variable_set') . $name, self::STOP_CRITICAL);
  1989. }
  1990. } catch (Exception $e) {
  1991. $this->SetError($e->getMessage());
  1992. if ($e->getCode() == self::STOP_CRITICAL) {
  1993. return false;
  1994. }
  1995. }
  1996. return true;
  1997. }
  1998. /**
  1999. * Strips newlines to prevent header injection.
  2000. * @access public
  2001. * @param string $str String
  2002. * @return string
  2003. */
  2004. public function SecureHeader($str) {
  2005. $str = str_replace("\r", '', $str);
  2006. $str = str_replace("\n", '', $str);
  2007. return trim($str);
  2008. }
  2009. /**
  2010. * Set the private key file and password to sign the message.
  2011. *
  2012. * @access public
  2013. * @param string $key_filename Parameter File Name
  2014. * @param string $key_pass Password for private key
  2015. */
  2016. public function Sign($cert_filename, $key_filename, $key_pass) {
  2017. $this->sign_cert_file = $cert_filename;
  2018. $this->sign_key_file = $key_filename;
  2019. $this->sign_key_pass = $key_pass;
  2020. }
  2021. /**
  2022. * Set the private key file and password to sign the message.
  2023. *
  2024. * @access public
  2025. * @param string $key_filename Parameter File Name
  2026. * @param string $key_pass Password for private key
  2027. */
  2028. public function DKIM_QP($txt) {
  2029. $tmp="";
  2030. $line="";
  2031. for ($i=0;$i<strlen($txt);$i++) {
  2032. $ord=ord($txt[$i]);
  2033. if ( ((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E)) ) {
  2034. $line.=$txt[$i];
  2035. } else {
  2036. $line.="=".sprintf("%02X",$ord);
  2037. }
  2038. }
  2039. return $line;
  2040. }
  2041. /**
  2042. * Generate DKIM signature
  2043. *
  2044. * @access public
  2045. * @param string $s Header
  2046. */
  2047. public function DKIM_Sign($s) {
  2048. $privKeyStr = file_get_contents($this->DKIM_private);
  2049. if ($this->DKIM_passphrase!='') {
  2050. $privKey = openssl_pkey_get_private($privKeyStr,$this->DKIM_passphrase);
  2051. } else {
  2052. $privKey = $privKeyStr;
  2053. }
  2054. if (openssl_sign($s, $signature, $privKey)) {
  2055. return base64_encode($signature);
  2056. }
  2057. }
  2058. /**
  2059. * Generate DKIM Canonicalization Header
  2060. *
  2061. * @access public
  2062. * @param string $s Header
  2063. */
  2064. public function DKIM_HeaderC($s) {
  2065. $s=preg_replace("/\r\n\s+/"," ",$s);
  2066. $lines=explode("\r\n",$s);
  2067. foreach ($lines as $key=>$line) {
  2068. list($heading,$value)=explode(":",$line,2);
  2069. $heading=strtolower($heading);
  2070. $value=preg_replace("/\s+/"," ",$value) ; // Compress useless spaces
  2071. $lines[$key]=$heading.":".trim($value) ; // Don't forget to remove WSP around the value
  2072. }
  2073. $s=implode("\r\n",$lines);
  2074. return $s;
  2075. }
  2076. /**
  2077. * Generate DKIM Canonicalization Body
  2078. *
  2079. * @access public
  2080. * @param string $body Message Body
  2081. */
  2082. public function DKIM_BodyC($body) {
  2083. if ($body == '') return "\r\n";
  2084. // stabilize line endings
  2085. $body=str_replace("\r\n","\n",$body);
  2086. $body=str_replace("\n","\r\n",$body);
  2087. // END stabilize line endings
  2088. while (substr($body,strlen($body)-4,4) == "\r\n\r\n") {
  2089. $body=substr($body,0,strlen($body)-2);
  2090. }
  2091. return $body;
  2092. }
  2093. /**
  2094. * Create the DKIM header, body, as new header
  2095. *
  2096. * @access public
  2097. * @param string $headers_line Header lines
  2098. * @param string $subject Subject
  2099. * @param string $body Body
  2100. */
  2101. public function DKIM_Add($headers_line,$subject,$body) {
  2102. $DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms
  2103. $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
  2104. $DKIMquery = 'dns/txt'; // Query method
  2105. $DKIMtime = time() ; // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
  2106. $subject_header = "Subject: $subject";
  2107. $headers = explode("\r\n",$headers_line);
  2108. foreach($headers as $header) {
  2109. if (strpos($header,'From:') === 0) {
  2110. $from_header=$header;
  2111. } elseif (strpos($header,'To:') === 0) {
  2112. $to_header=$header;
  2113. }
  2114. }
  2115. $from = str_replace('|','=7C',$this->DKIM_QP($from_header));
  2116. $to = str_replace('|','=7C',$this->DKIM_QP($to_header));
  2117. $subject = str_replace('|','=7C',$this->DKIM_QP($subject_header)) ; // Copied header fields (dkim-quoted-printable
  2118. $body = $this->DKIM_BodyC($body);
  2119. $DKIMlen = strlen($body) ; // Length of body
  2120. $DKIMb64 = base64_encode(pack("H*", sha1($body))) ; // Base64 of packed binary SHA-1 hash of body
  2121. $ident = ($this->DKIM_identity == '')? '' : " i=" . $this->DKIM_identity . ";";
  2122. $dkimhdrs = "DKIM-Signature: v=1; a=" . $DKIMsignatureType . "; q=" . $DKIMquery . "; l=" . $DKIMlen . "; s=" . $this->DKIM_selector . ";\r\n".
  2123. "\tt=" . $DKIMtime . "; c=" . $DKIMcanonicalization . ";\r\n".
  2124. "\th=From:To:Subject;\r\n".
  2125. "\td=" . $this->DKIM_domain . ";" . $ident . "\r\n".
  2126. "\tz=$from\r\n".
  2127. "\t|$to\r\n".
  2128. "\t|$subject;\r\n".
  2129. "\tbh=" . $DKIMb64 . ";\r\n".
  2130. "\tb=";
  2131. $toSign = $this->DKIM_HeaderC($from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs);
  2132. $signed = $this->DKIM_Sign($toSign);
  2133. return "X-PHPMAILER-DKIM: phpmailer.worxware.com\r\n".$dkimhdrs.$signed."\r\n";
  2134. }
  2135. protected function doCallback($isSent,$to,$cc,$bcc,$subject,$body) {
  2136. if (!empty($this->action_function) && function_exists($this->action_function)) {
  2137. $params = array($isSent,$to,$cc,$bcc,$subject,$body);
  2138. call_user_func_array($this->action_function,$params);
  2139. }
  2140. }
  2141. }
  2142. class phpmailerException extends Exception {
  2143. public function errorMessage() {
  2144. $errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n";
  2145. return $errorMsg;
  2146. }
  2147. }
  2148. ?>