Açıklama Yok

PHPMailer.php 151KB

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