smtp.phpmailer.inc 71 KB

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