class.phpmailer.php 147 KB

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