class.phpmailer.php 82 KB

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