PHPMailer.php 128 KB

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