暂无描述

PHPMailer.php 174KB

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