*/}}

PHPMailer.php 179 KB

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