smtp.phpmailer.inc 72 KB

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