smtp.phpmailer.inc 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347
  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. $pattern = '';
  1581. $encoded = str_replace(array("\r", "\n"), '', $str);
  1582. switch (strtolower($position)) {
  1583. case 'phrase':
  1584. // RFC 2047 section 5.3
  1585. $pattern = '^A-Za-z0-9!*+\/ -';
  1586. break;
  1587. /** @noinspection PhpMissingBreakStatementInspection */
  1588. case 'comment':
  1589. // RFC 2047 section 5.2
  1590. $pattern = '\(\)"';
  1591. // intentional fall-through
  1592. // for this reason we build the $pattern without including delimiters and []
  1593. case 'text':
  1594. default:
  1595. // RFC 2047 section 5.1
  1596. // Replace every high ascii, control, =, ? and _ characters
  1597. $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern;
  1598. break;
  1599. }
  1600. $matches = array();
  1601. if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
  1602. // If the string contains an '=', make sure it's the first thing we replace
  1603. // so as to avoid double-encoding
  1604. $s = array_search('=', $matches[0]);
  1605. if ($s !== false) {
  1606. unset($matches[0][$s]);
  1607. array_unshift($matches[0], '=');
  1608. }
  1609. foreach (array_unique($matches[0]) as $char) {
  1610. $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
  1611. }
  1612. }
  1613. // Replace every spaces to _ (more readable than =20)
  1614. return str_replace(' ', '_', $encoded);
  1615. }
  1616. /**
  1617. * Adds a string or binary attachment (non-filesystem) to the list.
  1618. * This method can be used to attach ascii or binary data,
  1619. * such as a BLOB record from a database.
  1620. * @param string $string String attachment data.
  1621. * @param string $filename Name of the attachment.
  1622. * @param string $encoding File encoding (see $Encoding).
  1623. * @param string $type File extension (MIME) type.
  1624. * @return void
  1625. */
  1626. public function AddStringAttachment($string, $filename, $encoding = 'base64', $type = 'application/octet-stream') {
  1627. // Append to $attachment array
  1628. $this->attachment[] = array(
  1629. 0 => $string,
  1630. 1 => $filename,
  1631. 2 => basename($filename),
  1632. 3 => $encoding,
  1633. 4 => $type,
  1634. 5 => TRUE, // isStringAttachment
  1635. 6 => 'attachment',
  1636. 7 => 0
  1637. );
  1638. }
  1639. /**
  1640. * Adds an embedded attachment. This can include images, sounds, and
  1641. * just about any other document. Make sure to set the $type to an
  1642. * image type. For JPEG images use "image/jpeg" and for GIF images
  1643. * use "image/gif".
  1644. * @param string $path Path to the attachment.
  1645. * @param string $cid Content ID of the attachment. Use this to identify
  1646. * the Id for accessing the image in an HTML form.
  1647. * @param string $name Overrides the attachment name.
  1648. * @param string $encoding File encoding (see $Encoding).
  1649. * @param string $type File extension (MIME) type.
  1650. * @return bool
  1651. */
  1652. public function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
  1653. if ( !@is_file($path) ) {
  1654. $this->SetError(t('Could not access file: !nofile', array('!nofile' => $path)));
  1655. return FALSE;
  1656. }
  1657. $filename = basename($path);
  1658. if ( $name == '' ) {
  1659. $name = $filename;
  1660. }
  1661. // Append to $attachment array
  1662. $this->attachment[] = array(
  1663. 0 => $path,
  1664. 1 => $filename,
  1665. 2 => $name,
  1666. 3 => $encoding,
  1667. 4 => $type,
  1668. 5 => FALSE, // isStringAttachment
  1669. 6 => 'inline',
  1670. 7 => $cid
  1671. );
  1672. return TRUE;
  1673. }
  1674. /**
  1675. * Returns TRUE if an inline attachment is present.
  1676. * @access public
  1677. * @return bool
  1678. */
  1679. public function InlineImageExists() {
  1680. foreach ($this->attachment as $attachment) {
  1681. if ($attachment[6] == 'inline') {
  1682. return TRUE;
  1683. }
  1684. }
  1685. return FALSE;
  1686. }
  1687. /////////////////////////////////////////////////
  1688. // CLASS METHODS, MESSAGE RESET
  1689. /////////////////////////////////////////////////
  1690. /**
  1691. * Clears all recipients assigned in the TO array. Returns void.
  1692. * @return void
  1693. */
  1694. public function ClearAddresses() {
  1695. foreach ($this->to as $to) {
  1696. unset($this->all_recipients[strtolower($to[0])]);
  1697. }
  1698. $this->to = array();
  1699. }
  1700. /**
  1701. * Clears all recipients assigned in the CC array. Returns void.
  1702. * @return void
  1703. */
  1704. public function ClearCCs() {
  1705. foreach ($this->cc as $cc) {
  1706. unset($this->all_recipients[strtolower($cc[0])]);
  1707. }
  1708. $this->cc = array();
  1709. }
  1710. /**
  1711. * Clears all recipients assigned in the BCC array. Returns void.
  1712. * @return void
  1713. */
  1714. public function ClearBCCs() {
  1715. foreach ($this->bcc as $bcc) {
  1716. unset($this->all_recipients[strtolower($bcc[0])]);
  1717. }
  1718. $this->bcc = array();
  1719. }
  1720. /**
  1721. * Clears all recipients assigned in the ReplyTo array. Returns void.
  1722. * @return void
  1723. */
  1724. public function ClearReplyTos() {
  1725. $this->ReplyTo = array();
  1726. }
  1727. /**
  1728. * Clears all recipients assigned in the TO, CC and BCC
  1729. * array. Returns void.
  1730. * @return void
  1731. */
  1732. public function ClearAllRecipients() {
  1733. $this->to = array();
  1734. $this->cc = array();
  1735. $this->bcc = array();
  1736. $this->all_recipients = array();
  1737. }
  1738. /**
  1739. * Clears all previously set filesystem, string, and binary
  1740. * attachments. Returns void.
  1741. * @return void
  1742. */
  1743. public function ClearAttachments() {
  1744. $this->attachment = array();
  1745. }
  1746. /**
  1747. * Clears all custom headers. Returns void.
  1748. * @return void
  1749. */
  1750. public function ClearCustomHeaders() {
  1751. $this->CustomHeader = array();
  1752. }
  1753. /////////////////////////////////////////////////
  1754. // CLASS METHODS, MISCELLANEOUS
  1755. /////////////////////////////////////////////////
  1756. /**
  1757. * Adds the error message to the error container.
  1758. * @access protected
  1759. * @return void
  1760. */
  1761. protected function SetError($msg) {
  1762. $this->error_count++;
  1763. if ($this->Mailer == 'smtp' and !is_null($this->smtp)) {
  1764. $lasterror = $this->smtp->getError();
  1765. if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) {
  1766. $msg .= '<p>' . t('SMTP server error: !lasterror', array('!lasterror' => $lasterror['smtp_msg'])) . "</p>\n";
  1767. }
  1768. }
  1769. $this->ErrorInfo = $msg;
  1770. }
  1771. /**
  1772. * Returns the proper RFC 822 formatted date.
  1773. * @access public
  1774. * @return string
  1775. * @static
  1776. */
  1777. public static function RFCDate() {
  1778. $tz = date('Z');
  1779. $tzs = ($tz < 0) ? '-' : '+';
  1780. $tz = abs($tz);
  1781. $tz = (int)($tz/3600)*100 + ($tz%3600)/60;
  1782. $result = sprintf("%s %s%04d", date('D, j M Y H:i:s'), $tzs, $tz);
  1783. return $result;
  1784. }
  1785. /**
  1786. * Returns the server hostname or 'localhost.localdomain' if unknown.
  1787. * @access private
  1788. * @return string
  1789. */
  1790. private function ServerHostname() {
  1791. if (!empty($this->Hostname)) {
  1792. $result = $this->Hostname;
  1793. }
  1794. elseif (isset($_SERVER['SERVER_NAME'])) {
  1795. $result = $_SERVER['SERVER_NAME'];
  1796. }
  1797. else {
  1798. $result = 'localhost.localdomain';
  1799. }
  1800. return $result;
  1801. }
  1802. /**
  1803. * Returns TRUE if an error occurred.
  1804. * @access public
  1805. * @return bool
  1806. */
  1807. public function IsError() {
  1808. return ($this->error_count > 0);
  1809. }
  1810. /**
  1811. * Changes every end of line from CR or LF to CRLF.
  1812. * @access private
  1813. * @return string
  1814. */
  1815. private function FixEOL($str) {
  1816. $str = str_replace("\r\n", "\n", $str);
  1817. $str = str_replace("\r", "\n", $str);
  1818. $str = str_replace("\n", $this->LE, $str);
  1819. return $str;
  1820. }
  1821. /**
  1822. * Adds a custom header.
  1823. * @access public
  1824. * @return void
  1825. */
  1826. public function AddCustomHeader($custom_header) {
  1827. $this->CustomHeader[] = explode(':', $custom_header, 2);
  1828. }
  1829. /**
  1830. * Evaluates the message and returns modifications for inline images and backgrounds
  1831. * @access public
  1832. * @return $message
  1833. */
  1834. public function MsgHTML($message, $basedir = '') {
  1835. preg_match_all("/(src|background)=\"(.*)\"/Ui", $message, $images);
  1836. if (isset($images[2])) {
  1837. foreach ($images[2] as $i => $url) {
  1838. // do not change urls for absolute images (thanks to corvuscorax)
  1839. if (!preg_match('#^[A-z]+://#', $url)) {
  1840. $filename = basename($url);
  1841. $directory = dirname($url);
  1842. ($directory == '.')?$directory='':'';
  1843. $cid = 'cid:' . md5($filename);
  1844. $ext = pathinfo($filename, PATHINFO_EXTENSION);
  1845. $mimeType = self::_mime_types($ext);
  1846. if ( strlen($basedir) > 1 && substr($basedir, -1) != '/') {
  1847. $basedir .= '/';
  1848. }
  1849. if ( strlen($directory) > 1 && substr($directory, -1) != '/') {
  1850. $directory .= '/';
  1851. }
  1852. if ( $this->AddEmbeddedImage($basedir . $directory . $filename, md5($filename), $filename, 'base64', $mimeType) ) {
  1853. $message = preg_replace("/" . $images[1][$i] . "=\"" . preg_quote($url, '/') . "\"/Ui", $images[1][$i] . "=\"" . $cid . "\"", $message);
  1854. }
  1855. }
  1856. }
  1857. }
  1858. $this->IsHTML(TRUE);
  1859. $this->Body = $message;
  1860. $textMsg = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s', '', $message)));
  1861. if (!empty($textMsg) && empty($this->AltBody)) {
  1862. $this->AltBody = html_entity_decode($textMsg);
  1863. }
  1864. if (empty($this->AltBody)) {
  1865. $this->AltBody = 'To view this email message, open it in a program that understands HTML!' . "\n\n";
  1866. }
  1867. }
  1868. /**
  1869. * Gets the MIME type of the embedded or inline image
  1870. * @param string File extension
  1871. * @access public
  1872. * @return string MIME type of ext
  1873. * @static
  1874. */
  1875. public static function _mime_types($ext = '') {
  1876. $mimes = array(
  1877. 'hqx' => 'application/mac-binhex40',
  1878. 'cpt' => 'application/mac-compactpro',
  1879. 'doc' => 'application/msword',
  1880. 'bin' => 'application/macbinary',
  1881. 'dms' => 'application/octet-stream',
  1882. 'lha' => 'application/octet-stream',
  1883. 'lzh' => 'application/octet-stream',
  1884. 'exe' => 'application/octet-stream',
  1885. 'class' => 'application/octet-stream',
  1886. 'psd' => 'application/octet-stream',
  1887. 'so' => 'application/octet-stream',
  1888. 'sea' => 'application/octet-stream',
  1889. 'dll' => 'application/octet-stream',
  1890. 'oda' => 'application/oda',
  1891. 'pdf' => 'application/pdf',
  1892. 'ai' => 'application/postscript',
  1893. 'eps' => 'application/postscript',
  1894. 'ps' => 'application/postscript',
  1895. 'smi' => 'application/smil',
  1896. 'smil' => 'application/smil',
  1897. 'mif' => 'application/vnd.mif',
  1898. 'xls' => 'application/vnd.ms-excel',
  1899. 'ppt' => 'application/vnd.ms-powerpoint',
  1900. 'wbxml' => 'application/vnd.wap.wbxml',
  1901. 'wmlc' => 'application/vnd.wap.wmlc',
  1902. 'dcr' => 'application/x-director',
  1903. 'dir' => 'application/x-director',
  1904. 'dxr' => 'application/x-director',
  1905. 'dvi' => 'application/x-dvi',
  1906. 'gtar' => 'application/x-gtar',
  1907. 'php' => 'application/x-httpd-php',
  1908. 'php4' => 'application/x-httpd-php',
  1909. 'php3' => 'application/x-httpd-php',
  1910. 'phtml' => 'application/x-httpd-php',
  1911. 'phps' => 'application/x-httpd-php-source',
  1912. 'js' => 'application/x-javascript',
  1913. 'swf' => 'application/x-shockwave-flash',
  1914. 'sit' => 'application/x-stuffit',
  1915. 'tar' => 'application/x-tar',
  1916. 'tgz' => 'application/x-tar',
  1917. 'xhtml' => 'application/xhtml+xml',
  1918. 'xht' => 'application/xhtml+xml',
  1919. 'zip' => 'application/zip',
  1920. 'mid' => 'audio/midi',
  1921. 'midi' => 'audio/midi',
  1922. 'mpga' => 'audio/mpeg',
  1923. 'mp2' => 'audio/mpeg',
  1924. 'mp3' => 'audio/mpeg',
  1925. 'aif' => 'audio/x-aiff',
  1926. 'aiff' => 'audio/x-aiff',
  1927. 'aifc' => 'audio/x-aiff',
  1928. 'ram' => 'audio/x-pn-realaudio',
  1929. 'rm' => 'audio/x-pn-realaudio',
  1930. 'rpm' => 'audio/x-pn-realaudio-plugin',
  1931. 'ra' => 'audio/x-realaudio',
  1932. 'rv' => 'video/vnd.rn-realvideo',
  1933. 'wav' => 'audio/x-wav',
  1934. 'bmp' => 'image/bmp',
  1935. 'gif' => 'image/gif',
  1936. 'jpeg' => 'image/jpeg',
  1937. 'jpg' => 'image/jpeg',
  1938. 'jpe' => 'image/jpeg',
  1939. 'png' => 'image/png',
  1940. 'tiff' => 'image/tiff',
  1941. 'tif' => 'image/tiff',
  1942. 'css' => 'text/css',
  1943. 'html' => 'text/html',
  1944. 'htm' => 'text/html',
  1945. 'shtml' => 'text/html',
  1946. 'txt' => 'text/plain',
  1947. 'text' => 'text/plain',
  1948. 'log' => 'text/plain',
  1949. 'rtx' => 'text/richtext',
  1950. 'rtf' => 'text/rtf',
  1951. 'xml' => 'text/xml',
  1952. 'xsl' => 'text/xml',
  1953. 'mpeg' => 'video/mpeg',
  1954. 'mpg' => 'video/mpeg',
  1955. 'mpe' => 'video/mpeg',
  1956. 'qt' => 'video/quicktime',
  1957. 'mov' => 'video/quicktime',
  1958. 'avi' => 'video/x-msvideo',
  1959. 'movie' => 'video/x-sgi-movie',
  1960. 'doc' => 'application/msword',
  1961. 'word' => 'application/msword',
  1962. 'xl' => 'application/excel',
  1963. 'eml' => 'message/rfc822'
  1964. );
  1965. return (!isset($mimes[strtolower($ext)])) ? 'application/octet-stream' : $mimes[strtolower($ext)];
  1966. }
  1967. /**
  1968. * Set (or reset) Class Objects (variables)
  1969. *
  1970. * Usage Example:
  1971. * $page->set('X-Priority', '3');
  1972. *
  1973. * @access public
  1974. * @param string $name Parameter Name
  1975. * @param mixed $value Parameter Value
  1976. * NOTE: will not work with arrays, there are no arrays to set/reset
  1977. * @todo Should this not be using __set() magic function?
  1978. */
  1979. public function set($name, $value = '') {
  1980. try {
  1981. if (isset($this->$name) ) {
  1982. $this->$name = $value;
  1983. }
  1984. else {
  1985. throw new phpmailerException(t('Cannot set or reset variable: !name', array('!name' => $name)) , self::STOP_CRITICAL);
  1986. }
  1987. } catch (Exception $e) {
  1988. $this->SetError($e->getMessage());
  1989. if ($e->getCode() == self::STOP_CRITICAL) {
  1990. return FALSE;
  1991. }
  1992. }
  1993. return TRUE;
  1994. }
  1995. /**
  1996. * Strips newlines to prevent header injection.
  1997. * @access public
  1998. * @param string $str String
  1999. * @return string
  2000. */
  2001. public function SecureHeader($str) {
  2002. $str = str_replace("\r", '', $str);
  2003. $str = str_replace("\n", '', $str);
  2004. return trim($str);
  2005. }
  2006. /**
  2007. * Set the private key file and password to sign the message.
  2008. *
  2009. * @access public
  2010. * @param string $key_filename Parameter File Name
  2011. * @param string $key_pass Password for private key
  2012. */
  2013. public function Sign($cert_filename, $key_filename, $key_pass) {
  2014. $this->sign_cert_file = $cert_filename;
  2015. $this->sign_key_file = $key_filename;
  2016. $this->sign_key_pass = $key_pass;
  2017. }
  2018. /**
  2019. * Set the private key file and password to sign the message.
  2020. *
  2021. * @access public
  2022. * @param string $key_filename Parameter File Name
  2023. * @param string $key_pass Password for private key
  2024. */
  2025. public function DKIM_QP($txt) {
  2026. $tmp="";
  2027. $line="";
  2028. for ($i=0;$i<strlen($txt);$i++) {
  2029. $ord=ord($txt[$i]);
  2030. if ( ((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E)) ) {
  2031. $line .=$txt[$i];
  2032. }
  2033. else {
  2034. $line .="=" . sprintf("%02X", $ord);
  2035. }
  2036. }
  2037. return $line;
  2038. }
  2039. /**
  2040. * Generate DKIM signature
  2041. *
  2042. * @access public
  2043. * @param string $s Header
  2044. */
  2045. public function DKIM_Sign($s) {
  2046. $privKeyStr = file_get_contents($this->DKIM_private);
  2047. if ($this->DKIM_passphrase!='') {
  2048. $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
  2049. }
  2050. else {
  2051. $privKey = $privKeyStr;
  2052. }
  2053. if (openssl_sign($s, $signature, $privKey)) {
  2054. return base64_encode($signature);
  2055. }
  2056. }
  2057. /**
  2058. * Generate DKIM Canonicalization Header
  2059. *
  2060. * @access public
  2061. * @param string $s Header
  2062. */
  2063. public function DKIM_HeaderC($s) {
  2064. $s=preg_replace("/\r\n\s+/", " ", $s);
  2065. $lines=explode("\r\n", $s);
  2066. foreach ($lines as $key => $line) {
  2067. list($heading, $value)=explode(":", $line, 2);
  2068. $heading=strtolower($heading);
  2069. $value=preg_replace("/\s+/", " ", $value); // Compress useless spaces
  2070. $lines[$key]=$heading . ":" . trim($value); // Don't forget to remove WSP around the value
  2071. }
  2072. $s=implode("\r\n", $lines);
  2073. return $s;
  2074. }
  2075. /**
  2076. * Generate DKIM Canonicalization Body
  2077. *
  2078. * @access public
  2079. * @param string $body Message Body
  2080. */
  2081. public function DKIM_BodyC($body) {
  2082. if ($body == '') return "\r\n";
  2083. // stabilize line endings
  2084. $body=str_replace("\r\n", "\n", $body);
  2085. $body=str_replace("\n", "\r\n", $body);
  2086. // END stabilize line endings
  2087. while (substr($body, strlen($body)-4, 4) == "\r\n\r\n") {
  2088. $body=substr($body, 0, strlen($body)-2);
  2089. }
  2090. return $body;
  2091. }
  2092. /**
  2093. * Create the DKIM header, body, as new header
  2094. *
  2095. * @access public
  2096. * @param string $headers_line Header lines
  2097. * @param string $subject Subject
  2098. * @param string $body Body
  2099. */
  2100. public function DKIM_Add($headers_line, $subject, $body) {
  2101. $DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms
  2102. $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
  2103. $DKIMquery = 'dns/txt'; // Query method
  2104. $DKIMtime = REQUEST_TIME; // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
  2105. $subject_header = "Subject: $subject";
  2106. $headers = explode("\r\n", $headers_line);
  2107. foreach ($headers as $header) {
  2108. if (strpos($header, 'From:') === 0) {
  2109. $from_header=$header;
  2110. }
  2111. elseif (strpos($header, 'To:') === 0) {
  2112. $to_header=$header;
  2113. }
  2114. }
  2115. $from = str_replace('|', '=7C', $this->DKIM_QP($from_header));
  2116. $to = str_replace('|', '=7C', $this->DKIM_QP($to_header));
  2117. $subject = str_replace('|', '=7C', $this->DKIM_QP($subject_header)); // Copied header fields (dkim-quoted-printable
  2118. $body = $this->DKIM_BodyC($body);
  2119. $DKIMlen = strlen($body) ; // Length of body
  2120. $DKIMb64 = base64_encode(pack("H*", sha1($body))) ; // Base64 of packed binary SHA-1 hash of body
  2121. $ident = ($this->DKIM_identity == '')? '' : " i=" . $this->DKIM_identity . ";";
  2122. $dkimhdrs = "DKIM-Signature: v=1; a=" . $DKIMsignatureType . "; q=" . $DKIMquery . "; l=" . $DKIMlen . "; s=" . $this->DKIM_selector . ";\r\n" .
  2123. "\tt=" . $DKIMtime . "; c=" . $DKIMcanonicalization . ";\r\n" .
  2124. "\th=From:To:Subject;\r\n" .
  2125. "\td=" . $this->DKIM_domain . ";" . $ident . "\r\n" .
  2126. "\tz=$from\r\n" .
  2127. "\t|$to\r\n" .
  2128. "\t|$subject;\r\n" .
  2129. "\tbh=" . $DKIMb64 . ";\r\n" .
  2130. "\tb=";
  2131. $toSign = $this->DKIM_HeaderC($from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs);
  2132. $signed = $this->DKIM_Sign($toSign);
  2133. return "X-PHPMAILER-DKIM: phpmailer.worxware.com\r\n" . $dkimhdrs . $signed . "\r\n";
  2134. }
  2135. protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body) {
  2136. if (!empty($this->action_function) && function_exists($this->action_function)) {
  2137. $params = array($isSent, $to, $cc, $bcc, $subject, $body);
  2138. call_user_func_array($this->action_function, $params);
  2139. }
  2140. }
  2141. }
  2142. class phpmailerException extends Exception {
  2143. public function errorMessage() {
  2144. $errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n";
  2145. return $errorMsg;
  2146. }
  2147. }