class.phpmailer.php 73 KB

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