Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

PHPMailer.php 147KB

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