class.phpmailer.php 73 KB

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