PHPMailer.php 162 KB

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