smtp.phpmailer.inc 71 KB

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