class.phpmailer.php 113 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392
  1. <?php
  2. /**
  3. * PHPMailer - PHP email creation and transport class.
  4. * PHP Version 5.0.0
  5. * Version 5.2.7
  6. * @package PHPMailer
  7. * @link https://github.com/PHPMailer/PHPMailer/
  8. * @author Marcus Bointon (coolbru) <phpmailer@synchromedia.co.uk>
  9. * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
  10. * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
  11. * @author Brent R. Matzelle (original founder)
  12. * @copyright 2013 Marcus Bointon
  13. * @copyright 2010 - 2012 Jim Jagielski
  14. * @copyright 2004 - 2009 Andy Prevost
  15. * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
  16. * @note This program is distributed in the hope that it will be useful - WITHOUT
  17. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  18. * FITNESS FOR A PARTICULAR PURPOSE.
  19. */
  20. if (version_compare(PHP_VERSION, '5.0.0', '<')) {
  21. exit("Sorry, PHPMailer will only run on PHP version 5 or greater!\n");
  22. }
  23. /**
  24. * PHPMailer - PHP email creation and transport class.
  25. * PHP Version 5.0.0
  26. * @package PHPMailer
  27. * @author Marcus Bointon (coolbru) <phpmailer@synchromedia.co.uk>
  28. * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
  29. * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
  30. * @author Brent R. Matzelle (original founder)
  31. * @copyright 2013 Marcus Bointon
  32. * @copyright 2010 - 2012 Jim Jagielski
  33. * @copyright 2004 - 2009 Andy Prevost
  34. */
  35. class PHPMailer
  36. {
  37. /**
  38. * The PHPMailer Version number.
  39. * @type string
  40. */
  41. public $Version = '5.2.7';
  42. /**
  43. * Email priority.
  44. * Options: 1 = High, 3 = Normal, 5 = low.
  45. * @type int
  46. */
  47. public $Priority = 3;
  48. /**
  49. * The character set of the message.
  50. * @type string
  51. */
  52. public $CharSet = 'iso-8859-1';
  53. /**
  54. * The MIME Content-type of the message.
  55. * @type string
  56. */
  57. public $ContentType = 'text/plain';
  58. /**
  59. * The message encoding.
  60. * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable".
  61. * @type string
  62. */
  63. public $Encoding = '8bit';
  64. /**
  65. * Holds the most recent mailer error message.
  66. * @type string
  67. */
  68. public $ErrorInfo = '';
  69. /**
  70. * The From email address for the message.
  71. * @type string
  72. */
  73. public $From = 'root@localhost';
  74. /**
  75. * The From name of the message.
  76. * @type string
  77. */
  78. public $FromName = 'Root User';
  79. /**
  80. * The Sender email (Return-Path) of the message.
  81. * If not empty, will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
  82. * @type string
  83. */
  84. public $Sender = '';
  85. /**
  86. * The Return-Path of the message.
  87. * If empty, it will be set to either From or Sender.
  88. * @type string
  89. */
  90. public $ReturnPath = '';
  91. /**
  92. * The Subject of the message.
  93. * @type string
  94. */
  95. public $Subject = '';
  96. /**
  97. * An HTML or plain text message body.
  98. * If HTML then call isHTML(true).
  99. * @type string
  100. */
  101. public $Body = '';
  102. /**
  103. * The plain-text message body.
  104. * This body can be read by mail clients that do not have HTML email
  105. * capability such as mutt & Eudora.
  106. * Clients that can read HTML will view the normal Body.
  107. * @type string
  108. */
  109. public $AltBody = '';
  110. /**
  111. * An iCal message part body.
  112. * Only supported in simple alt or alt_inline message types
  113. * To generate iCal events, use the bundled extras/EasyPeasyICS.php class or iCalcreator
  114. * @link http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/
  115. * @link http://kigkonsult.se/iCalcreator/
  116. * @type string
  117. */
  118. public $Ical = '';
  119. /**
  120. * The complete compiled MIME message body.
  121. * @access protected
  122. * @type string
  123. */
  124. protected $MIMEBody = '';
  125. /**
  126. * The complete compiled MIME message headers.
  127. * @type string
  128. * @access protected
  129. */
  130. protected $MIMEHeader = '';
  131. /**
  132. * Extra headers that createHeader() doesn't fold in.
  133. * @type string
  134. * @access protected
  135. */
  136. protected $mailHeader = '';
  137. /**
  138. * Word-wrap the message body to this number of chars.
  139. * @type int
  140. */
  141. public $WordWrap = 0;
  142. /**
  143. * Which method to use to send mail.
  144. * Options: "mail", "sendmail", or "smtp".
  145. * @type string
  146. */
  147. public $Mailer = 'mail';
  148. /**
  149. * The path to the sendmail program.
  150. * @type string
  151. */
  152. public $Sendmail = '/usr/sbin/sendmail';
  153. /**
  154. * Whether mail() uses a fully sendmail-compatible MTA.
  155. * One which supports sendmail's "-oi -f" options.
  156. * @type bool
  157. */
  158. public $UseSendmailOptions = true;
  159. /**
  160. * Path to PHPMailer plugins.
  161. * Useful if the SMTP class is not in the PHP include path.
  162. * @type string
  163. * @deprecated Should not be needed now there is an autoloader.
  164. */
  165. public $PluginDir = '';
  166. /**
  167. * The email address that a reading confirmation should be sent to.
  168. * @type string
  169. */
  170. public $ConfirmReadingTo = '';
  171. /**
  172. * The hostname to use in Message-Id and Received headers
  173. * and as default HELO string.
  174. * If empty, the value returned
  175. * by SERVER_NAME is used or 'localhost.localdomain'.
  176. * @type string
  177. */
  178. public $Hostname = '';
  179. /**
  180. * An ID to be used in the Message-Id header.
  181. * If empty, a unique id will be generated.
  182. * @type string
  183. */
  184. public $MessageID = '';
  185. /**
  186. * The message Date to be used in the Date header.
  187. * If empty, the current date will be added.
  188. * @type string
  189. */
  190. public $MessageDate = '';
  191. /**
  192. * SMTP hosts.
  193. * Either a single hostname or multiple semicolon-delimited hostnames.
  194. * You can also specify a different port
  195. * for each host by using this format: [hostname:port]
  196. * (e.g. "smtp1.example.com:25;smtp2.example.com").
  197. * Hosts will be tried in order.
  198. * @type string
  199. */
  200. public $Host = 'localhost';
  201. /**
  202. * The default SMTP server port.
  203. * @type int
  204. * @Todo Why is this needed when the SMTP class takes care of it?
  205. */
  206. public $Port = 25;
  207. /**
  208. * The SMTP HELO of the message.
  209. * Default is $Hostname.
  210. * @type string
  211. * @see PHPMailer::$Hostname
  212. */
  213. public $Helo = '';
  214. /**
  215. * The secure connection prefix.
  216. * Options: "", "ssl" or "tls"
  217. * @type string
  218. */
  219. public $SMTPSecure = '';
  220. /**
  221. * Whether to use SMTP authentication.
  222. * Uses the Username and Password properties.
  223. * @type bool
  224. * @see PHPMailer::$Username
  225. * @see PHPMailer::$Password
  226. */
  227. public $SMTPAuth = false;
  228. /**
  229. * SMTP username.
  230. * @type string
  231. */
  232. public $Username = '';
  233. /**
  234. * SMTP password.
  235. * @type string
  236. */
  237. public $Password = '';
  238. /**
  239. * SMTP auth type.
  240. * Options are LOGIN (default), PLAIN, NTLM, CRAM-MD5
  241. * @type string
  242. */
  243. public $AuthType = '';
  244. /**
  245. * SMTP realm.
  246. * Used for NTLM auth
  247. * @type string
  248. */
  249. public $Realm = '';
  250. /**
  251. * SMTP workstation.
  252. * Used for NTLM auth
  253. * @type string
  254. */
  255. public $Workstation = '';
  256. /**
  257. * The SMTP server timeout in seconds.
  258. * @type int
  259. */
  260. public $Timeout = 10;
  261. /**
  262. * SMTP class debug output mode.
  263. * Options: 0 = off, 1 = commands, 2 = commands and data
  264. * @type int
  265. * @see SMTP::$do_debug
  266. */
  267. public $SMTPDebug = 0;
  268. /**
  269. * The function/method to use for debugging output.
  270. * Options: "echo" or "error_log"
  271. * @type string
  272. * @see SMTP::$Debugoutput
  273. */
  274. public $Debugoutput = "echo";
  275. /**
  276. * Whether to keep SMTP connection open after each message.
  277. * If this is set to true then to close the connection
  278. * requires an explicit call to smtpClose().
  279. * @type bool
  280. */
  281. public $SMTPKeepAlive = false;
  282. /**
  283. * Whether to split multiple to addresses into multiple messages
  284. * or send them all in one message.
  285. * @type bool
  286. */
  287. public $SingleTo = false;
  288. /**
  289. * Storage for addresses when SingleTo is enabled.
  290. * @type array
  291. * @todo This should really not be public
  292. */
  293. public $SingleToArray = array();
  294. /**
  295. * Whether to generate VERP addresses on send.
  296. * Only applicable when sending via SMTP.
  297. * @link http://en.wikipedia.org/wiki/Variable_envelope_return_path
  298. * @type bool
  299. */
  300. public $do_verp = false;
  301. /**
  302. * Whether to allow sending messages with an empty body.
  303. * @type bool
  304. */
  305. public $AllowEmpty = false;
  306. /**
  307. * The default line ending.
  308. * @note The default remains "\n". We force CRLF where we know
  309. * it must be used via self::CRLF.
  310. * @type string
  311. */
  312. public $LE = "\n";
  313. /**
  314. * DKIM selector.
  315. * @type string
  316. */
  317. public $DKIM_selector = '';
  318. /**
  319. * DKIM Identity.
  320. * Usually the email address used as the source of the email
  321. * @type string
  322. */
  323. public $DKIM_identity = '';
  324. /**
  325. * DKIM passphrase.
  326. * Used if your key is encrypted.
  327. * @type string
  328. */
  329. public $DKIM_passphrase = '';
  330. /**
  331. * DKIM signing domain name.
  332. * @example 'example.com'
  333. * @type string
  334. */
  335. public $DKIM_domain = '';
  336. /**
  337. * DKIM private key file path.
  338. * @type string
  339. */
  340. public $DKIM_private = '';
  341. /**
  342. * Callback Action function name.
  343. *
  344. * The function that handles the result of the send email action.
  345. * It is called out by send() for each email sent.
  346. *
  347. * Value can be any php callable: http://www.php.net/is_callable
  348. *
  349. * Parameters:
  350. * bool $result result of the send action
  351. * string $to email address of the recipient
  352. * string $cc cc email addresses
  353. * string $bcc bcc email addresses
  354. * string $subject the subject
  355. * string $body the email body
  356. * string $from email address of sender
  357. * @type string
  358. */
  359. public $action_function = '';
  360. /**
  361. * What to use in the X-Mailer header.
  362. * Options: null for default, whitespace for none, or a string to use
  363. * @type string
  364. */
  365. public $XMailer = '';
  366. /**
  367. * An instance of the SMTP sender class.
  368. * @type SMTP
  369. * @access protected
  370. */
  371. public $smtp = null;
  372. /**
  373. * The array of 'to' addresses.
  374. * @type array
  375. * @access protected
  376. */
  377. protected $to = array();
  378. /**
  379. * The array of 'cc' addresses.
  380. * @type array
  381. * @access protected
  382. */
  383. protected $cc = array();
  384. /**
  385. * The array of 'bcc' addresses.
  386. * @type array
  387. * @access protected
  388. */
  389. protected $bcc = array();
  390. /**
  391. * The array of reply-to names and addresses.
  392. * @type array
  393. * @access protected
  394. */
  395. protected $ReplyTo = array();
  396. /**
  397. * An array of all kinds of addresses.
  398. * Includes all of $to, $cc, $bcc, $replyto
  399. * @type array
  400. * @access protected
  401. */
  402. protected $all_recipients = array();
  403. /**
  404. * The array of attachments.
  405. * @type array
  406. * @access protected
  407. */
  408. protected $attachment = array();
  409. /**
  410. * The array of custom headers.
  411. * @type array
  412. * @access protected
  413. */
  414. protected $CustomHeader = array();
  415. /**
  416. * The most recent Message-ID (including angular brackets).
  417. * @type string
  418. * @access protected
  419. */
  420. protected $lastMessageID = '';
  421. /**
  422. * The message's MIME type.
  423. * @type string
  424. * @access protected
  425. */
  426. protected $message_type = '';
  427. /**
  428. * The array of MIME boundary strings.
  429. * @type array
  430. * @access protected
  431. */
  432. protected $boundary = array();
  433. /**
  434. * The array of available languages.
  435. * @type array
  436. * @access protected
  437. */
  438. protected $language = array();
  439. /**
  440. * The number of errors encountered.
  441. * @type integer
  442. * @access protected
  443. */
  444. protected $error_count = 0;
  445. /**
  446. * The S/MIME certificate file path.
  447. * @type string
  448. * @access protected
  449. */
  450. protected $sign_cert_file = '';
  451. /**
  452. * The S/MIME key file path.
  453. * @type string
  454. * @access protected
  455. */
  456. protected $sign_key_file = '';
  457. /**
  458. * The S/MIME password for the key.
  459. * Used only if the key is encrypted.
  460. * @type string
  461. * @access protected
  462. */
  463. protected $sign_key_pass = '';
  464. /**
  465. * Whether to throw exceptions for errors.
  466. * @type bool
  467. * @access protected
  468. */
  469. protected $exceptions = false;
  470. /**
  471. * Error severity: message only, continue processing
  472. */
  473. const STOP_MESSAGE = 0;
  474. /**
  475. * Error severity: message, likely ok to continue processing
  476. */
  477. const STOP_CONTINUE = 1;
  478. /**
  479. * Error severity: message, plus full stop, critical error reached
  480. */
  481. const STOP_CRITICAL = 2;
  482. /**
  483. * SMTP RFC standard line ending
  484. */
  485. const CRLF = "\r\n";
  486. /**
  487. * Constructor
  488. * @param bool $exceptions Should we throw external exceptions?
  489. */
  490. public function __construct($exceptions = false)
  491. {
  492. $this->exceptions = ($exceptions == true);
  493. //Make sure our autoloader is loaded
  494. if (version_compare(PHP_VERSION, '5.1.2', '>=')) {
  495. $al = spl_autoload_functions();
  496. if ($al === false or !in_array('PHPMailerAutoload', $al)) {
  497. require 'PHPMailerAutoload.php';
  498. }
  499. }
  500. }
  501. /**
  502. * Destructor.
  503. */
  504. public function __destruct()
  505. {
  506. if ($this->Mailer == 'smtp') { //close any open SMTP connection nicely
  507. $this->smtpClose();
  508. }
  509. }
  510. /**
  511. * Call mail() in a safe_mode-aware fashion.
  512. * Also, unless sendmail_path points to sendmail (or something that
  513. * claims to be sendmail), don't pass params (not a perfect fix,
  514. * but it will do)
  515. * @param string $to To
  516. * @param string $subject Subject
  517. * @param string $body Message Body
  518. * @param string $header Additional Header(s)
  519. * @param string $params Params
  520. * @access private
  521. * @return bool
  522. */
  523. private function mailPassthru($to, $subject, $body, $header, $params)
  524. {
  525. //Check overloading of mail function to avoid double-encoding
  526. if (ini_get('mbstring.func_overload') & 1) {
  527. $subject = $this->secureHeader($subject);
  528. } else {
  529. $subject = $this->encodeHeader($this->secureHeader($subject));
  530. }
  531. if (ini_get('safe_mode') || !($this->UseSendmailOptions)) {
  532. $rt = @mail($to, $subject, $body, $header);
  533. } else {
  534. $rt = @mail($to, $subject, $body, $header, $params);
  535. }
  536. return $rt;
  537. }
  538. /**
  539. * Output debugging info via user-defined method.
  540. * Only if debug output is enabled.
  541. * @see PHPMailer::$Debugoutput
  542. * @see PHPMailer::$SMTPDebug
  543. * @param string $str
  544. */
  545. protected function edebug($str)
  546. {
  547. if (!$this->SMTPDebug) {
  548. return;
  549. }
  550. switch ($this->Debugoutput) {
  551. case 'error_log':
  552. error_log($str);
  553. break;
  554. case 'html':
  555. //Cleans up output a bit for a better looking display that's HTML-safe
  556. echo htmlentities(preg_replace('/[\r\n]+/', '', $str), ENT_QUOTES, $this->CharSet) . "<br>\n";
  557. break;
  558. case 'echo':
  559. default:
  560. echo $str."\n";
  561. }
  562. }
  563. /**
  564. * Sets message type to HTML or plain.
  565. * @param bool $ishtml True for HTML mode.
  566. * @return void
  567. */
  568. public function isHTML($ishtml = true)
  569. {
  570. if ($ishtml) {
  571. $this->ContentType = 'text/html';
  572. } else {
  573. $this->ContentType = 'text/plain';
  574. }
  575. }
  576. /**
  577. * Send messages using SMTP.
  578. * @return void
  579. */
  580. public function isSMTP()
  581. {
  582. $this->Mailer = 'smtp';
  583. }
  584. /**
  585. * Send messages using PHP's mail() function.
  586. * @return void
  587. */
  588. public function isMail()
  589. {
  590. $this->Mailer = 'mail';
  591. }
  592. /**
  593. * Send messages using $Sendmail.
  594. * @return void
  595. */
  596. public function isSendmail()
  597. {
  598. if (!stristr(ini_get('sendmail_path'), 'sendmail')) {
  599. $this->Sendmail = '/usr/sbin/sendmail';
  600. }
  601. $this->Mailer = 'sendmail';
  602. }
  603. /**
  604. * Send messages using qmail.
  605. * @return void
  606. */
  607. public function isQmail()
  608. {
  609. if (!stristr(ini_get('sendmail_path'), 'qmail')) {
  610. $this->Sendmail = '/var/qmail/bin/qmail-inject';
  611. }
  612. $this->Mailer = 'qmail';
  613. }
  614. /**
  615. * Add a "To" address.
  616. * @param string $address
  617. * @param string $name
  618. * @return bool true on success, false if address already used
  619. */
  620. public function addAddress($address, $name = '')
  621. {
  622. return $this->addAnAddress('to', $address, $name);
  623. }
  624. /**
  625. * Add a "CC" address.
  626. * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer.
  627. * @param string $address
  628. * @param string $name
  629. * @return bool true on success, false if address already used
  630. */
  631. public function addCC($address, $name = '')
  632. {
  633. return $this->addAnAddress('cc', $address, $name);
  634. }
  635. /**
  636. * Add a "BCC" address.
  637. * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer.
  638. * @param string $address
  639. * @param string $name
  640. * @return bool true on success, false if address already used
  641. */
  642. public function addBCC($address, $name = '')
  643. {
  644. return $this->addAnAddress('bcc', $address, $name);
  645. }
  646. /**
  647. * Add a "Reply-to" address.
  648. * @param string $address
  649. * @param string $name
  650. * @return bool
  651. */
  652. public function addReplyTo($address, $name = '')
  653. {
  654. return $this->addAnAddress('Reply-To', $address, $name);
  655. }
  656. /**
  657. * Add an address to one of the recipient arrays.
  658. * Addresses that have been added already return false, but do not throw exceptions
  659. * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo'
  660. * @param string $address The email address to send to
  661. * @param string $name
  662. * @throws phpmailerException
  663. * @return bool true on success, false if address already used or invalid in some way
  664. * @access protected
  665. */
  666. protected function addAnAddress($kind, $address, $name = '')
  667. {
  668. if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) {
  669. $this->setError($this->lang('Invalid recipient array') . ': ' . $kind);
  670. $this->edebug($this->lang('Invalid recipient array') . ': ' . $kind);
  671. if ($this->exceptions) {
  672. throw new phpmailerException('Invalid recipient array: ' . $kind);
  673. }
  674. return false;
  675. }
  676. $address = trim($address);
  677. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  678. if (!$this->validateAddress($address)) {
  679. $this->setError($this->lang('invalid_address') . ': ' . $address);
  680. $this->edebug($this->lang('invalid_address') . ': ' . $address);
  681. if ($this->exceptions) {
  682. throw new phpmailerException($this->lang('invalid_address') . ': ' . $address);
  683. }
  684. return false;
  685. }
  686. if ($kind != 'Reply-To') {
  687. if (!isset($this->all_recipients[strtolower($address)])) {
  688. array_push($this->$kind, array($address, $name));
  689. $this->all_recipients[strtolower($address)] = true;
  690. return true;
  691. }
  692. } else {
  693. if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
  694. $this->ReplyTo[strtolower($address)] = array($address, $name);
  695. return true;
  696. }
  697. }
  698. return false;
  699. }
  700. /**
  701. * Set the From and FromName properties.
  702. * @param string $address
  703. * @param string $name
  704. * @param bool $auto Whether to also set the Sender address, defaults to true
  705. * @throws phpmailerException
  706. * @return bool
  707. */
  708. public function setFrom($address, $name = '', $auto = true)
  709. {
  710. $address = trim($address);
  711. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  712. if (!$this->validateAddress($address)) {
  713. $this->setError($this->lang('invalid_address') . ': ' . $address);
  714. $this->edebug($this->lang('invalid_address') . ': ' . $address);
  715. if ($this->exceptions) {
  716. throw new phpmailerException($this->lang('invalid_address') . ': ' . $address);
  717. }
  718. return false;
  719. }
  720. $this->From = $address;
  721. $this->FromName = $name;
  722. if ($auto) {
  723. if (empty($this->Sender)) {
  724. $this->Sender = $address;
  725. }
  726. }
  727. return true;
  728. }
  729. /**
  730. * Return the Message-ID header of the last email.
  731. * Technically this is the value from the last time the headers were created,
  732. * but it's also the message ID of the last sent message except in
  733. * pathological cases.
  734. * @return string
  735. */
  736. public function getLastMessageID()
  737. {
  738. return $this->lastMessageID;
  739. }
  740. /**
  741. * Check that a string looks like an email address.
  742. * @param string $address The email address to check
  743. * @param string $patternselect A selector for the validation pattern to use :
  744. * 'auto' - pick best one automatically;
  745. * 'pcre8' - use the squiloople.com pattern, requires PCRE > 8.0, PHP >= 5.3.2, 5.2.14;
  746. * 'pcre' - use old PCRE implementation;
  747. * 'php' - use PHP built-in FILTER_VALIDATE_EMAIL; faster, less thorough;
  748. * 'noregex' - super fast, really dumb.
  749. * @return bool
  750. * @static
  751. * @access public
  752. */
  753. public static function validateAddress($address, $patternselect = 'auto')
  754. {
  755. if ($patternselect == 'auto') {
  756. if (defined(
  757. 'PCRE_VERSION'
  758. )
  759. ) { //Check this instead of extension_loaded so it works when that function is disabled
  760. if (version_compare(PCRE_VERSION, '8.0') >= 0) {
  761. $patternselect = 'pcre8';
  762. } else {
  763. $patternselect = 'pcre';
  764. }
  765. } else {
  766. //Filter_var appeared in PHP 5.2.0 and does not require the PCRE extension
  767. if (version_compare(PHP_VERSION, '5.2.0') >= 0) {
  768. $patternselect = 'php';
  769. } else {
  770. $patternselect = 'noregex';
  771. }
  772. }
  773. }
  774. switch ($patternselect) {
  775. case 'pcre8':
  776. /**
  777. * Conforms to RFC5322: Uses *correct* regex on which FILTER_VALIDATE_EMAIL is
  778. * based; So why not use FILTER_VALIDATE_EMAIL? Because it was broken to
  779. * not allow a@b type valid addresses :(
  780. * @link http://squiloople.com/2009/12/20/email-address-validation/
  781. * @copyright 2009-2010 Michael Rushton
  782. * Feel free to use and redistribute this code. But please keep this copyright notice.
  783. */
  784. return (bool)preg_match(
  785. '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' .
  786. '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' .
  787. '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' .
  788. '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' .
  789. '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' .
  790. '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' .
  791. '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' .
  792. '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
  793. '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD',
  794. $address
  795. );
  796. break;
  797. case 'pcre':
  798. //An older regex that doesn't need a recent PCRE
  799. return (bool)preg_match(
  800. '/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!(?>"?(?>\\\[ -~]|[^"])"?){65,}@)(?>' .
  801. '[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*")' .
  802. '(?>\.(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*"))*' .
  803. '@(?>(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?![a-z0-9-]{64,})' .
  804. '(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)){0,126}|\[(?:(?>IPv6:(?>(?>[a-f0-9]{1,4})(?>:' .
  805. '[a-f0-9]{1,4}){7}|(?!(?:.*[a-f0-9][:\]]){8,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?' .
  806. '::(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?))|(?>(?>IPv6:(?>[a-f0-9]{1,4}(?>:' .
  807. '[a-f0-9]{1,4}){5}:|(?!(?:.*[a-f0-9]:){6,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4})?' .
  808. '::(?>(?:[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4}):)?))?(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
  809. '|[1-9]?[0-9])(?>\.(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}))\])$/isD',
  810. $address
  811. );
  812. break;
  813. case 'php':
  814. default:
  815. return (bool)filter_var($address, FILTER_VALIDATE_EMAIL);
  816. break;
  817. case 'noregex':
  818. //No PCRE! Do something _very_ approximate!
  819. //Check the address is 3 chars or longer and contains an @ that's not the first or last char
  820. return (strlen($address) >= 3
  821. and strpos($address, '@') >= 1
  822. and strpos($address, '@') != strlen($address) - 1);
  823. break;
  824. }
  825. }
  826. /**
  827. * Create a message and send it.
  828. * Uses the sending method specified by $Mailer.
  829. * @throws phpmailerException
  830. * @return bool false on error - See the ErrorInfo property for details of the error.
  831. */
  832. public function send()
  833. {
  834. try {
  835. if (!$this->preSend()) {
  836. return false;
  837. }
  838. return $this->postSend();
  839. } catch (phpmailerException $e) {
  840. $this->mailHeader = '';
  841. $this->setError($e->getMessage());
  842. if ($this->exceptions) {
  843. throw $e;
  844. }
  845. return false;
  846. }
  847. }
  848. /**
  849. * Prepare a message for sending.
  850. * @throws phpmailerException
  851. * @return bool
  852. */
  853. public function preSend()
  854. {
  855. try {
  856. $this->mailHeader = "";
  857. if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
  858. throw new phpmailerException($this->lang('provide_address'), self::STOP_CRITICAL);
  859. }
  860. // Set whether the message is multipart/alternative
  861. if (!empty($this->AltBody)) {
  862. $this->ContentType = 'multipart/alternative';
  863. }
  864. $this->error_count = 0; // reset errors
  865. $this->setMessageType();
  866. // Refuse to send an empty message unless we are specifically allowing it
  867. if (!$this->AllowEmpty and empty($this->Body)) {
  868. throw new phpmailerException($this->lang('empty_message'), self::STOP_CRITICAL);
  869. }
  870. $this->MIMEHeader = $this->createHeader();
  871. $this->MIMEBody = $this->createBody();
  872. // To capture the complete message when using mail(), create
  873. // an extra header list which createHeader() doesn't fold in
  874. if ($this->Mailer == 'mail') {
  875. if (count($this->to) > 0) {
  876. $this->mailHeader .= $this->addrAppend("To", $this->to);
  877. } else {
  878. $this->mailHeader .= $this->headerLine("To", "undisclosed-recipients:;");
  879. }
  880. $this->mailHeader .= $this->headerLine(
  881. 'Subject',
  882. $this->encodeHeader($this->secureHeader(trim($this->Subject)))
  883. );
  884. }
  885. // Sign with DKIM if enabled
  886. if (!empty($this->DKIM_domain)
  887. && !empty($this->DKIM_private)
  888. && !empty($this->DKIM_selector)
  889. && !empty($this->DKIM_domain)
  890. && file_exists($this->DKIM_private)) {
  891. $header_dkim = $this->DKIM_Add(
  892. $this->MIMEHeader . $this->mailHeader,
  893. $this->encodeHeader($this->secureHeader($this->Subject)),
  894. $this->MIMEBody
  895. );
  896. $this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . self::CRLF .
  897. str_replace("\r\n", "\n", $header_dkim) . self::CRLF;
  898. }
  899. return true;
  900. } catch (phpmailerException $e) {
  901. $this->setError($e->getMessage());
  902. if ($this->exceptions) {
  903. throw $e;
  904. }
  905. return false;
  906. }
  907. }
  908. /**
  909. * Actually send a message.
  910. * Send the email via the selected mechanism
  911. * @throws phpmailerException
  912. * @return bool
  913. */
  914. public function postSend()
  915. {
  916. try {
  917. // Choose the mailer and send through it
  918. switch ($this->Mailer) {
  919. case 'sendmail':
  920. case 'qmail':
  921. return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody);
  922. case 'smtp':
  923. return $this->smtpSend($this->MIMEHeader, $this->MIMEBody);
  924. case 'mail':
  925. return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
  926. default:
  927. if (method_exists($this, $this->Mailer.'Send')) {
  928. $sendMethod = $this->Mailer.'Send';
  929. return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody);
  930. } else {
  931. return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
  932. }
  933. }
  934. } catch (phpmailerException $e) {
  935. $this->setError($e->getMessage());
  936. $this->edebug($e->getMessage());
  937. if ($this->exceptions) {
  938. throw $e;
  939. }
  940. }
  941. return false;
  942. }
  943. /**
  944. * Send mail using the $Sendmail program.
  945. * @param string $header The message headers
  946. * @param string $body The message body
  947. * @see PHPMailer::$Sendmail
  948. * @throws phpmailerException
  949. * @access protected
  950. * @return bool
  951. */
  952. protected function sendmailSend($header, $body)
  953. {
  954. if ($this->Sender != '') {
  955. if ($this->Mailer == 'qmail') {
  956. $sendmail = sprintf("%s -f%s", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
  957. } else {
  958. $sendmail = sprintf("%s -oi -f%s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
  959. }
  960. } else {
  961. if ($this->Mailer == 'qmail') {
  962. $sendmail = sprintf("%s", escapeshellcmd($this->Sendmail));
  963. } else {
  964. $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail));
  965. }
  966. }
  967. if ($this->SingleTo === true) {
  968. foreach ($this->SingleToArray as $val) {
  969. if (!@$mail = popen($sendmail, 'w')) {
  970. throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  971. }
  972. fputs($mail, "To: " . $val . "\n");
  973. fputs($mail, $header);
  974. fputs($mail, $body);
  975. $result = pclose($mail);
  976. // implement call back function if it exists
  977. $isSent = ($result == 0) ? 1 : 0;
  978. $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
  979. if ($result != 0) {
  980. throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  981. }
  982. }
  983. } else {
  984. if (!@$mail = popen($sendmail, 'w')) {
  985. throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  986. }
  987. fputs($mail, $header);
  988. fputs($mail, $body);
  989. $result = pclose($mail);
  990. // implement call back function if it exists
  991. $isSent = ($result == 0) ? 1 : 0;
  992. $this->doCallback($isSent, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
  993. if ($result != 0) {
  994. throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  995. }
  996. }
  997. return true;
  998. }
  999. /**
  1000. * Send mail using the PHP mail() function.
  1001. * @param string $header The message headers
  1002. * @param string $body The message body
  1003. * @link http://www.php.net/manual/en/book.mail.php
  1004. * @throws phpmailerException
  1005. * @access protected
  1006. * @return bool
  1007. */
  1008. protected function mailSend($header, $body)
  1009. {
  1010. $toArr = array();
  1011. foreach ($this->to as $t) {
  1012. $toArr[] = $this->addrFormat($t);
  1013. }
  1014. $to = implode(', ', $toArr);
  1015. if (empty($this->Sender)) {
  1016. $params = " ";
  1017. } else {
  1018. $params = sprintf("-f%s", $this->Sender);
  1019. }
  1020. if ($this->Sender != '' and !ini_get('safe_mode')) {
  1021. $old_from = ini_get('sendmail_from');
  1022. ini_set('sendmail_from', $this->Sender);
  1023. }
  1024. $rt = false;
  1025. if ($this->SingleTo === true && count($toArr) > 1) {
  1026. foreach ($toArr as $val) {
  1027. $rt = $this->mailPassthru($val, $this->Subject, $body, $header, $params);
  1028. // implement call back function if it exists
  1029. $isSent = ($rt == 1) ? 1 : 0;
  1030. $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
  1031. }
  1032. } else {
  1033. $rt = $this->mailPassthru($to, $this->Subject, $body, $header, $params);
  1034. // implement call back function if it exists
  1035. $isSent = ($rt == 1) ? 1 : 0;
  1036. $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
  1037. }
  1038. if (isset($old_from)) {
  1039. ini_set('sendmail_from', $old_from);
  1040. }
  1041. if (!$rt) {
  1042. throw new phpmailerException($this->lang('instantiate'), self::STOP_CRITICAL);
  1043. }
  1044. return true;
  1045. }
  1046. /**
  1047. * Get an instance to use for SMTP operations.
  1048. * Override this function to load your own SMTP implementation
  1049. * @return SMTP
  1050. */
  1051. public function getSMTPInstance()
  1052. {
  1053. if (!is_object($this->smtp)) {
  1054. $this->smtp = new SMTP;
  1055. }
  1056. return $this->smtp;
  1057. }
  1058. /**
  1059. * Send mail via SMTP.
  1060. * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
  1061. * Uses the PHPMailerSMTP class by default.
  1062. * @see PHPMailer::getSMTPInstance() to use a different class.
  1063. * @param string $header The message headers
  1064. * @param string $body The message body
  1065. * @throws phpmailerException
  1066. * @uses SMTP
  1067. * @access protected
  1068. * @return bool
  1069. */
  1070. protected function smtpSend($header, $body)
  1071. {
  1072. $bad_rcpt = array();
  1073. $result = $this->smtpConnect();
  1074. if (is_error($result)) {
  1075. throw new phpmailerException($result['message'], self::STOP_CRITICAL);
  1076. }
  1077. $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender;
  1078. if (!$this->smtp->mail($smtp_from)) {
  1079. $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError()));
  1080. throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL);
  1081. }
  1082. // Attempt to send to all recipients
  1083. foreach ($this->to as $to) {
  1084. if (!$this->smtp->recipient($to[0])) {
  1085. $bad_rcpt[] = $to[0];
  1086. $isSent = 0;
  1087. } else {
  1088. $isSent = 1;
  1089. }
  1090. $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body, $this->From);
  1091. }
  1092. foreach ($this->cc as $cc) {
  1093. if (!$this->smtp->recipient($cc[0])) {
  1094. $bad_rcpt[] = $cc[0];
  1095. $isSent = 0;
  1096. } else {
  1097. $isSent = 1;
  1098. }
  1099. $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body, $this->From);
  1100. }
  1101. foreach ($this->bcc as $bcc) {
  1102. if (!$this->smtp->recipient($bcc[0])) {
  1103. $bad_rcpt[] = $bcc[0];
  1104. $isSent = 0;
  1105. } else {
  1106. $isSent = 1;
  1107. }
  1108. $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body, $this->From);
  1109. }
  1110. //Only send the DATA command if we have viable recipients
  1111. if ((count($this->all_recipients) > count($bad_rcpt)) and !$this->smtp->data($header . $body)) {
  1112. throw new phpmailerException($this->lang('data_not_accepted'), self::STOP_CRITICAL);
  1113. }
  1114. if ($this->SMTPKeepAlive == true) {
  1115. $this->smtp->reset();
  1116. } else {
  1117. $this->smtp->quit();
  1118. $this->smtp->close();
  1119. }
  1120. if (count($bad_rcpt) > 0) { //Create error message for any bad addresses
  1121. throw new phpmailerException(
  1122. $this->lang('recipients_failed') . implode(', ', $bad_rcpt),
  1123. self::STOP_CONTINUE
  1124. );
  1125. }
  1126. return true;
  1127. }
  1128. /**
  1129. * Initiate a connection to an SMTP server.
  1130. * Returns false if the operation failed.
  1131. * @param array $options An array of options compatible with stream_context_create()
  1132. * @uses SMTP
  1133. * @access public
  1134. * @throws phpmailerException
  1135. * @return bool
  1136. */
  1137. public function smtpConnect($options = array())
  1138. {
  1139. if (is_null($this->smtp)) {
  1140. $this->smtp = $this->getSMTPInstance();
  1141. }
  1142. //Already connected?
  1143. if ($this->smtp->connected()) {
  1144. return true;
  1145. }
  1146. $this->smtp->setTimeout($this->Timeout);
  1147. $this->smtp->setDebugLevel($this->SMTPDebug);
  1148. $this->smtp->setDebugOutput($this->Debugoutput);
  1149. $this->smtp->setVerp($this->do_verp);
  1150. $hosts = explode(';', $this->Host);
  1151. $lastexception = null;
  1152. foreach ($hosts as $hostentry) {
  1153. $hostinfo = array();
  1154. if (!preg_match('/^((ssl|tls):\/\/)*([a-zA-Z0-9\.-]*):?([0-9]*)$/', trim($hostentry), $hostinfo)) {
  1155. //Not a valid host entry
  1156. continue;
  1157. }
  1158. //$hostinfo[2]: optional ssl or tls prefix
  1159. //$hostinfo[3]: the hostname
  1160. //$hostinfo[4]: optional port number
  1161. //The host string prefix can temporarily override the current setting for SMTPSecure
  1162. //If it's not specified, the default value is used
  1163. $prefix = '';
  1164. $tls = ($this->SMTPSecure == 'tls');
  1165. if ($hostinfo[2] == 'ssl' or ($hostinfo[2] == '' and $this->SMTPSecure == 'ssl')) {
  1166. $prefix = 'ssl://';
  1167. $tls = false; //Can't have SSL and TLS at once
  1168. } elseif ($hostinfo[2] == 'tls') {
  1169. $tls = true;
  1170. //tls doesn't use a prefix
  1171. }
  1172. $host = $hostinfo[3];
  1173. $port = $this->Port;
  1174. $tport = (integer)$hostinfo[4];
  1175. if ($tport > 0 and $tport < 65536) {
  1176. $port = $tport;
  1177. }
  1178. if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) {
  1179. try {
  1180. if ($this->Helo) {
  1181. $hello = $this->Helo;
  1182. } else {
  1183. $hello = $this->serverHostname();
  1184. }
  1185. $this->smtp->hello($hello);
  1186. if ($tls) {
  1187. if (!$this->smtp->startTLS()) {
  1188. throw new phpmailerException($this->lang('connect_host'));
  1189. }
  1190. //We must resend HELO after tls negotiation
  1191. $this->smtp->hello($hello);
  1192. }
  1193. if ($this->SMTPAuth) {
  1194. if (!$this->smtp->authenticate(
  1195. $this->Username,
  1196. $this->Password,
  1197. $this->AuthType,
  1198. $this->Realm,
  1199. $this->Workstation
  1200. )
  1201. ) {
  1202. throw new phpmailerException($this->lang('authenticate'));
  1203. }
  1204. }
  1205. return true;
  1206. } catch (phpmailerException $e) {
  1207. $lastexception = $e;
  1208. //We must have connected, but then failed TLS or Auth, so close connection nicely
  1209. $this->smtp->quit();
  1210. $this->ErrorInfo = $e->errorMessage();
  1211. }
  1212. }
  1213. }
  1214. //If we get here, all connection attempts have failed, so close connection hard
  1215. $this->smtp->close();
  1216. //As we've caught all exceptions, just report whatever the last one was
  1217. if ($this->exceptions and !is_null($lastexception)) {
  1218. throw $lastexception;
  1219. }
  1220. return error(1, $this->ErrorInfo);
  1221. }
  1222. /**
  1223. * Close the active SMTP session if one exists.
  1224. * @return void
  1225. */
  1226. public function smtpClose()
  1227. {
  1228. if ($this->smtp !== null) {
  1229. if ($this->smtp->connected()) {
  1230. $this->smtp->quit();
  1231. $this->smtp->close();
  1232. }
  1233. }
  1234. }
  1235. /**
  1236. * Set the language for error messages.
  1237. * Returns false if it cannot load the language file.
  1238. * The default language is English.
  1239. * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr")
  1240. * @param string $lang_path Path to the language file directory, with trailing separator (slash)
  1241. * @return bool
  1242. * @access public
  1243. */
  1244. public function setLanguage($langcode = 'en', $lang_path = 'language/')
  1245. {
  1246. //Define full set of translatable strings
  1247. $PHPMAILER_LANG = array(
  1248. 'authenticate' => 'SMTP Error: Could not authenticate.',
  1249. 'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
  1250. 'data_not_accepted' => 'SMTP Error: data not accepted.',
  1251. 'empty_message' => 'Message body empty',
  1252. 'encoding' => 'Unknown encoding: ',
  1253. 'execute' => 'Could not execute: ',
  1254. 'file_access' => 'Could not access file: ',
  1255. 'file_open' => 'File Error: Could not open file: ',
  1256. 'from_failed' => 'The following From address failed: ',
  1257. 'instantiate' => 'Could not instantiate mail function.',
  1258. 'invalid_address' => 'Invalid address',
  1259. 'mailer_not_supported' => ' mailer is not supported.',
  1260. 'provide_address' => 'You must provide at least one recipient email address.',
  1261. 'recipients_failed' => 'SMTP Error: The following recipients failed: ',
  1262. 'signing' => 'Signing Error: ',
  1263. 'smtp_connect_failed' => 'SMTP connect() failed.',
  1264. 'smtp_error' => 'SMTP server error: ',
  1265. 'variable_set' => 'Cannot set or reset variable: '
  1266. );
  1267. //Overwrite language-specific strings.
  1268. //This way we'll never have missing translations - no more "language string failed to load"!
  1269. $l = true;
  1270. $lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php';
  1271. if ($langcode != 'en') { //There is no English translation file
  1272. //Make sure language file path is readable
  1273. if (!is_readable($lang_file)) {
  1274. $l = false;
  1275. } else {
  1276. $l = include $lang_file;
  1277. }
  1278. }
  1279. $this->language = $PHPMAILER_LANG;
  1280. return ($l == true); //Returns false if language not found
  1281. }
  1282. /**
  1283. * Get the array of strings for the current language.
  1284. * @return array
  1285. */
  1286. public function getTranslations()
  1287. {
  1288. return $this->language;
  1289. }
  1290. /**
  1291. * Create recipient headers.
  1292. * @access public
  1293. * @param string $type
  1294. * @param array $addr An array of recipient,
  1295. * where each recipient is a 2-element indexed array with element 0 containing an address
  1296. * and element 1 containing a name, like:
  1297. * array(array('joe@example.com', 'Joe User'), array('zoe@example.com', 'Zoe User'))
  1298. * @return string
  1299. */
  1300. public function addrAppend($type, $addr)
  1301. {
  1302. $addresses = array();
  1303. foreach ($addr as $a) {
  1304. $addresses[] = $this->addrFormat($a);
  1305. }
  1306. return $type . ': ' . implode(', ', $addresses) . $this->LE;
  1307. }
  1308. /**
  1309. * Format an address for use in a message header.
  1310. * @access public
  1311. * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name
  1312. * like array('joe@example.com', 'Joe User')
  1313. * @return string
  1314. */
  1315. public function addrFormat($addr)
  1316. {
  1317. if (empty($addr[1])) { // No name provided
  1318. return $this->secureHeader($addr[0]);
  1319. } else {
  1320. return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . " <" . $this->secureHeader(
  1321. $addr[0]
  1322. ) . ">";
  1323. }
  1324. }
  1325. /**
  1326. * Word-wrap message.
  1327. * For use with mailers that do not automatically perform wrapping
  1328. * and for quoted-printable encoded messages.
  1329. * Original written by philippe.
  1330. * @param string $message The message to wrap
  1331. * @param integer $length The line length to wrap to
  1332. * @param bool $qp_mode Whether to run in Quoted-Printable mode
  1333. * @access public
  1334. * @return string
  1335. */
  1336. public function wrapText($message, $length, $qp_mode = false)
  1337. {
  1338. $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE;
  1339. // If utf-8 encoding is used, we will need to make sure we don't
  1340. // split multibyte characters when we wrap
  1341. $is_utf8 = (strtolower($this->CharSet) == "utf-8");
  1342. $lelen = strlen($this->LE);
  1343. $crlflen = strlen(self::CRLF);
  1344. $message = $this->fixEOL($message);
  1345. if (substr($message, -$lelen) == $this->LE) {
  1346. $message = substr($message, 0, -$lelen);
  1347. }
  1348. $line = explode($this->LE, $message); // Magic. We know fixEOL uses $LE
  1349. $message = '';
  1350. for ($i = 0; $i < count($line); $i++) {
  1351. $line_part = explode(' ', $line[$i]);
  1352. $buf = '';
  1353. for ($e = 0; $e < count($line_part); $e++) {
  1354. $word = $line_part[$e];
  1355. if ($qp_mode and (strlen($word) > $length)) {
  1356. $space_left = $length - strlen($buf) - $crlflen;
  1357. if ($e != 0) {
  1358. if ($space_left > 20) {
  1359. $len = $space_left;
  1360. if ($is_utf8) {
  1361. $len = $this->utf8CharBoundary($word, $len);
  1362. } elseif (substr($word, $len - 1, 1) == "=") {
  1363. $len--;
  1364. } elseif (substr($word, $len - 2, 1) == "=") {
  1365. $len -= 2;
  1366. }
  1367. $part = substr($word, 0, $len);
  1368. $word = substr($word, $len);
  1369. $buf .= ' ' . $part;
  1370. $message .= $buf . sprintf("=%s", self::CRLF);
  1371. } else {
  1372. $message .= $buf . $soft_break;
  1373. }
  1374. $buf = '';
  1375. }
  1376. while (strlen($word) > 0) {
  1377. if ($length <= 0) {
  1378. break;
  1379. }
  1380. $len = $length;
  1381. if ($is_utf8) {
  1382. $len = $this->utf8CharBoundary($word, $len);
  1383. } elseif (substr($word, $len - 1, 1) == "=") {
  1384. $len--;
  1385. } elseif (substr($word, $len - 2, 1) == "=") {
  1386. $len -= 2;
  1387. }
  1388. $part = substr($word, 0, $len);
  1389. $word = substr($word, $len);
  1390. if (strlen($word) > 0) {
  1391. $message .= $part . sprintf("=%s", self::CRLF);
  1392. } else {
  1393. $buf = $part;
  1394. }
  1395. }
  1396. } else {
  1397. $buf_o = $buf;
  1398. $buf .= ($e == 0) ? $word : (' ' . $word);
  1399. if (strlen($buf) > $length and $buf_o != '') {
  1400. $message .= $buf_o . $soft_break;
  1401. $buf = $word;
  1402. }
  1403. }
  1404. }
  1405. $message .= $buf . self::CRLF;
  1406. }
  1407. return $message;
  1408. }
  1409. /**
  1410. * Find the last character boundary prior to $maxLength in a utf-8
  1411. * quoted (printable) encoded string.
  1412. * Original written by Colin Brown.
  1413. * @access public
  1414. * @param string $encodedText utf-8 QP text
  1415. * @param int $maxLength find last character boundary prior to this length
  1416. * @return int
  1417. */
  1418. public function utf8CharBoundary($encodedText, $maxLength)
  1419. {
  1420. $foundSplitPos = false;
  1421. $lookBack = 3;
  1422. while (!$foundSplitPos) {
  1423. $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
  1424. $encodedCharPos = strpos($lastChunk, "=");
  1425. if ($encodedCharPos !== false) {
  1426. // Found start of encoded character byte within $lookBack block.
  1427. // Check the encoded byte value (the 2 chars after the '=')
  1428. $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
  1429. $dec = hexdec($hex);
  1430. if ($dec < 128) { // Single byte character.
  1431. // If the encoded char was found at pos 0, it will fit
  1432. // otherwise reduce maxLength to start of the encoded char
  1433. $maxLength = ($encodedCharPos == 0) ? $maxLength :
  1434. $maxLength - ($lookBack - $encodedCharPos);
  1435. $foundSplitPos = true;
  1436. } elseif ($dec >= 192) { // First byte of a multi byte character
  1437. // Reduce maxLength to split at start of character
  1438. $maxLength = $maxLength - ($lookBack - $encodedCharPos);
  1439. $foundSplitPos = true;
  1440. } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back
  1441. $lookBack += 3;
  1442. }
  1443. } else {
  1444. // No encoded character found
  1445. $foundSplitPos = true;
  1446. }
  1447. }
  1448. return $maxLength;
  1449. }
  1450. /**
  1451. * Set the body wrapping.
  1452. * @access public
  1453. * @return void
  1454. */
  1455. public function setWordWrap()
  1456. {
  1457. if ($this->WordWrap < 1) {
  1458. return;
  1459. }
  1460. switch ($this->message_type) {
  1461. case 'alt':
  1462. case 'alt_inline':
  1463. case 'alt_attach':
  1464. case 'alt_inline_attach':
  1465. $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap);
  1466. break;
  1467. default:
  1468. $this->Body = $this->wrapText($this->Body, $this->WordWrap);
  1469. break;
  1470. }
  1471. }
  1472. /**
  1473. * Assemble message headers.
  1474. * @access public
  1475. * @return string The assembled headers
  1476. */
  1477. public function createHeader()
  1478. {
  1479. $result = '';
  1480. // Set the boundaries
  1481. $uniq_id = md5(uniqid(time()));
  1482. $this->boundary[1] = 'b1_' . $uniq_id;
  1483. $this->boundary[2] = 'b2_' . $uniq_id;
  1484. $this->boundary[3] = 'b3_' . $uniq_id;
  1485. if ($this->MessageDate == '') {
  1486. $result .= $this->headerLine('Date', self::rfcDate());
  1487. } else {
  1488. $result .= $this->headerLine('Date', $this->MessageDate);
  1489. }
  1490. if ($this->ReturnPath) {
  1491. $result .= $this->headerLine('Return-Path', '<' . trim($this->ReturnPath) . '>');
  1492. } elseif ($this->Sender == '') {
  1493. $result .= $this->headerLine('Return-Path', '<' . trim($this->From) . '>');
  1494. } else {
  1495. $result .= $this->headerLine('Return-Path', '<' . trim($this->Sender) . '>');
  1496. }
  1497. // To be created automatically by mail()
  1498. if ($this->Mailer != 'mail') {
  1499. if ($this->SingleTo === true) {
  1500. foreach ($this->to as $t) {
  1501. $this->SingleToArray[] = $this->addrFormat($t);
  1502. }
  1503. } else {
  1504. if (count($this->to) > 0) {
  1505. $result .= $this->addrAppend('To', $this->to);
  1506. } elseif (count($this->cc) == 0) {
  1507. $result .= $this->headerLine('To', 'undisclosed-recipients:;');
  1508. }
  1509. }
  1510. }
  1511. $result .= $this->addrAppend('From', array(array(trim($this->From), $this->FromName)));
  1512. // sendmail and mail() extract Cc from the header before sending
  1513. if (count($this->cc) > 0) {
  1514. $result .= $this->addrAppend('Cc', $this->cc);
  1515. }
  1516. // sendmail and mail() extract Bcc from the header before sending
  1517. if ((
  1518. $this->Mailer == 'sendmail' or $this->Mailer == 'qmail' or $this->Mailer == 'mail'
  1519. )
  1520. and count($this->bcc) > 0
  1521. ) {
  1522. $result .= $this->addrAppend('Bcc', $this->bcc);
  1523. }
  1524. if (count($this->ReplyTo) > 0) {
  1525. $result .= $this->addrAppend('Reply-To', $this->ReplyTo);
  1526. }
  1527. // mail() sets the subject itself
  1528. if ($this->Mailer != 'mail') {
  1529. $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject)));
  1530. }
  1531. if ($this->MessageID != '') {
  1532. $this->lastMessageID = $this->MessageID;
  1533. } else {
  1534. $this->lastMessageID = sprintf("<%s@%s>", $uniq_id, $this->ServerHostname());
  1535. }
  1536. $result .= $this->HeaderLine('Message-ID', $this->lastMessageID);
  1537. $result .= $this->headerLine('X-Priority', $this->Priority);
  1538. if ($this->XMailer == '') {
  1539. $result .= $this->headerLine(
  1540. 'X-Mailer',
  1541. 'PHPMailer ' . $this->Version . ' (https://github.com/PHPMailer/PHPMailer/)'
  1542. );
  1543. } else {
  1544. $myXmailer = trim($this->XMailer);
  1545. if ($myXmailer) {
  1546. $result .= $this->headerLine('X-Mailer', $myXmailer);
  1547. }
  1548. }
  1549. if ($this->ConfirmReadingTo != '') {
  1550. $result .= $this->headerLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>');
  1551. }
  1552. // Add custom headers
  1553. for ($index = 0; $index < count($this->CustomHeader); $index++) {
  1554. $result .= $this->headerLine(
  1555. trim($this->CustomHeader[$index][0]),
  1556. $this->encodeHeader(trim($this->CustomHeader[$index][1]))
  1557. );
  1558. }
  1559. if (!$this->sign_key_file) {
  1560. $result .= $this->headerLine('MIME-Version', '1.0');
  1561. $result .= $this->getMailMIME();
  1562. }
  1563. return $result;
  1564. }
  1565. /**
  1566. * Get the message MIME type headers.
  1567. * @access public
  1568. * @return string
  1569. */
  1570. public function getMailMIME()
  1571. {
  1572. $result = '';
  1573. switch ($this->message_type) {
  1574. case 'inline':
  1575. $result .= $this->headerLine('Content-Type', 'multipart/related;');
  1576. $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
  1577. break;
  1578. case 'attach':
  1579. case 'inline_attach':
  1580. case 'alt_attach':
  1581. case 'alt_inline_attach':
  1582. $result .= $this->headerLine('Content-Type', 'multipart/mixed;');
  1583. $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
  1584. break;
  1585. case 'alt':
  1586. case 'alt_inline':
  1587. $result .= $this->headerLine('Content-Type', 'multipart/alternative;');
  1588. $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
  1589. break;
  1590. default:
  1591. // Catches case 'plain': and case '':
  1592. $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet);
  1593. break;
  1594. }
  1595. //RFC1341 part 5 says 7bit is assumed if not specified
  1596. if ($this->Encoding != '7bit') {
  1597. $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding);
  1598. }
  1599. if ($this->Mailer != 'mail') {
  1600. $result .= $this->LE;
  1601. }
  1602. return $result;
  1603. }
  1604. /**
  1605. * Returns the whole MIME message.
  1606. * Includes complete headers and body.
  1607. * Only valid post PreSend().
  1608. * @see PHPMailer::PreSend()
  1609. * @access public
  1610. * @return string
  1611. */
  1612. public function getSentMIMEMessage()
  1613. {
  1614. return $this->MIMEHeader . $this->mailHeader . self::CRLF . $this->MIMEBody;
  1615. }
  1616. /**
  1617. * Assemble the message body.
  1618. * Returns an empty string on failure.
  1619. * @access public
  1620. * @throws phpmailerException
  1621. * @return string The assembled message body
  1622. */
  1623. public function createBody()
  1624. {
  1625. $body = '';
  1626. if ($this->sign_key_file) {
  1627. $body .= $this->getMailMIME() . $this->LE;
  1628. }
  1629. $this->setWordWrap();
  1630. $bodyEncoding = $this->Encoding;
  1631. $bodyCharSet = $this->CharSet;
  1632. if (!$this->has8bitChars($this->Body)) {
  1633. $bodyEncoding = '7bit';
  1634. $bodyCharSet = 'us-ascii';
  1635. }
  1636. $altBodyEncoding = $this->Encoding;
  1637. $altBodyCharSet = $this->CharSet;
  1638. if (!$this->has8bitChars($this->AltBody)) {
  1639. $altBodyEncoding = '7bit';
  1640. $altBodyCharSet = 'us-ascii';
  1641. }
  1642. switch ($this->message_type) {
  1643. case 'inline':
  1644. $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
  1645. $body .= $this->encodeString($this->Body, $bodyEncoding);
  1646. $body .= $this->LE . $this->LE;
  1647. $body .= $this->attachAll('inline', $this->boundary[1]);
  1648. break;
  1649. case 'attach':
  1650. $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
  1651. $body .= $this->encodeString($this->Body, $bodyEncoding);
  1652. $body .= $this->LE . $this->LE;
  1653. $body .= $this->attachAll('attachment', $this->boundary[1]);
  1654. break;
  1655. case 'inline_attach':
  1656. $body .= $this->textLine('--' . $this->boundary[1]);
  1657. $body .= $this->headerLine('Content-Type', 'multipart/related;');
  1658. $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  1659. $body .= $this->LE;
  1660. $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding);
  1661. $body .= $this->encodeString($this->Body, $bodyEncoding);
  1662. $body .= $this->LE . $this->LE;
  1663. $body .= $this->attachAll('inline', $this->boundary[2]);
  1664. $body .= $this->LE;
  1665. $body .= $this->attachAll('attachment', $this->boundary[1]);
  1666. break;
  1667. case 'alt':
  1668. $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  1669. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  1670. $body .= $this->LE . $this->LE;
  1671. $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, 'text/html', $bodyEncoding);
  1672. $body .= $this->encodeString($this->Body, $bodyEncoding);
  1673. $body .= $this->LE . $this->LE;
  1674. if (!empty($this->Ical)) {
  1675. $body .= $this->getBoundary($this->boundary[1], '', 'text/calendar; method=REQUEST', '');
  1676. $body .= $this->encodeString($this->Ical, $this->Encoding);
  1677. $body .= $this->LE . $this->LE;
  1678. }
  1679. $body .= $this->endBoundary($this->boundary[1]);
  1680. break;
  1681. case 'alt_inline':
  1682. $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  1683. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  1684. $body .= $this->LE . $this->LE;
  1685. $body .= $this->textLine('--' . $this->boundary[1]);
  1686. $body .= $this->headerLine('Content-Type', 'multipart/related;');
  1687. $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  1688. $body .= $this->LE;
  1689. $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
  1690. $body .= $this->encodeString($this->Body, $bodyEncoding);
  1691. $body .= $this->LE . $this->LE;
  1692. $body .= $this->attachAll('inline', $this->boundary[2]);
  1693. $body .= $this->LE;
  1694. $body .= $this->endBoundary($this->boundary[1]);
  1695. break;
  1696. case 'alt_attach':
  1697. $body .= $this->textLine('--' . $this->boundary[1]);
  1698. $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
  1699. $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  1700. $body .= $this->LE;
  1701. $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  1702. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  1703. $body .= $this->LE . $this->LE;
  1704. $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
  1705. $body .= $this->encodeString($this->Body, $bodyEncoding);
  1706. $body .= $this->LE . $this->LE;
  1707. $body .= $this->endBoundary($this->boundary[2]);
  1708. $body .= $this->LE;
  1709. $body .= $this->attachAll('attachment', $this->boundary[1]);
  1710. break;
  1711. case 'alt_inline_attach':
  1712. $body .= $this->textLine('--' . $this->boundary[1]);
  1713. $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
  1714. $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  1715. $body .= $this->LE;
  1716. $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  1717. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  1718. $body .= $this->LE . $this->LE;
  1719. $body .= $this->textLine('--' . $this->boundary[2]);
  1720. $body .= $this->headerLine('Content-Type', 'multipart/related;');
  1721. $body .= $this->textLine("\tboundary=\"" . $this->boundary[3] . '"');
  1722. $body .= $this->LE;
  1723. $body .= $this->getBoundary($this->boundary[3], $bodyCharSet, 'text/html', $bodyEncoding);
  1724. $body .= $this->encodeString($this->Body, $bodyEncoding);
  1725. $body .= $this->LE . $this->LE;
  1726. $body .= $this->attachAll('inline', $this->boundary[3]);
  1727. $body .= $this->LE;
  1728. $body .= $this->endBoundary($this->boundary[2]);
  1729. $body .= $this->LE;
  1730. $body .= $this->attachAll('attachment', $this->boundary[1]);
  1731. break;
  1732. default:
  1733. // catch case 'plain' and case ''
  1734. $body .= $this->encodeString($this->Body, $bodyEncoding);
  1735. break;
  1736. }
  1737. if ($this->isError()) {
  1738. $body = '';
  1739. } elseif ($this->sign_key_file) {
  1740. try {
  1741. if (!defined('PKCS7_TEXT')) {
  1742. throw new phpmailerException($this->lang('signing') . ' OpenSSL extension missing.');
  1743. }
  1744. //TODO would be nice to use php://temp streams here, but need to wrap for PHP < 5.1
  1745. $file = tempnam(sys_get_temp_dir(), 'mail');
  1746. file_put_contents($file, $body); //TODO check this worked
  1747. $signed = tempnam(sys_get_temp_dir(), 'signed');
  1748. if (@openssl_pkcs7_sign(
  1749. $file,
  1750. $signed,
  1751. 'file://' . realpath($this->sign_cert_file),
  1752. array('file://' . realpath($this->sign_key_file), $this->sign_key_pass),
  1753. null
  1754. )
  1755. ) {
  1756. @unlink($file);
  1757. $body = file_get_contents($signed);
  1758. @unlink($signed);
  1759. } else {
  1760. @unlink($file);
  1761. @unlink($signed);
  1762. throw new phpmailerException($this->lang('signing') . openssl_error_string());
  1763. }
  1764. } catch (phpmailerException $e) {
  1765. $body = '';
  1766. if ($this->exceptions) {
  1767. throw $e;
  1768. }
  1769. }
  1770. }
  1771. return $body;
  1772. }
  1773. /**
  1774. * Return the start of a message boundary.
  1775. * @access protected
  1776. * @param string $boundary
  1777. * @param string $charSet
  1778. * @param string $contentType
  1779. * @param string $encoding
  1780. * @return string
  1781. */
  1782. protected function getBoundary($boundary, $charSet, $contentType, $encoding)
  1783. {
  1784. $result = '';
  1785. if ($charSet == '') {
  1786. $charSet = $this->CharSet;
  1787. }
  1788. if ($contentType == '') {
  1789. $contentType = $this->ContentType;
  1790. }
  1791. if ($encoding == '') {
  1792. $encoding = $this->Encoding;
  1793. }
  1794. $result .= $this->textLine('--' . $boundary);
  1795. $result .= sprintf("Content-Type: %s; charset=%s", $contentType, $charSet);
  1796. $result .= $this->LE;
  1797. //RFC1341 part 5 says 7bit is assumed if not specified
  1798. if ($encoding != '7bit') {
  1799. $result .= $this->headerLine('Content-Transfer-Encoding', $encoding);
  1800. }
  1801. $result .= $this->LE;
  1802. return $result;
  1803. }
  1804. /**
  1805. * Return the end of a message boundary.
  1806. * @access protected
  1807. * @param string $boundary
  1808. * @return string
  1809. */
  1810. protected function endBoundary($boundary)
  1811. {
  1812. return $this->LE . '--' . $boundary . '--' . $this->LE;
  1813. }
  1814. /**
  1815. * Set the message type.
  1816. * PHPMailer only supports some preset message types,
  1817. * not arbitrary MIME structures.
  1818. * @access protected
  1819. * @return void
  1820. */
  1821. protected function setMessageType()
  1822. {
  1823. $this->message_type = array();
  1824. if ($this->alternativeExists()) {
  1825. $this->message_type[] = "alt";
  1826. }
  1827. if ($this->inlineImageExists()) {
  1828. $this->message_type[] = "inline";
  1829. }
  1830. if ($this->attachmentExists()) {
  1831. $this->message_type[] = "attach";
  1832. }
  1833. $this->message_type = implode("_", $this->message_type);
  1834. if ($this->message_type == "") {
  1835. $this->message_type = "plain";
  1836. }
  1837. }
  1838. /**
  1839. * Format a header line.
  1840. * @access public
  1841. * @param string $name
  1842. * @param string $value
  1843. * @return string
  1844. */
  1845. public function headerLine($name, $value)
  1846. {
  1847. return $name . ': ' . $value . $this->LE;
  1848. }
  1849. /**
  1850. * Return a formatted mail line.
  1851. * @access public
  1852. * @param string $value
  1853. * @return string
  1854. */
  1855. public function textLine($value)
  1856. {
  1857. return $value . $this->LE;
  1858. }
  1859. /**
  1860. * Add an attachment from a path on the filesystem.
  1861. * Returns false if the file could not be found or read.
  1862. * @param string $path Path to the attachment.
  1863. * @param string $name Overrides the attachment name.
  1864. * @param string $encoding File encoding (see $Encoding).
  1865. * @param string $type File extension (MIME) type.
  1866. * @param string $disposition Disposition to use
  1867. * @throws phpmailerException
  1868. * @return bool
  1869. */
  1870. public function addAttachment($path, $name = '', $encoding = 'base64', $type = '', $disposition = 'attachment')
  1871. {
  1872. try {
  1873. if (!@is_file($path)) {
  1874. throw new phpmailerException($this->lang('file_access') . $path, self::STOP_CONTINUE);
  1875. }
  1876. //If a MIME type is not specified, try to work it out from the file name
  1877. if ($type == '') {
  1878. $type = self::filenameToType($path);
  1879. }
  1880. $filename = basename($path);
  1881. if ($name == '') {
  1882. $name = $filename;
  1883. }
  1884. $this->attachment[] = array(
  1885. 0 => $path,
  1886. 1 => $filename,
  1887. 2 => $name,
  1888. 3 => $encoding,
  1889. 4 => $type,
  1890. 5 => false, // isStringAttachment
  1891. 6 => $disposition,
  1892. 7 => 0
  1893. );
  1894. } catch (phpmailerException $e) {
  1895. $this->setError($e->getMessage());
  1896. $this->edebug($e->getMessage());
  1897. if ($this->exceptions) {
  1898. throw $e;
  1899. }
  1900. return false;
  1901. }
  1902. return true;
  1903. }
  1904. /**
  1905. * Return the array of attachments.
  1906. * @return array
  1907. */
  1908. public function getAttachments()
  1909. {
  1910. return $this->attachment;
  1911. }
  1912. /**
  1913. * Attach all file, string, and binary attachments to the message.
  1914. * Returns an empty string on failure.
  1915. * @access protected
  1916. * @param string $disposition_type
  1917. * @param string $boundary
  1918. * @return string
  1919. */
  1920. protected function attachAll($disposition_type, $boundary)
  1921. {
  1922. // Return text of body
  1923. $mime = array();
  1924. $cidUniq = array();
  1925. $incl = array();
  1926. // Add all attachments
  1927. foreach ($this->attachment as $attachment) {
  1928. // Check if it is a valid disposition_filter
  1929. if ($attachment[6] == $disposition_type) {
  1930. // Check for string attachment
  1931. $string = '';
  1932. $path = '';
  1933. $bString = $attachment[5];
  1934. if ($bString) {
  1935. $string = $attachment[0];
  1936. } else {
  1937. $path = $attachment[0];
  1938. }
  1939. $inclhash = md5(serialize($attachment));
  1940. if (in_array($inclhash, $incl)) {
  1941. continue;
  1942. }
  1943. $incl[] = $inclhash;
  1944. $name = $attachment[2];
  1945. $encoding = $attachment[3];
  1946. $type = $attachment[4];
  1947. $disposition = $attachment[6];
  1948. $cid = $attachment[7];
  1949. if ($disposition == 'inline' && isset($cidUniq[$cid])) {
  1950. continue;
  1951. }
  1952. $cidUniq[$cid] = true;
  1953. $mime[] = sprintf("--%s%s", $boundary, $this->LE);
  1954. $mime[] = sprintf(
  1955. "Content-Type: %s; name=\"%s\"%s",
  1956. $type,
  1957. $this->encodeHeader($this->secureHeader($name)),
  1958. $this->LE
  1959. );
  1960. //RFC1341 part 5 says 7bit is assumed if not specified
  1961. if ($encoding != '7bit') {
  1962. $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE);
  1963. }
  1964. if ($disposition == 'inline') {
  1965. $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE);
  1966. }
  1967. // If a filename contains any of these chars, it should be quoted,
  1968. // but not otherwise: RFC2183 & RFC2045 5.1
  1969. // Fixes a warning in IETF's msglint MIME checker
  1970. // Allow for bypassing the Content-Disposition header totally
  1971. if (!(empty($disposition))) {
  1972. if (preg_match('/[ \(\)<>@,;:\\"\/\[\]\?=]/', $name)) {
  1973. $mime[] = sprintf(
  1974. "Content-Disposition: %s; filename=\"%s\"%s",
  1975. $disposition,
  1976. $this->encodeHeader($this->secureHeader($name)),
  1977. $this->LE . $this->LE
  1978. );
  1979. } else {
  1980. $mime[] = sprintf(
  1981. "Content-Disposition: %s; filename=%s%s",
  1982. $disposition,
  1983. $this->encodeHeader($this->secureHeader($name)),
  1984. $this->LE . $this->LE
  1985. );
  1986. }
  1987. } else {
  1988. $mime[] = $this->LE;
  1989. }
  1990. // Encode as string attachment
  1991. if ($bString) {
  1992. $mime[] = $this->encodeString($string, $encoding);
  1993. if ($this->isError()) {
  1994. return '';
  1995. }
  1996. $mime[] = $this->LE . $this->LE;
  1997. } else {
  1998. $mime[] = $this->encodeFile($path, $encoding);
  1999. if ($this->isError()) {
  2000. return '';
  2001. }
  2002. $mime[] = $this->LE . $this->LE;
  2003. }
  2004. }
  2005. }
  2006. $mime[] = sprintf("--%s--%s", $boundary, $this->LE);
  2007. return implode("", $mime);
  2008. }
  2009. /**
  2010. * Encode a file attachment in requested format.
  2011. * Returns an empty string on failure.
  2012. * @param string $path The full path to the file
  2013. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  2014. * @throws phpmailerException
  2015. * @see EncodeFile(encodeFile
  2016. * @access protected
  2017. * @return string
  2018. */
  2019. protected function encodeFile($path, $encoding = 'base64')
  2020. {
  2021. try {
  2022. if (!is_readable($path)) {
  2023. throw new phpmailerException($this->lang('file_open') . $path, self::STOP_CONTINUE);
  2024. }
  2025. $magic_quotes = get_magic_quotes_runtime();
  2026. if ($magic_quotes) {
  2027. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  2028. set_magic_quotes_runtime(0);
  2029. } else {
  2030. ini_set('magic_quotes_runtime', 0);
  2031. }
  2032. }
  2033. $file_buffer = file_get_contents($path);
  2034. $file_buffer = $this->encodeString($file_buffer, $encoding);
  2035. if ($magic_quotes) {
  2036. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  2037. set_magic_quotes_runtime($magic_quotes);
  2038. } else {
  2039. ini_set('magic_quotes_runtime', $magic_quotes);
  2040. }
  2041. }
  2042. return $file_buffer;
  2043. } catch (Exception $e) {
  2044. $this->setError($e->getMessage());
  2045. return '';
  2046. }
  2047. }
  2048. /**
  2049. * Encode a string in requested format.
  2050. * Returns an empty string on failure.
  2051. * @param string $str The text to encode
  2052. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  2053. * @access public
  2054. * @return string
  2055. */
  2056. public function encodeString($str, $encoding = 'base64')
  2057. {
  2058. $encoded = '';
  2059. switch (strtolower($encoding)) {
  2060. case 'base64':
  2061. $encoded = chunk_split(base64_encode($str), 76, $this->LE);
  2062. break;
  2063. case '7bit':
  2064. case '8bit':
  2065. $encoded = $this->fixEOL($str);
  2066. //Make sure it ends with a line break
  2067. if (substr($encoded, -(strlen($this->LE))) != $this->LE) {
  2068. $encoded .= $this->LE;
  2069. }
  2070. break;
  2071. case 'binary':
  2072. $encoded = $str;
  2073. break;
  2074. case 'quoted-printable':
  2075. $encoded = $this->encodeQP($str);
  2076. break;
  2077. default:
  2078. $this->setError($this->lang('encoding') . $encoding);
  2079. break;
  2080. }
  2081. return $encoded;
  2082. }
  2083. /**
  2084. * Encode a header string optimally.
  2085. * Picks shortest of Q, B, quoted-printable or none.
  2086. * @access public
  2087. * @param string $str
  2088. * @param string $position
  2089. * @return string
  2090. */
  2091. public function encodeHeader($str, $position = 'text')
  2092. {
  2093. $x = 0;
  2094. switch (strtolower($position)) {
  2095. case 'phrase':
  2096. if (!preg_match('/[\200-\377]/', $str)) {
  2097. // Can't use addslashes as we don't know the value of magic_quotes_sybase
  2098. $encoded = addcslashes($str, "\0..\37\177\\\"");
  2099. if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
  2100. return ($encoded);
  2101. } else {
  2102. return ("\"$encoded\"");
  2103. }
  2104. }
  2105. $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
  2106. break;
  2107. /** @noinspection PhpMissingBreakStatementInspection */
  2108. case 'comment':
  2109. $x = preg_match_all('/[()"]/', $str, $matches);
  2110. // Intentional fall-through
  2111. case 'text':
  2112. default:
  2113. $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
  2114. break;
  2115. }
  2116. if ($x == 0) { //There are no chars that need encoding
  2117. return ($str);
  2118. }
  2119. $maxlen = 75 - 7 - strlen($this->CharSet);
  2120. // Try to select the encoding which should produce the shortest output
  2121. if ($x > strlen($str) / 3) {
  2122. //More than a third of the content will need encoding, so B encoding will be most efficient
  2123. $encoding = 'B';
  2124. if (function_exists('mb_strlen') && $this->hasMultiBytes($str)) {
  2125. // Use a custom function which correctly encodes and wraps long
  2126. // multibyte strings without breaking lines within a character
  2127. $encoded = $this->base64EncodeWrapMB($str, "\n");
  2128. } else {
  2129. $encoded = base64_encode($str);
  2130. $maxlen -= $maxlen % 4;
  2131. $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
  2132. }
  2133. } else {
  2134. $encoding = 'Q';
  2135. $encoded = $this->encodeQ($str, $position);
  2136. $encoded = $this->wrapText($encoded, $maxlen, true);
  2137. $encoded = str_replace('=' . self::CRLF, "\n", trim($encoded));
  2138. }
  2139. $encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet . "?$encoding?\\1?=", $encoded);
  2140. $encoded = trim(str_replace("\n", $this->LE, $encoded));
  2141. return $encoded;
  2142. }
  2143. /**
  2144. * Check if a string contains multi-byte characters.
  2145. * @access public
  2146. * @param string $str multi-byte text to wrap encode
  2147. * @return bool
  2148. */
  2149. public function hasMultiBytes($str)
  2150. {
  2151. if (function_exists('mb_strlen')) {
  2152. return (strlen($str) > mb_strlen($str, $this->CharSet));
  2153. } else { // Assume no multibytes (we can't handle without mbstring functions anyway)
  2154. return false;
  2155. }
  2156. }
  2157. /**
  2158. * Does a string contain any 8-bit chars (in any charset)?
  2159. * @param string $text
  2160. * @return bool
  2161. */
  2162. public function has8bitChars($text) {
  2163. return (bool)preg_match('/[\x80-\xFF]/', $text);
  2164. }
  2165. /**
  2166. * Encode and wrap long multibyte strings for mail headers
  2167. * without breaking lines within a character.
  2168. * Adapted from a function by paravoid
  2169. * @link http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283
  2170. * @access public
  2171. * @param string $str multi-byte text to wrap encode
  2172. * @param string $lf string to use as linefeed/end-of-line
  2173. * @return string
  2174. */
  2175. public function base64EncodeWrapMB($str, $lf = null)
  2176. {
  2177. $start = "=?" . $this->CharSet . "?B?";
  2178. $end = "?=";
  2179. $encoded = "";
  2180. if ($lf === null) {
  2181. $lf = $this->LE;
  2182. }
  2183. $mb_length = mb_strlen($str, $this->CharSet);
  2184. // Each line must have length <= 75, including $start and $end
  2185. $length = 75 - strlen($start) - strlen($end);
  2186. // Average multi-byte ratio
  2187. $ratio = $mb_length / strlen($str);
  2188. // Base64 has a 4:3 ratio
  2189. $avgLength = floor($length * $ratio * .75);
  2190. for ($i = 0; $i < $mb_length; $i += $offset) {
  2191. $lookBack = 0;
  2192. do {
  2193. $offset = $avgLength - $lookBack;
  2194. $chunk = mb_substr($str, $i, $offset, $this->CharSet);
  2195. $chunk = base64_encode($chunk);
  2196. $lookBack++;
  2197. } while (strlen($chunk) > $length);
  2198. $encoded .= $chunk . $lf;
  2199. }
  2200. // Chomp the last linefeed
  2201. $encoded = substr($encoded, 0, -strlen($lf));
  2202. return $encoded;
  2203. }
  2204. /**
  2205. * Encode a string in quoted-printable format.
  2206. * According to RFC2045 section 6.7.
  2207. * @access public
  2208. * @param string $string The text to encode
  2209. * @param integer $line_max Number of chars allowed on a line before wrapping
  2210. * @return string
  2211. * @link PHP version adapted from http://www.php.net/manual/en/function.quoted-printable-decode.php#89417
  2212. */
  2213. public function encodeQP($string, $line_max = 76)
  2214. {
  2215. if (function_exists('quoted_printable_encode')) { //Use native function if it's available (>= PHP5.3)
  2216. return $this->fixEOL(quoted_printable_encode($string));
  2217. }
  2218. //Fall back to a pure PHP implementation
  2219. $string = str_replace(
  2220. array('%20', '%0D%0A.', '%0D%0A', '%'),
  2221. array(' ', "\r\n=2E", "\r\n", '='),
  2222. rawurlencode($string)
  2223. );
  2224. $string = preg_replace('/[^\r\n]{' . ($line_max - 3) . '}[^=\r\n]{2}/', "$0=\r\n", $string);
  2225. return $this->fixEOL($string);
  2226. }
  2227. /**
  2228. * Backward compatibility wrapper for an old QP encoding function that was removed.
  2229. * @see PHPMailer::encodeQP()
  2230. * @access public
  2231. * @param string $string
  2232. * @param integer $line_max
  2233. * @param bool $space_conv
  2234. * @return string
  2235. * @deprecated Use encodeQP instead.
  2236. */
  2237. public function encodeQPphp(
  2238. $string,
  2239. $line_max = 76,
  2240. /** @noinspection PhpUnusedParameterInspection */ $space_conv = false
  2241. ) {
  2242. return $this->encodeQP($string, $line_max);
  2243. }
  2244. /**
  2245. * Encode a string using Q encoding.
  2246. * @link http://tools.ietf.org/html/rfc2047
  2247. * @param string $str the text to encode
  2248. * @param string $position Where the text is going to be used, see the RFC for what that means
  2249. * @access public
  2250. * @return string
  2251. */
  2252. public function encodeQ($str, $position = 'text')
  2253. {
  2254. //There should not be any EOL in the string
  2255. $pattern = '';
  2256. $encoded = str_replace(array("\r", "\n"), '', $str);
  2257. switch (strtolower($position)) {
  2258. case 'phrase':
  2259. //RFC 2047 section 5.3
  2260. $pattern = '^A-Za-z0-9!*+\/ -';
  2261. break;
  2262. /** @noinspection PhpMissingBreakStatementInspection */
  2263. case 'comment':
  2264. //RFC 2047 section 5.2
  2265. $pattern = '\(\)"';
  2266. //intentional fall-through
  2267. //for this reason we build the $pattern without including delimiters and []
  2268. case 'text':
  2269. default:
  2270. //RFC 2047 section 5.1
  2271. //Replace every high ascii, control, =, ? and _ characters
  2272. $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern;
  2273. break;
  2274. }
  2275. $matches = array();
  2276. if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
  2277. //If the string contains an '=', make sure it's the first thing we replace
  2278. //so as to avoid double-encoding
  2279. $s = array_search('=', $matches[0]);
  2280. if ($s !== false) {
  2281. unset($matches[0][$s]);
  2282. array_unshift($matches[0], '=');
  2283. }
  2284. foreach (array_unique($matches[0]) as $char) {
  2285. $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
  2286. }
  2287. }
  2288. //Replace every spaces to _ (more readable than =20)
  2289. return str_replace(' ', '_', $encoded);
  2290. }
  2291. /**
  2292. * Add a string or binary attachment (non-filesystem).
  2293. * This method can be used to attach ascii or binary data,
  2294. * such as a BLOB record from a database.
  2295. * @param string $string String attachment data.
  2296. * @param string $filename Name of the attachment.
  2297. * @param string $encoding File encoding (see $Encoding).
  2298. * @param string $type File extension (MIME) type.
  2299. * @param string $disposition Disposition to use
  2300. * @return void
  2301. */
  2302. public function addStringAttachment(
  2303. $string,
  2304. $filename,
  2305. $encoding = 'base64',
  2306. $type = '',
  2307. $disposition = 'attachment'
  2308. ) {
  2309. //If a MIME type is not specified, try to work it out from the file name
  2310. if ($type == '') {
  2311. $type = self::filenameToType($filename);
  2312. }
  2313. // Append to $attachment array
  2314. $this->attachment[] = array(
  2315. 0 => $string,
  2316. 1 => $filename,
  2317. 2 => basename($filename),
  2318. 3 => $encoding,
  2319. 4 => $type,
  2320. 5 => true, // isStringAttachment
  2321. 6 => $disposition,
  2322. 7 => 0
  2323. );
  2324. }
  2325. /**
  2326. * Add an embedded (inline) attachment from a file.
  2327. * This can include images, sounds, and just about any other document type.
  2328. * These differ from 'regular' attachmants in that they are intended to be
  2329. * displayed inline with the message, not just attached for download.
  2330. * This is used in HTML messages that embed the images
  2331. * the HTML refers to using the $cid value.
  2332. * @param string $path Path to the attachment.
  2333. * @param string $cid Content ID of the attachment; Use this to reference
  2334. * the content when using an embedded image in HTML.
  2335. * @param string $name Overrides the attachment name.
  2336. * @param string $encoding File encoding (see $Encoding).
  2337. * @param string $type File MIME type.
  2338. * @param string $disposition Disposition to use
  2339. * @return bool True on successfully adding an attachment
  2340. */
  2341. public function addEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline')
  2342. {
  2343. if (!@is_file($path)) {
  2344. $this->setError($this->lang('file_access') . $path);
  2345. return false;
  2346. }
  2347. //If a MIME type is not specified, try to work it out from the file name
  2348. if ($type == '') {
  2349. $type = self::filenameToType($path);
  2350. }
  2351. $filename = basename($path);
  2352. if ($name == '') {
  2353. $name = $filename;
  2354. }
  2355. // Append to $attachment array
  2356. $this->attachment[] = array(
  2357. 0 => $path,
  2358. 1 => $filename,
  2359. 2 => $name,
  2360. 3 => $encoding,
  2361. 4 => $type,
  2362. 5 => false, // isStringAttachment
  2363. 6 => $disposition,
  2364. 7 => $cid
  2365. );
  2366. return true;
  2367. }
  2368. /**
  2369. * Add an embedded stringified attachment.
  2370. * This can include images, sounds, and just about any other document type.
  2371. * Be sure to set the $type to an image type for images:
  2372. * JPEG images use 'image/jpeg', GIF uses 'image/gif', PNG uses 'image/png'.
  2373. * @param string $string The attachment binary data.
  2374. * @param string $cid Content ID of the attachment; Use this to reference
  2375. * the content when using an embedded image in HTML.
  2376. * @param string $name
  2377. * @param string $encoding File encoding (see $Encoding).
  2378. * @param string $type MIME type.
  2379. * @param string $disposition Disposition to use
  2380. * @return bool True on successfully adding an attachment
  2381. */
  2382. public function addStringEmbeddedImage(
  2383. $string,
  2384. $cid,
  2385. $name = '',
  2386. $encoding = 'base64',
  2387. $type = '',
  2388. $disposition = 'inline'
  2389. ) {
  2390. //If a MIME type is not specified, try to work it out from the name
  2391. if ($type == '') {
  2392. $type = self::filenameToType($name);
  2393. }
  2394. // Append to $attachment array
  2395. $this->attachment[] = array(
  2396. 0 => $string,
  2397. 1 => $name,
  2398. 2 => $name,
  2399. 3 => $encoding,
  2400. 4 => $type,
  2401. 5 => true, // isStringAttachment
  2402. 6 => $disposition,
  2403. 7 => $cid
  2404. );
  2405. return true;
  2406. }
  2407. /**
  2408. * Check if an inline attachment is present.
  2409. * @access public
  2410. * @return bool
  2411. */
  2412. public function inlineImageExists()
  2413. {
  2414. foreach ($this->attachment as $attachment) {
  2415. if ($attachment[6] == 'inline') {
  2416. return true;
  2417. }
  2418. }
  2419. return false;
  2420. }
  2421. /**
  2422. * Check if an attachment (non-inline) is present.
  2423. * @return bool
  2424. */
  2425. public function attachmentExists()
  2426. {
  2427. foreach ($this->attachment as $attachment) {
  2428. if ($attachment[6] == 'attachment') {
  2429. return true;
  2430. }
  2431. }
  2432. return false;
  2433. }
  2434. /**
  2435. * Check if this message has an alternative body set.
  2436. * @return bool
  2437. */
  2438. public function alternativeExists()
  2439. {
  2440. return !empty($this->AltBody);
  2441. }
  2442. /**
  2443. * Clear all To recipients.
  2444. * @return void
  2445. */
  2446. public function clearAddresses()
  2447. {
  2448. foreach ($this->to as $to) {
  2449. unset($this->all_recipients[strtolower($to[0])]);
  2450. }
  2451. $this->to = array();
  2452. }
  2453. /**
  2454. * Clear all CC recipients.
  2455. * @return void
  2456. */
  2457. public function clearCCs()
  2458. {
  2459. foreach ($this->cc as $cc) {
  2460. unset($this->all_recipients[strtolower($cc[0])]);
  2461. }
  2462. $this->cc = array();
  2463. }
  2464. /**
  2465. * Clear all BCC recipients.
  2466. * @return void
  2467. */
  2468. public function clearBCCs()
  2469. {
  2470. foreach ($this->bcc as $bcc) {
  2471. unset($this->all_recipients[strtolower($bcc[0])]);
  2472. }
  2473. $this->bcc = array();
  2474. }
  2475. /**
  2476. * Clear all ReplyTo recipients.
  2477. * @return void
  2478. */
  2479. public function clearReplyTos()
  2480. {
  2481. $this->ReplyTo = array();
  2482. }
  2483. /**
  2484. * Clear all recipient types.
  2485. * @return void
  2486. */
  2487. public function clearAllRecipients()
  2488. {
  2489. $this->to = array();
  2490. $this->cc = array();
  2491. $this->bcc = array();
  2492. $this->all_recipients = array();
  2493. }
  2494. /**
  2495. * Clear all filesystem, string, and binary attachments.
  2496. * @return void
  2497. */
  2498. public function clearAttachments()
  2499. {
  2500. $this->attachment = array();
  2501. }
  2502. /**
  2503. * Clear all custom headers.
  2504. * @return void
  2505. */
  2506. public function clearCustomHeaders()
  2507. {
  2508. $this->CustomHeader = array();
  2509. }
  2510. /**
  2511. * Add an error message to the error container.
  2512. * @access protected
  2513. * @param string $msg
  2514. * @return void
  2515. */
  2516. protected function setError($msg)
  2517. {
  2518. $this->error_count++;
  2519. if ($this->Mailer == 'smtp' and !is_null($this->smtp)) {
  2520. $lasterror = $this->smtp->getError();
  2521. if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) {
  2522. $msg .= '<p>' . $this->lang('smtp_error') . $lasterror['smtp_msg'] . "</p>\n";
  2523. }
  2524. }
  2525. $this->ErrorInfo = $msg;
  2526. }
  2527. /**
  2528. * Return an RFC 822 formatted date.
  2529. * @access public
  2530. * @return string
  2531. * @static
  2532. */
  2533. public static function rfcDate()
  2534. {
  2535. //Set the time zone to whatever the default is to avoid 500 errors
  2536. //Will default to UTC if it's not set properly in php.ini
  2537. date_default_timezone_set(@date_default_timezone_get());
  2538. return date('D, j M Y H:i:s O');
  2539. }
  2540. /**
  2541. * Get the server hostname.
  2542. * Returns 'localhost.localdomain' if unknown.
  2543. * @access protected
  2544. * @return string
  2545. */
  2546. protected function serverHostname()
  2547. {
  2548. $result = 'localhost.localdomain';
  2549. if (!empty($this->Hostname)) {
  2550. $result = $this->Hostname;
  2551. } elseif (isset($_SERVER) and array_key_exists('SERVER_NAME', $_SERVER) and !empty($_SERVER['SERVER_NAME'])) {
  2552. $result = $_SERVER['SERVER_NAME'];
  2553. } elseif (function_exists('gethostname') && gethostname() !== false) {
  2554. $result = gethostname();
  2555. } elseif (php_uname('n') !== false) {
  2556. $result = php_uname('n');
  2557. }
  2558. return $result;
  2559. }
  2560. /**
  2561. * Get an error message in the current language.
  2562. * @access protected
  2563. * @param string $key
  2564. * @return string
  2565. */
  2566. protected function lang($key)
  2567. {
  2568. if (count($this->language) < 1) {
  2569. $this->setLanguage('en'); // set the default language
  2570. }
  2571. if (isset($this->language[$key])) {
  2572. return $this->language[$key];
  2573. } else {
  2574. return 'Language string failed to load: ' . $key;
  2575. }
  2576. }
  2577. /**
  2578. * Check if an error occurred.
  2579. * @access public
  2580. * @return bool True if an error did occur.
  2581. */
  2582. public function isError()
  2583. {
  2584. return ($this->error_count > 0);
  2585. }
  2586. /**
  2587. * Ensure consistent line endings in a string.
  2588. * Changes every end of line from CRLF, CR or LF to $this->LE.
  2589. * @access public
  2590. * @param string $str String to fixEOL
  2591. * @return string
  2592. */
  2593. public function fixEOL($str)
  2594. {
  2595. // Normalise to \n
  2596. $nstr = str_replace(array("\r\n", "\r"), "\n", $str);
  2597. // Now convert LE as needed
  2598. if ($this->LE !== "\n") {
  2599. $nstr = str_replace("\n", $this->LE, $nstr);
  2600. }
  2601. return $nstr;
  2602. }
  2603. /**
  2604. * Add a custom header.
  2605. * $name value can be overloaded to contain
  2606. * both header name and value (name:value)
  2607. * @access public
  2608. * @param string $name Custom header name
  2609. * @param string $value Header value
  2610. * @return void
  2611. */
  2612. public function addCustomHeader($name, $value = null)
  2613. {
  2614. if ($value === null) {
  2615. // Value passed in as name:value
  2616. $this->CustomHeader[] = explode(':', $name, 2);
  2617. } else {
  2618. $this->CustomHeader[] = array($name, $value);
  2619. }
  2620. }
  2621. /**
  2622. * Create a message from an HTML string.
  2623. * Automatically makes modifications for inline images and backgrounds
  2624. * and creates a plain-text version by converting the HTML.
  2625. * Overwrites any existing values in $this->Body and $this->AltBody
  2626. * @access public
  2627. * @param string $message HTML message string
  2628. * @param string $basedir baseline directory for path
  2629. * @param bool $advanced Whether to use the advanced HTML to text converter
  2630. * @return string $message
  2631. */
  2632. public function msgHTML($message, $basedir = '', $advanced = false)
  2633. {
  2634. preg_match_all("/(src|background)=[\"'](.*)[\"']/Ui", $message, $images);
  2635. if (isset($images[2])) {
  2636. foreach ($images[2] as $i => $url) {
  2637. // do not change urls for absolute images (thanks to corvuscorax)
  2638. if (!preg_match('#^[A-z]+://#', $url)) {
  2639. $filename = basename($url);
  2640. $directory = dirname($url);
  2641. if ($directory == '.') {
  2642. $directory = '';
  2643. }
  2644. $cid = md5($url) . '@phpmailer.0'; //RFC2392 S 2
  2645. if (strlen($basedir) > 1 && substr($basedir, -1) != '/') {
  2646. $basedir .= '/';
  2647. }
  2648. if (strlen($directory) > 1 && substr($directory, -1) != '/') {
  2649. $directory .= '/';
  2650. }
  2651. if ($this->addEmbeddedImage(
  2652. $basedir . $directory . $filename,
  2653. $cid,
  2654. $filename,
  2655. 'base64',
  2656. self::_mime_types(self::mb_pathinfo($filename, PATHINFO_EXTENSION))
  2657. )
  2658. ) {
  2659. $message = preg_replace(
  2660. "/" . $images[1][$i] . "=[\"']" . preg_quote($url, '/') . "[\"']/Ui",
  2661. $images[1][$i] . "=\"cid:" . $cid . "\"",
  2662. $message
  2663. );
  2664. }
  2665. }
  2666. }
  2667. }
  2668. $this->isHTML(true);
  2669. //Convert all message body line breaks to CRLF, makes quoted-printable encoding work much better
  2670. $this->Body = $this->normalizeBreaks($message);
  2671. $this->AltBody = $this->normalizeBreaks($this->html2text($message, $advanced));
  2672. if (empty($this->AltBody)) {
  2673. $this->AltBody = 'To view this email message, open it in a program that understands HTML!' .
  2674. self::CRLF . self::CRLF;
  2675. }
  2676. return $this->Body;
  2677. }
  2678. /**
  2679. * Convert an HTML string into plain text.
  2680. * @param string $html The HTML text to convert
  2681. * @param bool $advanced Should this use the more complex html2text converter or just a simple one?
  2682. * @return string
  2683. */
  2684. public function html2text($html, $advanced = false)
  2685. {
  2686. if ($advanced) {
  2687. require_once 'extras/class.html2text.php';
  2688. $h = new html2text($html);
  2689. return $h->get_text();
  2690. }
  2691. return html_entity_decode(
  2692. trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))),
  2693. ENT_QUOTES,
  2694. $this->CharSet
  2695. );
  2696. }
  2697. /**
  2698. * Get the MIME type for a file extension.
  2699. * @param string $ext File extension
  2700. * @access public
  2701. * @return string MIME type of file.
  2702. * @static
  2703. */
  2704. public static function _mime_types($ext = '')
  2705. {
  2706. $mimes = array(
  2707. 'xl' => 'application/excel',
  2708. 'hqx' => 'application/mac-binhex40',
  2709. 'cpt' => 'application/mac-compactpro',
  2710. 'bin' => 'application/macbinary',
  2711. 'doc' => 'application/msword',
  2712. 'word' => 'application/msword',
  2713. 'class' => 'application/octet-stream',
  2714. 'dll' => 'application/octet-stream',
  2715. 'dms' => 'application/octet-stream',
  2716. 'exe' => 'application/octet-stream',
  2717. 'lha' => 'application/octet-stream',
  2718. 'lzh' => 'application/octet-stream',
  2719. 'psd' => 'application/octet-stream',
  2720. 'sea' => 'application/octet-stream',
  2721. 'so' => 'application/octet-stream',
  2722. 'oda' => 'application/oda',
  2723. 'pdf' => 'application/pdf',
  2724. 'ai' => 'application/postscript',
  2725. 'eps' => 'application/postscript',
  2726. 'ps' => 'application/postscript',
  2727. 'smi' => 'application/smil',
  2728. 'smil' => 'application/smil',
  2729. 'mif' => 'application/vnd.mif',
  2730. 'xls' => 'application/vnd.ms-excel',
  2731. 'ppt' => 'application/vnd.ms-powerpoint',
  2732. 'wbxml' => 'application/vnd.wap.wbxml',
  2733. 'wmlc' => 'application/vnd.wap.wmlc',
  2734. 'dcr' => 'application/x-director',
  2735. 'dir' => 'application/x-director',
  2736. 'dxr' => 'application/x-director',
  2737. 'dvi' => 'application/x-dvi',
  2738. 'gtar' => 'application/x-gtar',
  2739. 'php3' => 'application/x-httpd-php',
  2740. 'php4' => 'application/x-httpd-php',
  2741. 'php' => 'application/x-httpd-php',
  2742. 'phtml' => 'application/x-httpd-php',
  2743. 'phps' => 'application/x-httpd-php-source',
  2744. 'js' => 'application/x-javascript',
  2745. 'swf' => 'application/x-shockwave-flash',
  2746. 'sit' => 'application/x-stuffit',
  2747. 'tar' => 'application/x-tar',
  2748. 'tgz' => 'application/x-tar',
  2749. 'xht' => 'application/xhtml+xml',
  2750. 'xhtml' => 'application/xhtml+xml',
  2751. 'zip' => 'application/zip',
  2752. 'mid' => 'audio/midi',
  2753. 'midi' => 'audio/midi',
  2754. 'mp2' => 'audio/mpeg',
  2755. 'mp3' => 'audio/mpeg',
  2756. 'mpga' => 'audio/mpeg',
  2757. 'aif' => 'audio/x-aiff',
  2758. 'aifc' => 'audio/x-aiff',
  2759. 'aiff' => 'audio/x-aiff',
  2760. 'ram' => 'audio/x-pn-realaudio',
  2761. 'rm' => 'audio/x-pn-realaudio',
  2762. 'rpm' => 'audio/x-pn-realaudio-plugin',
  2763. 'ra' => 'audio/x-realaudio',
  2764. 'wav' => 'audio/x-wav',
  2765. 'bmp' => 'image/bmp',
  2766. 'gif' => 'image/gif',
  2767. 'jpeg' => 'image/jpeg',
  2768. 'jpe' => 'image/jpeg',
  2769. 'jpg' => 'image/jpeg',
  2770. 'png' => 'image/png',
  2771. 'tiff' => 'image/tiff',
  2772. 'tif' => 'image/tiff',
  2773. 'eml' => 'message/rfc822',
  2774. 'css' => 'text/css',
  2775. 'html' => 'text/html',
  2776. 'htm' => 'text/html',
  2777. 'shtml' => 'text/html',
  2778. 'log' => 'text/plain',
  2779. 'text' => 'text/plain',
  2780. 'txt' => 'text/plain',
  2781. 'rtx' => 'text/richtext',
  2782. 'rtf' => 'text/rtf',
  2783. 'xml' => 'text/xml',
  2784. 'xsl' => 'text/xml',
  2785. 'mpeg' => 'video/mpeg',
  2786. 'mpe' => 'video/mpeg',
  2787. 'mpg' => 'video/mpeg',
  2788. 'mov' => 'video/quicktime',
  2789. 'qt' => 'video/quicktime',
  2790. 'rv' => 'video/vnd.rn-realvideo',
  2791. 'avi' => 'video/x-msvideo',
  2792. 'movie' => 'video/x-sgi-movie'
  2793. );
  2794. return (array_key_exists(strtolower($ext), $mimes) ? $mimes[strtolower($ext)]: 'application/octet-stream');
  2795. }
  2796. /**
  2797. * Map a file name to a MIME type.
  2798. * Defaults to 'application/octet-stream', i.e.. arbitrary binary data.
  2799. * @param string $filename A file name or full path, does not need to exist as a file
  2800. * @return string
  2801. * @static
  2802. */
  2803. public static function filenameToType($filename)
  2804. {
  2805. //In case the path is a URL, strip any query string before getting extension
  2806. $qpos = strpos($filename, '?');
  2807. if ($qpos !== false) {
  2808. $filename = substr($filename, 0, $qpos);
  2809. }
  2810. $pathinfo = self::mb_pathinfo($filename);
  2811. return self::_mime_types($pathinfo['extension']);
  2812. }
  2813. /**
  2814. * Multi-byte-safe pathinfo replacement.
  2815. * Drop-in replacement for pathinfo(), but multibyte-safe, cross-platform-safe, old-version-safe.
  2816. * Works similarly to the one in PHP >= 5.2.0
  2817. * @link http://www.php.net/manual/en/function.pathinfo.php#107461
  2818. * @param string $path A filename or path, does not need to exist as a file
  2819. * @param integer|string $options Either a PATHINFO_* constant,
  2820. * or a string name to return only the specified piece, allows 'filename' to work on PHP < 5.2
  2821. * @return string|array
  2822. * @static
  2823. */
  2824. public static function mb_pathinfo($path, $options = null)
  2825. {
  2826. $ret = array('dirname' => '', 'basename' => '', 'extension' => '', 'filename' => '');
  2827. $m = array();
  2828. preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', $path, $m);
  2829. if (array_key_exists(1, $m)) {
  2830. $ret['dirname'] = $m[1];
  2831. }
  2832. if (array_key_exists(2, $m)) {
  2833. $ret['basename'] = $m[2];
  2834. }
  2835. if (array_key_exists(5, $m)) {
  2836. $ret['extension'] = $m[5];
  2837. }
  2838. if (array_key_exists(3, $m)) {
  2839. $ret['filename'] = $m[3];
  2840. }
  2841. switch ($options) {
  2842. case PATHINFO_DIRNAME:
  2843. case 'dirname':
  2844. return $ret['dirname'];
  2845. break;
  2846. case PATHINFO_BASENAME:
  2847. case 'basename':
  2848. return $ret['basename'];
  2849. break;
  2850. case PATHINFO_EXTENSION:
  2851. case 'extension':
  2852. return $ret['extension'];
  2853. break;
  2854. case PATHINFO_FILENAME:
  2855. case 'filename':
  2856. return $ret['filename'];
  2857. break;
  2858. default:
  2859. return $ret;
  2860. }
  2861. }
  2862. /**
  2863. * Set or reset instance properties.
  2864. *
  2865. * Usage Example:
  2866. * $page->set('X-Priority', '3');
  2867. *
  2868. * @access public
  2869. * @param string $name
  2870. * @param mixed $value
  2871. * NOTE: will not work with arrays, there are no arrays to set/reset
  2872. * @throws phpmailerException
  2873. * @return bool
  2874. * @todo Should this not be using __set() magic function?
  2875. */
  2876. public function set($name, $value = '')
  2877. {
  2878. try {
  2879. if (isset($this->$name)) {
  2880. $this->$name = $value;
  2881. } else {
  2882. throw new phpmailerException($this->lang('variable_set') . $name, self::STOP_CRITICAL);
  2883. }
  2884. } catch (Exception $e) {
  2885. $this->setError($e->getMessage());
  2886. if ($e->getCode() == self::STOP_CRITICAL) {
  2887. return false;
  2888. }
  2889. }
  2890. return true;
  2891. }
  2892. /**
  2893. * Strip newlines to prevent header injection.
  2894. * @access public
  2895. * @param string $str
  2896. * @return string
  2897. */
  2898. public function secureHeader($str)
  2899. {
  2900. return trim(str_replace(array("\r", "\n"), '', $str));
  2901. }
  2902. /**
  2903. * Normalize line breaks in a string.
  2904. * Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format.
  2905. * Defaults to CRLF (for message bodies) and preserves consecutive breaks.
  2906. * @param string $text
  2907. * @param string $breaktype What kind of line break to use, defaults to CRLF
  2908. * @return string
  2909. * @access public
  2910. * @static
  2911. */
  2912. public static function normalizeBreaks($text, $breaktype = "\r\n")
  2913. {
  2914. return preg_replace('/(\r\n|\r|\n)/ms', $breaktype, $text);
  2915. }
  2916. /**
  2917. * Set the public and private key files and password for S/MIME signing.
  2918. * @access public
  2919. * @param string $cert_filename
  2920. * @param string $key_filename
  2921. * @param string $key_pass Password for private key
  2922. */
  2923. public function sign($cert_filename, $key_filename, $key_pass)
  2924. {
  2925. $this->sign_cert_file = $cert_filename;
  2926. $this->sign_key_file = $key_filename;
  2927. $this->sign_key_pass = $key_pass;
  2928. }
  2929. /**
  2930. * Quoted-Printable-encode a DKIM header.
  2931. * @access public
  2932. * @param string $txt
  2933. * @return string
  2934. */
  2935. public function DKIM_QP($txt)
  2936. {
  2937. $line = '';
  2938. for ($i = 0; $i < strlen($txt); $i++) {
  2939. $ord = ord($txt[$i]);
  2940. if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) {
  2941. $line .= $txt[$i];
  2942. } else {
  2943. $line .= "=" . sprintf("%02X", $ord);
  2944. }
  2945. }
  2946. return $line;
  2947. }
  2948. /**
  2949. * Generate a DKIM signature.
  2950. * @access public
  2951. * @param string $s Header
  2952. * @throws phpmailerException
  2953. * @return string
  2954. */
  2955. public function DKIM_Sign($s)
  2956. {
  2957. if (!defined('PKCS7_TEXT')) {
  2958. if ($this->exceptions) {
  2959. throw new phpmailerException($this->lang("signing") . ' OpenSSL extension missing.');
  2960. }
  2961. return '';
  2962. }
  2963. $privKeyStr = file_get_contents($this->DKIM_private);
  2964. if ($this->DKIM_passphrase != '') {
  2965. $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
  2966. } else {
  2967. $privKey = $privKeyStr;
  2968. }
  2969. if (openssl_sign($s, $signature, $privKey)) {
  2970. return base64_encode($signature);
  2971. }
  2972. return '';
  2973. }
  2974. /**
  2975. * Generate a DKIM canonicalization header.
  2976. * @access public
  2977. * @param string $s Header
  2978. * @return string
  2979. */
  2980. public function DKIM_HeaderC($s)
  2981. {
  2982. $s = preg_replace("/\r\n\s+/", " ", $s);
  2983. $lines = explode("\r\n", $s);
  2984. foreach ($lines as $key => $line) {
  2985. list($heading, $value) = explode(":", $line, 2);
  2986. $heading = strtolower($heading);
  2987. $value = preg_replace("/\s+/", " ", $value); // Compress useless spaces
  2988. $lines[$key] = $heading . ":" . trim($value); // Don't forget to remove WSP around the value
  2989. }
  2990. $s = implode("\r\n", $lines);
  2991. return $s;
  2992. }
  2993. /**
  2994. * Generate a DKIM canonicalization body.
  2995. * @access public
  2996. * @param string $body Message Body
  2997. * @return string
  2998. */
  2999. public function DKIM_BodyC($body)
  3000. {
  3001. if ($body == '') {
  3002. return "\r\n";
  3003. }
  3004. // stabilize line endings
  3005. $body = str_replace("\r\n", "\n", $body);
  3006. $body = str_replace("\n", "\r\n", $body);
  3007. // END stabilize line endings
  3008. while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") {
  3009. $body = substr($body, 0, strlen($body) - 2);
  3010. }
  3011. return $body;
  3012. }
  3013. /**
  3014. * Create the DKIM header and body in a new message header.
  3015. * @access public
  3016. * @param string $headers_line Header lines
  3017. * @param string $subject Subject
  3018. * @param string $body Body
  3019. * @return string
  3020. */
  3021. public function DKIM_Add($headers_line, $subject, $body)
  3022. {
  3023. $DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms
  3024. $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
  3025. $DKIMquery = 'dns/txt'; // Query method
  3026. $DKIMtime = time(); // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
  3027. $subject_header = "Subject: $subject";
  3028. $headers = explode($this->LE, $headers_line);
  3029. $from_header = '';
  3030. $to_header = '';
  3031. $current = '';
  3032. foreach ($headers as $header) {
  3033. if (strpos($header, 'From:') === 0) {
  3034. $from_header = $header;
  3035. $current = 'from_header';
  3036. } elseif (strpos($header, 'To:') === 0) {
  3037. $to_header = $header;
  3038. $current = 'to_header';
  3039. } else {
  3040. if ($current && strpos($header, ' =?') === 0) {
  3041. $current .= $header;
  3042. } else {
  3043. $current = '';
  3044. }
  3045. }
  3046. }
  3047. $from = str_replace('|', '=7C', $this->DKIM_QP($from_header));
  3048. $to = str_replace('|', '=7C', $this->DKIM_QP($to_header));
  3049. $subject = str_replace(
  3050. '|',
  3051. '=7C',
  3052. $this->DKIM_QP($subject_header)
  3053. ); // Copied header fields (dkim-quoted-printable)
  3054. $body = $this->DKIM_BodyC($body);
  3055. $DKIMlen = strlen($body); // Length of body
  3056. $DKIMb64 = base64_encode(pack("H*", sha1($body))); // Base64 of packed binary SHA-1 hash of body
  3057. $ident = ($this->DKIM_identity == '') ? '' : " i=" . $this->DKIM_identity . ";";
  3058. $dkimhdrs = "DKIM-Signature: v=1; a=" .
  3059. $DKIMsignatureType . "; q=" .
  3060. $DKIMquery . "; l=" .
  3061. $DKIMlen . "; s=" .
  3062. $this->DKIM_selector .
  3063. ";\r\n" .
  3064. "\tt=" . $DKIMtime . "; c=" . $DKIMcanonicalization . ";\r\n" .
  3065. "\th=From:To:Subject;\r\n" .
  3066. "\td=" . $this->DKIM_domain . ";" . $ident . "\r\n" .
  3067. "\tz=$from\r\n" .
  3068. "\t|$to\r\n" .
  3069. "\t|$subject;\r\n" .
  3070. "\tbh=" . $DKIMb64 . ";\r\n" .
  3071. "\tb=";
  3072. $toSign = $this->DKIM_HeaderC(
  3073. $from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs
  3074. );
  3075. $signed = $this->DKIM_Sign($toSign);
  3076. return $dkimhdrs . $signed . "\r\n";
  3077. }
  3078. /**
  3079. * Allows for public read access to 'to' property.
  3080. * @access public
  3081. * @return array
  3082. */
  3083. public function getToAddresses()
  3084. {
  3085. return $this->to;
  3086. }
  3087. /**
  3088. * Allows for public read access to 'cc' property.
  3089. * @access public
  3090. * @return array
  3091. */
  3092. public function getCcAddresses()
  3093. {
  3094. return $this->cc;
  3095. }
  3096. /**
  3097. * Allows for public read access to 'bcc' property.
  3098. * @access public
  3099. * @return array
  3100. */
  3101. public function getBccAddresses()
  3102. {
  3103. return $this->bcc;
  3104. }
  3105. /**
  3106. * Allows for public read access to 'ReplyTo' property.
  3107. * @access public
  3108. * @return array
  3109. */
  3110. public function getReplyToAddresses()
  3111. {
  3112. return $this->ReplyTo;
  3113. }
  3114. /**
  3115. * Allows for public read access to 'all_recipients' property.
  3116. * @access public
  3117. * @return array
  3118. */
  3119. public function getAllRecipientAddresses()
  3120. {
  3121. return $this->all_recipients;
  3122. }
  3123. /**
  3124. * Perform a callback.
  3125. * @param bool $isSent
  3126. * @param string $to
  3127. * @param string $cc
  3128. * @param string $bcc
  3129. * @param string $subject
  3130. * @param string $body
  3131. * @param string $from
  3132. */
  3133. protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from = null)
  3134. {
  3135. if (!empty($this->action_function) && is_callable($this->action_function)) {
  3136. $params = array($isSent, $to, $cc, $bcc, $subject, $body, $from);
  3137. call_user_func_array($this->action_function, $params);
  3138. }
  3139. }
  3140. }
  3141. /**
  3142. * PHPMailer exception handler
  3143. * @package PHPMailer
  3144. */
  3145. class phpmailerException extends Exception
  3146. {
  3147. /**
  3148. * Prettify error message output
  3149. * @return string
  3150. */
  3151. public function errorMessage()
  3152. {
  3153. $errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n";
  3154. return $errorMsg;
  3155. }
  3156. }