class.phpmailer.php 89 KB

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