class.phpmailer.php 144 KB

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