Git for the orangehattech website https://orangehattech.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

PHPMailer.php 152KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502
  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 PHPMailer\PHPMailer;
  21. /**
  22. * PHPMailer - PHP email creation and transport class.
  23. *
  24. * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
  25. * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
  26. * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
  27. * @author Brent R. Matzelle (original founder)
  28. */
  29. class PHPMailer
  30. {
  31. const CHARSET_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.6';
  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)
  1337. and static::isPermittedPath($this->DKIM_private)
  1338. and file_exists($this->DKIM_private)
  1339. )
  1340. )
  1341. ) {
  1342. $header_dkim = $this->DKIM_Add(
  1343. $this->MIMEHeader . $this->mailHeader,
  1344. $this->encodeHeader($this->secureHeader($this->Subject)),
  1345. $this->MIMEBody
  1346. );
  1347. $this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . static::$LE .
  1348. static::normalizeBreaks($header_dkim) . static::$LE;
  1349. }
  1350. return true;
  1351. } catch (Exception $exc) {
  1352. $this->setError($exc->getMessage());
  1353. if ($this->exceptions) {
  1354. throw $exc;
  1355. }
  1356. return false;
  1357. }
  1358. }
  1359. /**
  1360. * Actually send a message via the selected mechanism.
  1361. *
  1362. * @throws Exception
  1363. *
  1364. * @return bool
  1365. */
  1366. public function postSend()
  1367. {
  1368. try {
  1369. // Choose the mailer and send through it
  1370. switch ($this->Mailer) {
  1371. case 'sendmail':
  1372. case 'qmail':
  1373. return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody);
  1374. case 'smtp':
  1375. return $this->smtpSend($this->MIMEHeader, $this->MIMEBody);
  1376. case 'mail':
  1377. return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
  1378. default:
  1379. $sendMethod = $this->Mailer . 'Send';
  1380. if (method_exists($this, $sendMethod)) {
  1381. return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody);
  1382. }
  1383. return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
  1384. }
  1385. } catch (Exception $exc) {
  1386. $this->setError($exc->getMessage());
  1387. $this->edebug($exc->getMessage());
  1388. if ($this->exceptions) {
  1389. throw $exc;
  1390. }
  1391. }
  1392. return false;
  1393. }
  1394. /**
  1395. * Send mail using the $Sendmail program.
  1396. *
  1397. * @see PHPMailer::$Sendmail
  1398. *
  1399. * @param string $header The message headers
  1400. * @param string $body The message body
  1401. *
  1402. * @throws Exception
  1403. *
  1404. * @return bool
  1405. */
  1406. protected function sendmailSend($header, $body)
  1407. {
  1408. // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
  1409. if (!empty($this->Sender) and self::isShellSafe($this->Sender)) {
  1410. if ('qmail' == $this->Mailer) {
  1411. $sendmailFmt = '%s -f%s';
  1412. } else {
  1413. $sendmailFmt = '%s -oi -f%s -t';
  1414. }
  1415. } else {
  1416. if ('qmail' == $this->Mailer) {
  1417. $sendmailFmt = '%s';
  1418. } else {
  1419. $sendmailFmt = '%s -oi -t';
  1420. }
  1421. }
  1422. $sendmail = sprintf($sendmailFmt, escapeshellcmd($this->Sendmail), $this->Sender);
  1423. if ($this->SingleTo) {
  1424. foreach ($this->SingleToArray as $toAddr) {
  1425. $mail = @popen($sendmail, 'w');
  1426. if (!$mail) {
  1427. throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1428. }
  1429. fwrite($mail, 'To: ' . $toAddr . "\n");
  1430. fwrite($mail, $header);
  1431. fwrite($mail, $body);
  1432. $result = pclose($mail);
  1433. $this->doCallback(
  1434. ($result == 0),
  1435. [$toAddr],
  1436. $this->cc,
  1437. $this->bcc,
  1438. $this->Subject,
  1439. $body,
  1440. $this->From,
  1441. []
  1442. );
  1443. if (0 !== $result) {
  1444. throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1445. }
  1446. }
  1447. } else {
  1448. $mail = @popen($sendmail, 'w');
  1449. if (!$mail) {
  1450. throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1451. }
  1452. fwrite($mail, $header);
  1453. fwrite($mail, $body);
  1454. $result = pclose($mail);
  1455. $this->doCallback(
  1456. ($result == 0),
  1457. $this->to,
  1458. $this->cc,
  1459. $this->bcc,
  1460. $this->Subject,
  1461. $body,
  1462. $this->From,
  1463. []
  1464. );
  1465. if (0 !== $result) {
  1466. throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1467. }
  1468. }
  1469. return true;
  1470. }
  1471. /**
  1472. * Fix CVE-2016-10033 and CVE-2016-10045 by disallowing potentially unsafe shell characters.
  1473. * Note that escapeshellarg and escapeshellcmd are inadequate for our purposes, especially on Windows.
  1474. *
  1475. * @see https://github.com/PHPMailer/PHPMailer/issues/924 CVE-2016-10045 bug report
  1476. *
  1477. * @param string $string The string to be validated
  1478. *
  1479. * @return bool
  1480. */
  1481. protected static function isShellSafe($string)
  1482. {
  1483. // Future-proof
  1484. if (escapeshellcmd($string) !== $string
  1485. or !in_array(escapeshellarg($string), ["'$string'", "\"$string\""])
  1486. ) {
  1487. return false;
  1488. }
  1489. $length = strlen($string);
  1490. for ($i = 0; $i < $length; ++$i) {
  1491. $c = $string[$i];
  1492. // All other characters have a special meaning in at least one common shell, including = and +.
  1493. // Full stop (.) has a special meaning in cmd.exe, but its impact should be negligible here.
  1494. // Note that this does permit non-Latin alphanumeric characters based on the current locale.
  1495. if (!ctype_alnum($c) && strpos('@_-.', $c) === false) {
  1496. return false;
  1497. }
  1498. }
  1499. return true;
  1500. }
  1501. /**
  1502. * Check whether a file path is of a permitted type.
  1503. * Used to reject URLs and phar files from functions that access local file paths,
  1504. * such as addAttachment.
  1505. *
  1506. * @param string $path A relative or absolute path to a file
  1507. *
  1508. * @return bool
  1509. */
  1510. protected static function isPermittedPath($path)
  1511. {
  1512. return !preg_match('#^[a-z]+://#i', $path);
  1513. }
  1514. /**
  1515. * Send mail using the PHP mail() function.
  1516. *
  1517. * @see http://www.php.net/manual/en/book.mail.php
  1518. *
  1519. * @param string $header The message headers
  1520. * @param string $body The message body
  1521. *
  1522. * @throws Exception
  1523. *
  1524. * @return bool
  1525. */
  1526. protected function mailSend($header, $body)
  1527. {
  1528. $toArr = [];
  1529. foreach ($this->to as $toaddr) {
  1530. $toArr[] = $this->addrFormat($toaddr);
  1531. }
  1532. $to = implode(', ', $toArr);
  1533. $params = null;
  1534. //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver
  1535. if (!empty($this->Sender) and static::validateAddress($this->Sender)) {
  1536. //A space after `-f` is optional, but there is a long history of its presence
  1537. //causing problems, so we don't use one
  1538. //Exim docs: http://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html
  1539. //Sendmail docs: http://www.sendmail.org/~ca/email/man/sendmail.html
  1540. //Qmail docs: http://www.qmail.org/man/man8/qmail-inject.html
  1541. //Example problem: https://www.drupal.org/node/1057954
  1542. // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
  1543. if (self::isShellSafe($this->Sender)) {
  1544. $params = sprintf('-f%s', $this->Sender);
  1545. }
  1546. }
  1547. if (!empty($this->Sender) and static::validateAddress($this->Sender)) {
  1548. $old_from = ini_get('sendmail_from');
  1549. ini_set('sendmail_from', $this->Sender);
  1550. }
  1551. $result = false;
  1552. if ($this->SingleTo and count($toArr) > 1) {
  1553. foreach ($toArr as $toAddr) {
  1554. $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params);
  1555. $this->doCallback($result, [$toAddr], $this->cc, $this->bcc, $this->Subject, $body, $this->From, []);
  1556. }
  1557. } else {
  1558. $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params);
  1559. $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From, []);
  1560. }
  1561. if (isset($old_from)) {
  1562. ini_set('sendmail_from', $old_from);
  1563. }
  1564. if (!$result) {
  1565. throw new Exception($this->lang('instantiate'), self::STOP_CRITICAL);
  1566. }
  1567. return true;
  1568. }
  1569. /**
  1570. * Get an instance to use for SMTP operations.
  1571. * Override this function to load your own SMTP implementation,
  1572. * or set one with setSMTPInstance.
  1573. *
  1574. * @return SMTP
  1575. */
  1576. public function getSMTPInstance()
  1577. {
  1578. if (!is_object($this->smtp)) {
  1579. $this->smtp = new SMTP();
  1580. }
  1581. return $this->smtp;
  1582. }
  1583. /**
  1584. * Provide an instance to use for SMTP operations.
  1585. *
  1586. * @param SMTP $smtp
  1587. *
  1588. * @return SMTP
  1589. */
  1590. public function setSMTPInstance(SMTP $smtp)
  1591. {
  1592. $this->smtp = $smtp;
  1593. return $this->smtp;
  1594. }
  1595. /**
  1596. * Send mail via SMTP.
  1597. * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
  1598. *
  1599. * @see PHPMailer::setSMTPInstance() to use a different class.
  1600. *
  1601. * @uses \PHPMailer\PHPMailer\SMTP
  1602. *
  1603. * @param string $header The message headers
  1604. * @param string $body The message body
  1605. *
  1606. * @throws Exception
  1607. *
  1608. * @return bool
  1609. */
  1610. protected function smtpSend($header, $body)
  1611. {
  1612. $bad_rcpt = [];
  1613. if (!$this->smtpConnect($this->SMTPOptions)) {
  1614. throw new Exception($this->lang('smtp_connect_failed'), self::STOP_CRITICAL);
  1615. }
  1616. //Sender already validated in preSend()
  1617. if ('' == $this->Sender) {
  1618. $smtp_from = $this->From;
  1619. } else {
  1620. $smtp_from = $this->Sender;
  1621. }
  1622. if (!$this->smtp->mail($smtp_from)) {
  1623. $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError()));
  1624. throw new Exception($this->ErrorInfo, self::STOP_CRITICAL);
  1625. }
  1626. $callbacks = [];
  1627. // Attempt to send to all recipients
  1628. foreach ([$this->to, $this->cc, $this->bcc] as $togroup) {
  1629. foreach ($togroup as $to) {
  1630. if (!$this->smtp->recipient($to[0])) {
  1631. $error = $this->smtp->getError();
  1632. $bad_rcpt[] = ['to' => $to[0], 'error' => $error['detail']];
  1633. $isSent = false;
  1634. } else {
  1635. $isSent = true;
  1636. }
  1637. $callbacks[] = ['issent'=>$isSent, 'to'=>$to[0]];
  1638. }
  1639. }
  1640. // Only send the DATA command if we have viable recipients
  1641. if ((count($this->all_recipients) > count($bad_rcpt)) and !$this->smtp->data($header . $body)) {
  1642. throw new Exception($this->lang('data_not_accepted'), self::STOP_CRITICAL);
  1643. }
  1644. $smtp_transaction_id = $this->smtp->getLastTransactionID();
  1645. if ($this->SMTPKeepAlive) {
  1646. $this->smtp->reset();
  1647. } else {
  1648. $this->smtp->quit();
  1649. $this->smtp->close();
  1650. }
  1651. foreach ($callbacks as $cb) {
  1652. $this->doCallback(
  1653. $cb['issent'],
  1654. [$cb['to']],
  1655. [],
  1656. [],
  1657. $this->Subject,
  1658. $body,
  1659. $this->From,
  1660. ['smtp_transaction_id' => $smtp_transaction_id]
  1661. );
  1662. }
  1663. //Create error message for any bad addresses
  1664. if (count($bad_rcpt) > 0) {
  1665. $errstr = '';
  1666. foreach ($bad_rcpt as $bad) {
  1667. $errstr .= $bad['to'] . ': ' . $bad['error'];
  1668. }
  1669. throw new Exception(
  1670. $this->lang('recipients_failed') . $errstr,
  1671. self::STOP_CONTINUE
  1672. );
  1673. }
  1674. return true;
  1675. }
  1676. /**
  1677. * Initiate a connection to an SMTP server.
  1678. * Returns false if the operation failed.
  1679. *
  1680. * @param array $options An array of options compatible with stream_context_create()
  1681. *
  1682. * @throws Exception
  1683. *
  1684. * @uses \PHPMailer\PHPMailer\SMTP
  1685. *
  1686. * @return bool
  1687. */
  1688. public function smtpConnect($options = null)
  1689. {
  1690. if (null === $this->smtp) {
  1691. $this->smtp = $this->getSMTPInstance();
  1692. }
  1693. //If no options are provided, use whatever is set in the instance
  1694. if (null === $options) {
  1695. $options = $this->SMTPOptions;
  1696. }
  1697. // Already connected?
  1698. if ($this->smtp->connected()) {
  1699. return true;
  1700. }
  1701. $this->smtp->setTimeout($this->Timeout);
  1702. $this->smtp->setDebugLevel($this->SMTPDebug);
  1703. $this->smtp->setDebugOutput($this->Debugoutput);
  1704. $this->smtp->setVerp($this->do_verp);
  1705. $hosts = explode(';', $this->Host);
  1706. $lastexception = null;
  1707. foreach ($hosts as $hostentry) {
  1708. $hostinfo = [];
  1709. if (!preg_match(
  1710. '/^((ssl|tls):\/\/)*([a-zA-Z0-9\.-]*|\[[a-fA-F0-9:]+\]):?([0-9]*)$/',
  1711. trim($hostentry),
  1712. $hostinfo
  1713. )) {
  1714. static::edebug($this->lang('connect_host') . ' ' . $hostentry);
  1715. // Not a valid host entry
  1716. continue;
  1717. }
  1718. // $hostinfo[2]: optional ssl or tls prefix
  1719. // $hostinfo[3]: the hostname
  1720. // $hostinfo[4]: optional port number
  1721. // The host string prefix can temporarily override the current setting for SMTPSecure
  1722. // If it's not specified, the default value is used
  1723. //Check the host name is a valid name or IP address before trying to use it
  1724. if (!static::isValidHost($hostinfo[3])) {
  1725. static::edebug($this->lang('connect_host') . ' ' . $hostentry);
  1726. continue;
  1727. }
  1728. $prefix = '';
  1729. $secure = $this->SMTPSecure;
  1730. $tls = ('tls' == $this->SMTPSecure);
  1731. if ('ssl' == $hostinfo[2] or ('' == $hostinfo[2] and 'ssl' == $this->SMTPSecure)) {
  1732. $prefix = 'ssl://';
  1733. $tls = false; // Can't have SSL and TLS at the same time
  1734. $secure = 'ssl';
  1735. } elseif ('tls' == $hostinfo[2]) {
  1736. $tls = true;
  1737. // tls doesn't use a prefix
  1738. $secure = 'tls';
  1739. }
  1740. //Do we need the OpenSSL extension?
  1741. $sslext = defined('OPENSSL_ALGO_SHA256');
  1742. if ('tls' === $secure or 'ssl' === $secure) {
  1743. //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled
  1744. if (!$sslext) {
  1745. throw new Exception($this->lang('extension_missing') . 'openssl', self::STOP_CRITICAL);
  1746. }
  1747. }
  1748. $host = $hostinfo[3];
  1749. $port = $this->Port;
  1750. $tport = (int) $hostinfo[4];
  1751. if ($tport > 0 and $tport < 65536) {
  1752. $port = $tport;
  1753. }
  1754. if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) {
  1755. try {
  1756. if ($this->Helo) {
  1757. $hello = $this->Helo;
  1758. } else {
  1759. $hello = $this->serverHostname();
  1760. }
  1761. $this->smtp->hello($hello);
  1762. //Automatically enable TLS encryption if:
  1763. // * it's not disabled
  1764. // * we have openssl extension
  1765. // * we are not already using SSL
  1766. // * the server offers STARTTLS
  1767. if ($this->SMTPAutoTLS and $sslext and 'ssl' != $secure and $this->smtp->getServerExt('STARTTLS')) {
  1768. $tls = true;
  1769. }
  1770. if ($tls) {
  1771. if (!$this->smtp->startTLS()) {
  1772. throw new Exception($this->lang('connect_host'));
  1773. }
  1774. // We must resend EHLO after TLS negotiation
  1775. $this->smtp->hello($hello);
  1776. }
  1777. if ($this->SMTPAuth) {
  1778. if (!$this->smtp->authenticate(
  1779. $this->Username,
  1780. $this->Password,
  1781. $this->AuthType,
  1782. $this->oauth
  1783. )
  1784. ) {
  1785. throw new Exception($this->lang('authenticate'));
  1786. }
  1787. }
  1788. return true;
  1789. } catch (Exception $exc) {
  1790. $lastexception = $exc;
  1791. $this->edebug($exc->getMessage());
  1792. // We must have connected, but then failed TLS or Auth, so close connection nicely
  1793. $this->smtp->quit();
  1794. }
  1795. }
  1796. }
  1797. // If we get here, all connection attempts have failed, so close connection hard
  1798. $this->smtp->close();
  1799. // As we've caught all exceptions, just report whatever the last one was
  1800. if ($this->exceptions and null !== $lastexception) {
  1801. throw $lastexception;
  1802. }
  1803. return false;
  1804. }
  1805. /**
  1806. * Close the active SMTP session if one exists.
  1807. */
  1808. public function smtpClose()
  1809. {
  1810. if (null !== $this->smtp) {
  1811. if ($this->smtp->connected()) {
  1812. $this->smtp->quit();
  1813. $this->smtp->close();
  1814. }
  1815. }
  1816. }
  1817. /**
  1818. * Set the language for error messages.
  1819. * Returns false if it cannot load the language file.
  1820. * The default language is English.
  1821. *
  1822. * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr")
  1823. * @param string $lang_path Path to the language file directory, with trailing separator (slash)
  1824. *
  1825. * @return bool
  1826. */
  1827. public function setLanguage($langcode = 'en', $lang_path = '')
  1828. {
  1829. // Backwards compatibility for renamed language codes
  1830. $renamed_langcodes = [
  1831. 'br' => 'pt_br',
  1832. 'cz' => 'cs',
  1833. 'dk' => 'da',
  1834. 'no' => 'nb',
  1835. 'se' => 'sv',
  1836. 'rs' => 'sr',
  1837. 'tg' => 'tl',
  1838. ];
  1839. if (isset($renamed_langcodes[$langcode])) {
  1840. $langcode = $renamed_langcodes[$langcode];
  1841. }
  1842. // Define full set of translatable strings in English
  1843. $PHPMAILER_LANG = [
  1844. 'authenticate' => 'SMTP Error: Could not authenticate.',
  1845. 'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
  1846. 'data_not_accepted' => 'SMTP Error: data not accepted.',
  1847. 'empty_message' => 'Message body empty',
  1848. 'encoding' => 'Unknown encoding: ',
  1849. 'execute' => 'Could not execute: ',
  1850. 'file_access' => 'Could not access file: ',
  1851. 'file_open' => 'File Error: Could not open file: ',
  1852. 'from_failed' => 'The following From address failed: ',
  1853. 'instantiate' => 'Could not instantiate mail function.',
  1854. 'invalid_address' => 'Invalid address: ',
  1855. 'mailer_not_supported' => ' mailer is not supported.',
  1856. 'provide_address' => 'You must provide at least one recipient email address.',
  1857. 'recipients_failed' => 'SMTP Error: The following recipients failed: ',
  1858. 'signing' => 'Signing Error: ',
  1859. 'smtp_connect_failed' => 'SMTP connect() failed.',
  1860. 'smtp_error' => 'SMTP server error: ',
  1861. 'variable_set' => 'Cannot set or reset variable: ',
  1862. 'extension_missing' => 'Extension missing: ',
  1863. ];
  1864. if (empty($lang_path)) {
  1865. // Calculate an absolute path so it can work if CWD is not here
  1866. $lang_path = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'language' . DIRECTORY_SEPARATOR;
  1867. }
  1868. //Validate $langcode
  1869. if (!preg_match('/^[a-z]{2}(?:_[a-zA-Z]{2})?$/', $langcode)) {
  1870. $langcode = 'en';
  1871. }
  1872. $foundlang = true;
  1873. $lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php';
  1874. // There is no English translation file
  1875. if ('en' != $langcode) {
  1876. // Make sure language file path is readable
  1877. if (!static::isPermittedPath($lang_file) || !file_exists($lang_file)) {
  1878. $foundlang = false;
  1879. } else {
  1880. // Overwrite language-specific strings.
  1881. // This way we'll never have missing translation keys.
  1882. $foundlang = include $lang_file;
  1883. }
  1884. }
  1885. $this->language = $PHPMAILER_LANG;
  1886. return (bool) $foundlang; // Returns false if language not found
  1887. }
  1888. /**
  1889. * Get the array of strings for the current language.
  1890. *
  1891. * @return array
  1892. */
  1893. public function getTranslations()
  1894. {
  1895. return $this->language;
  1896. }
  1897. /**
  1898. * Create recipient headers.
  1899. *
  1900. * @param string $type
  1901. * @param array $addr An array of recipients,
  1902. * where each recipient is a 2-element indexed array with element 0 containing an address
  1903. * and element 1 containing a name, like:
  1904. * [['joe@example.com', 'Joe User'], ['zoe@example.com', 'Zoe User']]
  1905. *
  1906. * @return string
  1907. */
  1908. public function addrAppend($type, $addr)
  1909. {
  1910. $addresses = [];
  1911. foreach ($addr as $address) {
  1912. $addresses[] = $this->addrFormat($address);
  1913. }
  1914. return $type . ': ' . implode(', ', $addresses) . static::$LE;
  1915. }
  1916. /**
  1917. * Format an address for use in a message header.
  1918. *
  1919. * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name like
  1920. * ['joe@example.com', 'Joe User']
  1921. *
  1922. * @return string
  1923. */
  1924. public function addrFormat($addr)
  1925. {
  1926. if (empty($addr[1])) { // No name provided
  1927. return $this->secureHeader($addr[0]);
  1928. }
  1929. return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . ' <' . $this->secureHeader(
  1930. $addr[0]
  1931. ) . '>';
  1932. }
  1933. /**
  1934. * Word-wrap message.
  1935. * For use with mailers that do not automatically perform wrapping
  1936. * and for quoted-printable encoded messages.
  1937. * Original written by philippe.
  1938. *
  1939. * @param string $message The message to wrap
  1940. * @param int $length The line length to wrap to
  1941. * @param bool $qp_mode Whether to run in Quoted-Printable mode
  1942. *
  1943. * @return string
  1944. */
  1945. public function wrapText($message, $length, $qp_mode = false)
  1946. {
  1947. if ($qp_mode) {
  1948. $soft_break = sprintf(' =%s', static::$LE);
  1949. } else {
  1950. $soft_break = static::$LE;
  1951. }
  1952. // If utf-8 encoding is used, we will need to make sure we don't
  1953. // split multibyte characters when we wrap
  1954. $is_utf8 = static::CHARSET_UTF8 === strtolower($this->CharSet);
  1955. $lelen = strlen(static::$LE);
  1956. $crlflen = strlen(static::$LE);
  1957. $message = static::normalizeBreaks($message);
  1958. //Remove a trailing line break
  1959. if (substr($message, -$lelen) == static::$LE) {
  1960. $message = substr($message, 0, -$lelen);
  1961. }
  1962. //Split message into lines
  1963. $lines = explode(static::$LE, $message);
  1964. //Message will be rebuilt in here
  1965. $message = '';
  1966. foreach ($lines as $line) {
  1967. $words = explode(' ', $line);
  1968. $buf = '';
  1969. $firstword = true;
  1970. foreach ($words as $word) {
  1971. if ($qp_mode and (strlen($word) > $length)) {
  1972. $space_left = $length - strlen($buf) - $crlflen;
  1973. if (!$firstword) {
  1974. if ($space_left > 20) {
  1975. $len = $space_left;
  1976. if ($is_utf8) {
  1977. $len = $this->utf8CharBoundary($word, $len);
  1978. } elseif ('=' == substr($word, $len - 1, 1)) {
  1979. --$len;
  1980. } elseif ('=' == substr($word, $len - 2, 1)) {
  1981. $len -= 2;
  1982. }
  1983. $part = substr($word, 0, $len);
  1984. $word = substr($word, $len);
  1985. $buf .= ' ' . $part;
  1986. $message .= $buf . sprintf('=%s', static::$LE);
  1987. } else {
  1988. $message .= $buf . $soft_break;
  1989. }
  1990. $buf = '';
  1991. }
  1992. while (strlen($word) > 0) {
  1993. if ($length <= 0) {
  1994. break;
  1995. }
  1996. $len = $length;
  1997. if ($is_utf8) {
  1998. $len = $this->utf8CharBoundary($word, $len);
  1999. } elseif ('=' == substr($word, $len - 1, 1)) {
  2000. --$len;
  2001. } elseif ('=' == substr($word, $len - 2, 1)) {
  2002. $len -= 2;
  2003. }
  2004. $part = substr($word, 0, $len);
  2005. $word = substr($word, $len);
  2006. if (strlen($word) > 0) {
  2007. $message .= $part . sprintf('=%s', static::$LE);
  2008. } else {
  2009. $buf = $part;
  2010. }
  2011. }
  2012. } else {
  2013. $buf_o = $buf;
  2014. if (!$firstword) {
  2015. $buf .= ' ';
  2016. }
  2017. $buf .= $word;
  2018. if (strlen($buf) > $length and '' != $buf_o) {
  2019. $message .= $buf_o . $soft_break;
  2020. $buf = $word;
  2021. }
  2022. }
  2023. $firstword = false;
  2024. }
  2025. $message .= $buf . static::$LE;
  2026. }
  2027. return $message;
  2028. }
  2029. /**
  2030. * Find the last character boundary prior to $maxLength in a utf-8
  2031. * quoted-printable encoded string.
  2032. * Original written by Colin Brown.
  2033. *
  2034. * @param string $encodedText utf-8 QP text
  2035. * @param int $maxLength Find the last character boundary prior to this length
  2036. *
  2037. * @return int
  2038. */
  2039. public function utf8CharBoundary($encodedText, $maxLength)
  2040. {
  2041. $foundSplitPos = false;
  2042. $lookBack = 3;
  2043. while (!$foundSplitPos) {
  2044. $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
  2045. $encodedCharPos = strpos($lastChunk, '=');
  2046. if (false !== $encodedCharPos) {
  2047. // Found start of encoded character byte within $lookBack block.
  2048. // Check the encoded byte value (the 2 chars after the '=')
  2049. $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
  2050. $dec = hexdec($hex);
  2051. if ($dec < 128) {
  2052. // Single byte character.
  2053. // If the encoded char was found at pos 0, it will fit
  2054. // otherwise reduce maxLength to start of the encoded char
  2055. if ($encodedCharPos > 0) {
  2056. $maxLength -= $lookBack - $encodedCharPos;
  2057. }
  2058. $foundSplitPos = true;
  2059. } elseif ($dec >= 192) {
  2060. // First byte of a multi byte character
  2061. // Reduce maxLength to split at start of character
  2062. $maxLength -= $lookBack - $encodedCharPos;
  2063. $foundSplitPos = true;
  2064. } elseif ($dec < 192) {
  2065. // Middle byte of a multi byte character, look further back
  2066. $lookBack += 3;
  2067. }
  2068. } else {
  2069. // No encoded character found
  2070. $foundSplitPos = true;
  2071. }
  2072. }
  2073. return $maxLength;
  2074. }
  2075. /**
  2076. * Apply word wrapping to the message body.
  2077. * Wraps the message body to the number of chars set in the WordWrap property.
  2078. * You should only do this to plain-text bodies as wrapping HTML tags may break them.
  2079. * This is called automatically by createBody(), so you don't need to call it yourself.
  2080. */
  2081. public function setWordWrap()
  2082. {
  2083. if ($this->WordWrap < 1) {
  2084. return;
  2085. }
  2086. switch ($this->message_type) {
  2087. case 'alt':
  2088. case 'alt_inline':
  2089. case 'alt_attach':
  2090. case 'alt_inline_attach':
  2091. $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap);
  2092. break;
  2093. default:
  2094. $this->Body = $this->wrapText($this->Body, $this->WordWrap);
  2095. break;
  2096. }
  2097. }
  2098. /**
  2099. * Assemble message headers.
  2100. *
  2101. * @return string The assembled headers
  2102. */
  2103. public function createHeader()
  2104. {
  2105. $result = '';
  2106. $result .= $this->headerLine('Date', '' == $this->MessageDate ? self::rfcDate() : $this->MessageDate);
  2107. // To be created automatically by mail()
  2108. if ($this->SingleTo) {
  2109. if ('mail' != $this->Mailer) {
  2110. foreach ($this->to as $toaddr) {
  2111. $this->SingleToArray[] = $this->addrFormat($toaddr);
  2112. }
  2113. }
  2114. } else {
  2115. if (count($this->to) > 0) {
  2116. if ('mail' != $this->Mailer) {
  2117. $result .= $this->addrAppend('To', $this->to);
  2118. }
  2119. } elseif (count($this->cc) == 0) {
  2120. $result .= $this->headerLine('To', 'undisclosed-recipients:;');
  2121. }
  2122. }
  2123. $result .= $this->addrAppend('From', [[trim($this->From), $this->FromName]]);
  2124. // sendmail and mail() extract Cc from the header before sending
  2125. if (count($this->cc) > 0) {
  2126. $result .= $this->addrAppend('Cc', $this->cc);
  2127. }
  2128. // sendmail and mail() extract Bcc from the header before sending
  2129. if ((
  2130. 'sendmail' == $this->Mailer or 'qmail' == $this->Mailer or 'mail' == $this->Mailer
  2131. )
  2132. and count($this->bcc) > 0
  2133. ) {
  2134. $result .= $this->addrAppend('Bcc', $this->bcc);
  2135. }
  2136. if (count($this->ReplyTo) > 0) {
  2137. $result .= $this->addrAppend('Reply-To', $this->ReplyTo);
  2138. }
  2139. // mail() sets the subject itself
  2140. if ('mail' != $this->Mailer) {
  2141. $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject)));
  2142. }
  2143. // Only allow a custom message ID if it conforms to RFC 5322 section 3.6.4
  2144. // https://tools.ietf.org/html/rfc5322#section-3.6.4
  2145. if ('' != $this->MessageID and preg_match('/^<.*@.*>$/', $this->MessageID)) {
  2146. $this->lastMessageID = $this->MessageID;
  2147. } else {
  2148. $this->lastMessageID = sprintf('<%s@%s>', $this->uniqueid, $this->serverHostname());
  2149. }
  2150. $result .= $this->headerLine('Message-ID', $this->lastMessageID);
  2151. if (null !== $this->Priority) {
  2152. $result .= $this->headerLine('X-Priority', $this->Priority);
  2153. }
  2154. if ('' == $this->XMailer) {
  2155. $result .= $this->headerLine(
  2156. 'X-Mailer',
  2157. 'PHPMailer ' . self::VERSION . ' (https://github.com/PHPMailer/PHPMailer)'
  2158. );
  2159. } else {
  2160. $myXmailer = trim($this->XMailer);
  2161. if ($myXmailer) {
  2162. $result .= $this->headerLine('X-Mailer', $myXmailer);
  2163. }
  2164. }
  2165. if ('' != $this->ConfirmReadingTo) {
  2166. $result .= $this->headerLine('Disposition-Notification-To', '<' . $this->ConfirmReadingTo . '>');
  2167. }
  2168. // Add custom headers
  2169. foreach ($this->CustomHeader as $header) {
  2170. $result .= $this->headerLine(
  2171. trim($header[0]),
  2172. $this->encodeHeader(trim($header[1]))
  2173. );
  2174. }
  2175. if (!$this->sign_key_file) {
  2176. $result .= $this->headerLine('MIME-Version', '1.0');
  2177. $result .= $this->getMailMIME();
  2178. }
  2179. return $result;
  2180. }
  2181. /**
  2182. * Get the message MIME type headers.
  2183. *
  2184. * @return string
  2185. */
  2186. public function getMailMIME()
  2187. {
  2188. $result = '';
  2189. $ismultipart = true;
  2190. switch ($this->message_type) {
  2191. case 'inline':
  2192. $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
  2193. $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
  2194. break;
  2195. case 'attach':
  2196. case 'inline_attach':
  2197. case 'alt_attach':
  2198. case 'alt_inline_attach':
  2199. $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_MIXED . ';');
  2200. $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
  2201. break;
  2202. case 'alt':
  2203. case 'alt_inline':
  2204. $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';');
  2205. $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
  2206. break;
  2207. default:
  2208. // Catches case 'plain': and case '':
  2209. $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet);
  2210. $ismultipart = false;
  2211. break;
  2212. }
  2213. // RFC1341 part 5 says 7bit is assumed if not specified
  2214. if (static::ENCODING_7BIT != $this->Encoding) {
  2215. // RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE
  2216. if ($ismultipart) {
  2217. if (static::ENCODING_8BIT == $this->Encoding) {
  2218. $result .= $this->headerLine('Content-Transfer-Encoding', static::ENCODING_8BIT);
  2219. }
  2220. // The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible
  2221. } else {
  2222. $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding);
  2223. }
  2224. }
  2225. if ('mail' != $this->Mailer) {
  2226. $result .= static::$LE;
  2227. }
  2228. return $result;
  2229. }
  2230. /**
  2231. * Returns the whole MIME message.
  2232. * Includes complete headers and body.
  2233. * Only valid post preSend().
  2234. *
  2235. * @see PHPMailer::preSend()
  2236. *
  2237. * @return string
  2238. */
  2239. public function getSentMIMEMessage()
  2240. {
  2241. return rtrim($this->MIMEHeader . $this->mailHeader, "\n\r") . static::$LE . static::$LE . $this->MIMEBody;
  2242. }
  2243. /**
  2244. * Create a unique ID to use for boundaries.
  2245. *
  2246. * @return string
  2247. */
  2248. protected function generateId()
  2249. {
  2250. $len = 32; //32 bytes = 256 bits
  2251. if (function_exists('random_bytes')) {
  2252. $bytes = random_bytes($len);
  2253. } elseif (function_exists('openssl_random_pseudo_bytes')) {
  2254. $bytes = openssl_random_pseudo_bytes($len);
  2255. } else {
  2256. //Use a hash to force the length to the same as the other methods
  2257. $bytes = hash('sha256', uniqid((string) mt_rand(), true), true);
  2258. }
  2259. //We don't care about messing up base64 format here, just want a random string
  2260. return str_replace(['=', '+', '/'], '', base64_encode(hash('sha256', $bytes, true)));
  2261. }
  2262. /**
  2263. * Assemble the message body.
  2264. * Returns an empty string on failure.
  2265. *
  2266. * @throws Exception
  2267. *
  2268. * @return string The assembled message body
  2269. */
  2270. public function createBody()
  2271. {
  2272. $body = '';
  2273. //Create unique IDs and preset boundaries
  2274. $this->uniqueid = $this->generateId();
  2275. $this->boundary[1] = 'b1_' . $this->uniqueid;
  2276. $this->boundary[2] = 'b2_' . $this->uniqueid;
  2277. $this->boundary[3] = 'b3_' . $this->uniqueid;
  2278. if ($this->sign_key_file) {
  2279. $body .= $this->getMailMIME() . static::$LE;
  2280. }
  2281. $this->setWordWrap();
  2282. $bodyEncoding = $this->Encoding;
  2283. $bodyCharSet = $this->CharSet;
  2284. //Can we do a 7-bit downgrade?
  2285. if (static::ENCODING_8BIT == $bodyEncoding and !$this->has8bitChars($this->Body)) {
  2286. $bodyEncoding = static::ENCODING_7BIT;
  2287. //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit
  2288. $bodyCharSet = 'us-ascii';
  2289. }
  2290. //If lines are too long, and we're not already using an encoding that will shorten them,
  2291. //change to quoted-printable transfer encoding for the body part only
  2292. if (static::ENCODING_BASE64 != $this->Encoding and static::hasLineLongerThanMax($this->Body)) {
  2293. $bodyEncoding = static::ENCODING_QUOTED_PRINTABLE;
  2294. }
  2295. $altBodyEncoding = $this->Encoding;
  2296. $altBodyCharSet = $this->CharSet;
  2297. //Can we do a 7-bit downgrade?
  2298. if (static::ENCODING_8BIT == $altBodyEncoding and !$this->has8bitChars($this->AltBody)) {
  2299. $altBodyEncoding = static::ENCODING_7BIT;
  2300. //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit
  2301. $altBodyCharSet = 'us-ascii';
  2302. }
  2303. //If lines are too long, and we're not already using an encoding that will shorten them,
  2304. //change to quoted-printable transfer encoding for the alt body part only
  2305. if (static::ENCODING_BASE64 != $altBodyEncoding and static::hasLineLongerThanMax($this->AltBody)) {
  2306. $altBodyEncoding = static::ENCODING_QUOTED_PRINTABLE;
  2307. }
  2308. //Use this as a preamble in all multipart message types
  2309. $mimepre = 'This is a multi-part message in MIME format.' . static::$LE;
  2310. switch ($this->message_type) {
  2311. case 'inline':
  2312. $body .= $mimepre;
  2313. $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
  2314. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2315. $body .= static::$LE;
  2316. $body .= $this->attachAll('inline', $this->boundary[1]);
  2317. break;
  2318. case 'attach':
  2319. $body .= $mimepre;
  2320. $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
  2321. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2322. $body .= static::$LE;
  2323. $body .= $this->attachAll('attachment', $this->boundary[1]);
  2324. break;
  2325. case 'inline_attach':
  2326. $body .= $mimepre;
  2327. $body .= $this->textLine('--' . $this->boundary[1]);
  2328. $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
  2329. $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  2330. $body .= static::$LE;
  2331. $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding);
  2332. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2333. $body .= static::$LE;
  2334. $body .= $this->attachAll('inline', $this->boundary[2]);
  2335. $body .= static::$LE;
  2336. $body .= $this->attachAll('attachment', $this->boundary[1]);
  2337. break;
  2338. case 'alt':
  2339. $body .= $mimepre;
  2340. $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, static::CONTENT_TYPE_PLAINTEXT, $altBodyEncoding);
  2341. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  2342. $body .= static::$LE;
  2343. $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, static::CONTENT_TYPE_TEXT_HTML, $bodyEncoding);
  2344. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2345. $body .= static::$LE;
  2346. if (!empty($this->Ical)) {
  2347. $body .= $this->getBoundary($this->boundary[1], '', static::CONTENT_TYPE_TEXT_CALENDAR . '; method=REQUEST', '');
  2348. $body .= $this->encodeString($this->Ical, $this->Encoding);
  2349. $body .= static::$LE;
  2350. }
  2351. $body .= $this->endBoundary($this->boundary[1]);
  2352. break;
  2353. case 'alt_inline':
  2354. $body .= $mimepre;
  2355. $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, static::CONTENT_TYPE_PLAINTEXT, $altBodyEncoding);
  2356. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  2357. $body .= static::$LE;
  2358. $body .= $this->textLine('--' . $this->boundary[1]);
  2359. $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
  2360. $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  2361. $body .= static::$LE;
  2362. $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, static::CONTENT_TYPE_TEXT_HTML, $bodyEncoding);
  2363. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2364. $body .= static::$LE;
  2365. $body .= $this->attachAll('inline', $this->boundary[2]);
  2366. $body .= static::$LE;
  2367. $body .= $this->endBoundary($this->boundary[1]);
  2368. break;
  2369. case 'alt_attach':
  2370. $body .= $mimepre;
  2371. $body .= $this->textLine('--' . $this->boundary[1]);
  2372. $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';');
  2373. $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  2374. $body .= static::$LE;
  2375. $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, static::CONTENT_TYPE_PLAINTEXT, $altBodyEncoding);
  2376. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  2377. $body .= static::$LE;
  2378. $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, static::CONTENT_TYPE_TEXT_HTML, $bodyEncoding);
  2379. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2380. $body .= static::$LE;
  2381. if (!empty($this->Ical)) {
  2382. $body .= $this->getBoundary($this->boundary[2], '', static::CONTENT_TYPE_TEXT_CALENDAR . '; method=REQUEST', '');
  2383. $body .= $this->encodeString($this->Ical, $this->Encoding);
  2384. }
  2385. $body .= $this->endBoundary($this->boundary[2]);
  2386. $body .= static::$LE;
  2387. $body .= $this->attachAll('attachment', $this->boundary[1]);
  2388. break;
  2389. case 'alt_inline_attach':
  2390. $body .= $mimepre;
  2391. $body .= $this->textLine('--' . $this->boundary[1]);
  2392. $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';');
  2393. $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  2394. $body .= static::$LE;
  2395. $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, static::CONTENT_TYPE_PLAINTEXT, $altBodyEncoding);
  2396. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  2397. $body .= static::$LE;
  2398. $body .= $this->textLine('--' . $this->boundary[2]);
  2399. $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
  2400. $body .= $this->textLine("\tboundary=\"" . $this->boundary[3] . '"');
  2401. $body .= static::$LE;
  2402. $body .= $this->getBoundary($this->boundary[3], $bodyCharSet, static::CONTENT_TYPE_TEXT_HTML, $bodyEncoding);
  2403. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2404. $body .= static::$LE;
  2405. $body .= $this->attachAll('inline', $this->boundary[3]);
  2406. $body .= static::$LE;
  2407. $body .= $this->endBoundary($this->boundary[2]);
  2408. $body .= static::$LE;
  2409. $body .= $this->attachAll('attachment', $this->boundary[1]);
  2410. break;
  2411. default:
  2412. // Catch case 'plain' and case '', applies to simple `text/plain` and `text/html` body content types
  2413. //Reset the `Encoding` property in case we changed it for line length reasons
  2414. $this->Encoding = $bodyEncoding;
  2415. $body .= $this->encodeString($this->Body, $this->Encoding);
  2416. break;
  2417. }
  2418. if ($this->isError()) {
  2419. $body = '';
  2420. if ($this->exceptions) {
  2421. throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL);
  2422. }
  2423. } elseif ($this->sign_key_file) {
  2424. try {
  2425. if (!defined('PKCS7_TEXT')) {
  2426. throw new Exception($this->lang('extension_missing') . 'openssl');
  2427. }
  2428. // @TODO would be nice to use php://temp streams here
  2429. $file = tempnam(sys_get_temp_dir(), 'mail');
  2430. if (false === file_put_contents($file, $body)) {
  2431. throw new Exception($this->lang('signing') . ' Could not write temp file');
  2432. }
  2433. $signed = tempnam(sys_get_temp_dir(), 'signed');
  2434. //Workaround for PHP bug https://bugs.php.net/bug.php?id=69197
  2435. if (empty($this->sign_extracerts_file)) {
  2436. $sign = @openssl_pkcs7_sign(
  2437. $file,
  2438. $signed,
  2439. 'file://' . realpath($this->sign_cert_file),
  2440. ['file://' . realpath($this->sign_key_file), $this->sign_key_pass],
  2441. []
  2442. );
  2443. } else {
  2444. $sign = @openssl_pkcs7_sign(
  2445. $file,
  2446. $signed,
  2447. 'file://' . realpath($this->sign_cert_file),
  2448. ['file://' . realpath($this->sign_key_file), $this->sign_key_pass],
  2449. [],
  2450. PKCS7_DETACHED,
  2451. $this->sign_extracerts_file
  2452. );
  2453. }
  2454. @unlink($file);
  2455. if ($sign) {
  2456. $body = file_get_contents($signed);
  2457. @unlink($signed);
  2458. //The message returned by openssl contains both headers and body, so need to split them up
  2459. $parts = explode("\n\n", $body, 2);
  2460. $this->MIMEHeader .= $parts[0] . static::$LE . static::$LE;
  2461. $body = $parts[1];
  2462. } else {
  2463. @unlink($signed);
  2464. throw new Exception($this->lang('signing') . openssl_error_string());
  2465. }
  2466. } catch (Exception $exc) {
  2467. $body = '';
  2468. if ($this->exceptions) {
  2469. throw $exc;
  2470. }
  2471. }
  2472. }
  2473. return $body;
  2474. }
  2475. /**
  2476. * Return the start of a message boundary.
  2477. *
  2478. * @param string $boundary
  2479. * @param string $charSet
  2480. * @param string $contentType
  2481. * @param string $encoding
  2482. *
  2483. * @return string
  2484. */
  2485. protected function getBoundary($boundary, $charSet, $contentType, $encoding)
  2486. {
  2487. $result = '';
  2488. if ('' == $charSet) {
  2489. $charSet = $this->CharSet;
  2490. }
  2491. if ('' == $contentType) {
  2492. $contentType = $this->ContentType;
  2493. }
  2494. if ('' == $encoding) {
  2495. $encoding = $this->Encoding;
  2496. }
  2497. $result .= $this->textLine('--' . $boundary);
  2498. $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet);
  2499. $result .= static::$LE;
  2500. // RFC1341 part 5 says 7bit is assumed if not specified
  2501. if (static::ENCODING_7BIT != $encoding) {
  2502. $result .= $this->headerLine('Content-Transfer-Encoding', $encoding);
  2503. }
  2504. $result .= static::$LE;
  2505. return $result;
  2506. }
  2507. /**
  2508. * Return the end of a message boundary.
  2509. *
  2510. * @param string $boundary
  2511. *
  2512. * @return string
  2513. */
  2514. protected function endBoundary($boundary)
  2515. {
  2516. return static::$LE . '--' . $boundary . '--' . static::$LE;
  2517. }
  2518. /**
  2519. * Set the message type.
  2520. * PHPMailer only supports some preset message types, not arbitrary MIME structures.
  2521. */
  2522. protected function setMessageType()
  2523. {
  2524. $type = [];
  2525. if ($this->alternativeExists()) {
  2526. $type[] = 'alt';
  2527. }
  2528. if ($this->inlineImageExists()) {
  2529. $type[] = 'inline';
  2530. }
  2531. if ($this->attachmentExists()) {
  2532. $type[] = 'attach';
  2533. }
  2534. $this->message_type = implode('_', $type);
  2535. if ('' == $this->message_type) {
  2536. //The 'plain' message_type refers to the message having a single body element, not that it is plain-text
  2537. $this->message_type = 'plain';
  2538. }
  2539. }
  2540. /**
  2541. * Format a header line.
  2542. *
  2543. * @param string $name
  2544. * @param string|int $value
  2545. *
  2546. * @return string
  2547. */
  2548. public function headerLine($name, $value)
  2549. {
  2550. return $name . ': ' . $value . static::$LE;
  2551. }
  2552. /**
  2553. * Return a formatted mail line.
  2554. *
  2555. * @param string $value
  2556. *
  2557. * @return string
  2558. */
  2559. public function textLine($value)
  2560. {
  2561. return $value . static::$LE;
  2562. }
  2563. /**
  2564. * Add an attachment from a path on the filesystem.
  2565. * Never use a user-supplied path to a file!
  2566. * Returns false if the file could not be found or read.
  2567. * Explicitly *does not* support passing URLs; PHPMailer is not an HTTP client.
  2568. * If you need to do that, fetch the resource yourself and pass it in via a local file or string.
  2569. *
  2570. * @param string $path Path to the attachment
  2571. * @param string $name Overrides the attachment name
  2572. * @param string $encoding File encoding (see $Encoding)
  2573. * @param string $type File extension (MIME) type
  2574. * @param string $disposition Disposition to use
  2575. *
  2576. * @throws Exception
  2577. *
  2578. * @return bool
  2579. */
  2580. public function addAttachment($path, $name = '', $encoding = self::ENCODING_BASE64, $type = '', $disposition = 'attachment')
  2581. {
  2582. try {
  2583. if (!static::isPermittedPath($path) || !@is_file($path)) {
  2584. throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE);
  2585. }
  2586. // If a MIME type is not specified, try to work it out from the file name
  2587. if ('' == $type) {
  2588. $type = static::filenameToType($path);
  2589. }
  2590. $filename = basename($path);
  2591. if ('' == $name) {
  2592. $name = $filename;
  2593. }
  2594. $this->attachment[] = [
  2595. 0 => $path,
  2596. 1 => $filename,
  2597. 2 => $name,
  2598. 3 => $encoding,
  2599. 4 => $type,
  2600. 5 => false, // isStringAttachment
  2601. 6 => $disposition,
  2602. 7 => $name,
  2603. ];
  2604. } catch (Exception $exc) {
  2605. $this->setError($exc->getMessage());
  2606. $this->edebug($exc->getMessage());
  2607. if ($this->exceptions) {
  2608. throw $exc;
  2609. }
  2610. return false;
  2611. }
  2612. return true;
  2613. }
  2614. /**
  2615. * Return the array of attachments.
  2616. *
  2617. * @return array
  2618. */
  2619. public function getAttachments()
  2620. {
  2621. return $this->attachment;
  2622. }
  2623. /**
  2624. * Attach all file, string, and binary attachments to the message.
  2625. * Returns an empty string on failure.
  2626. *
  2627. * @param string $disposition_type
  2628. * @param string $boundary
  2629. *
  2630. * @return string
  2631. */
  2632. protected function attachAll($disposition_type, $boundary)
  2633. {
  2634. // Return text of body
  2635. $mime = [];
  2636. $cidUniq = [];
  2637. $incl = [];
  2638. // Add all attachments
  2639. foreach ($this->attachment as $attachment) {
  2640. // Check if it is a valid disposition_filter
  2641. if ($attachment[6] == $disposition_type) {
  2642. // Check for string attachment
  2643. $string = '';
  2644. $path = '';
  2645. $bString = $attachment[5];
  2646. if ($bString) {
  2647. $string = $attachment[0];
  2648. } else {
  2649. $path = $attachment[0];
  2650. }
  2651. $inclhash = hash('sha256', serialize($attachment));
  2652. if (in_array($inclhash, $incl)) {
  2653. continue;
  2654. }
  2655. $incl[] = $inclhash;
  2656. $name = $attachment[2];
  2657. $encoding = $attachment[3];
  2658. $type = $attachment[4];
  2659. $disposition = $attachment[6];
  2660. $cid = $attachment[7];
  2661. if ('inline' == $disposition and array_key_exists($cid, $cidUniq)) {
  2662. continue;
  2663. }
  2664. $cidUniq[$cid] = true;
  2665. $mime[] = sprintf('--%s%s', $boundary, static::$LE);
  2666. //Only include a filename property if we have one
  2667. if (!empty($name)) {
  2668. $mime[] = sprintf(
  2669. 'Content-Type: %s; name="%s"%s',
  2670. $type,
  2671. $this->encodeHeader($this->secureHeader($name)),
  2672. static::$LE
  2673. );
  2674. } else {
  2675. $mime[] = sprintf(
  2676. 'Content-Type: %s%s',
  2677. $type,
  2678. static::$LE
  2679. );
  2680. }
  2681. // RFC1341 part 5 says 7bit is assumed if not specified
  2682. if (static::ENCODING_7BIT != $encoding) {
  2683. $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, static::$LE);
  2684. }
  2685. if (!empty($cid)) {
  2686. $mime[] = sprintf('Content-ID: <%s>%s', $cid, static::$LE);
  2687. }
  2688. // If a filename contains any of these chars, it should be quoted,
  2689. // but not otherwise: RFC2183 & RFC2045 5.1
  2690. // Fixes a warning in IETF's msglint MIME checker
  2691. // Allow for bypassing the Content-Disposition header totally
  2692. if (!(empty($disposition))) {
  2693. $encoded_name = $this->encodeHeader($this->secureHeader($name));
  2694. if (preg_match('/[ \(\)<>@,;:\\"\/\[\]\?=]/', $encoded_name)) {
  2695. $mime[] = sprintf(
  2696. 'Content-Disposition: %s; filename="%s"%s',
  2697. $disposition,
  2698. $encoded_name,
  2699. static::$LE . static::$LE
  2700. );
  2701. } else {
  2702. if (!empty($encoded_name)) {
  2703. $mime[] = sprintf(
  2704. 'Content-Disposition: %s; filename=%s%s',
  2705. $disposition,
  2706. $encoded_name,
  2707. static::$LE . static::$LE
  2708. );
  2709. } else {
  2710. $mime[] = sprintf(
  2711. 'Content-Disposition: %s%s',
  2712. $disposition,
  2713. static::$LE . static::$LE
  2714. );
  2715. }
  2716. }
  2717. } else {
  2718. $mime[] = static::$LE;
  2719. }
  2720. // Encode as string attachment
  2721. if ($bString) {
  2722. $mime[] = $this->encodeString($string, $encoding);
  2723. } else {
  2724. $mime[] = $this->encodeFile($path, $encoding);
  2725. }
  2726. if ($this->isError()) {
  2727. return '';
  2728. }
  2729. $mime[] = static::$LE;
  2730. }
  2731. }
  2732. $mime[] = sprintf('--%s--%s', $boundary, static::$LE);
  2733. return implode('', $mime);
  2734. }
  2735. /**
  2736. * Encode a file attachment in requested format.
  2737. * Returns an empty string on failure.
  2738. *
  2739. * @param string $path The full path to the file
  2740. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  2741. *
  2742. * @throws Exception
  2743. *
  2744. * @return string
  2745. */
  2746. protected function encodeFile($path, $encoding = self::ENCODING_BASE64)
  2747. {
  2748. try {
  2749. if (!static::isPermittedPath($path) || !file_exists($path)) {
  2750. throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE);
  2751. }
  2752. $file_buffer = file_get_contents($path);
  2753. if (false === $file_buffer) {
  2754. throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE);
  2755. }
  2756. $file_buffer = $this->encodeString($file_buffer, $encoding);
  2757. return $file_buffer;
  2758. } catch (Exception $exc) {
  2759. $this->setError($exc->getMessage());
  2760. return '';
  2761. }
  2762. }
  2763. /**
  2764. * Encode a string in requested format.
  2765. * Returns an empty string on failure.
  2766. *
  2767. * @param string $str The text to encode
  2768. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  2769. *
  2770. * @return string
  2771. */
  2772. public function encodeString($str, $encoding = self::ENCODING_BASE64)
  2773. {
  2774. $encoded = '';
  2775. switch (strtolower($encoding)) {
  2776. case static::ENCODING_BASE64:
  2777. $encoded = chunk_split(
  2778. base64_encode($str),
  2779. static::STD_LINE_LENGTH,
  2780. static::$LE
  2781. );
  2782. break;
  2783. case static::ENCODING_7BIT:
  2784. case static::ENCODING_8BIT:
  2785. $encoded = static::normalizeBreaks($str);
  2786. // Make sure it ends with a line break
  2787. if (substr($encoded, -(strlen(static::$LE))) != static::$LE) {
  2788. $encoded .= static::$LE;
  2789. }
  2790. break;
  2791. case static::ENCODING_BINARY:
  2792. $encoded = $str;
  2793. break;
  2794. case static::ENCODING_QUOTED_PRINTABLE:
  2795. $encoded = $this->encodeQP($str);
  2796. break;
  2797. default:
  2798. $this->setError($this->lang('encoding') . $encoding);
  2799. break;
  2800. }
  2801. return $encoded;
  2802. }
  2803. /**
  2804. * Encode a header value (not including its label) optimally.
  2805. * Picks shortest of Q, B, or none. Result includes folding if needed.
  2806. * See RFC822 definitions for phrase, comment and text positions.
  2807. *
  2808. * @param string $str The header value to encode
  2809. * @param string $position What context the string will be used in
  2810. *
  2811. * @return string
  2812. */
  2813. public function encodeHeader($str, $position = 'text')
  2814. {
  2815. $matchcount = 0;
  2816. switch (strtolower($position)) {
  2817. case 'phrase':
  2818. if (!preg_match('/[\200-\377]/', $str)) {
  2819. // Can't use addslashes as we don't know the value of magic_quotes_sybase
  2820. $encoded = addcslashes($str, "\0..\37\177\\\"");
  2821. if (($str == $encoded) and !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
  2822. return $encoded;
  2823. }
  2824. return "\"$encoded\"";
  2825. }
  2826. $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
  2827. break;
  2828. /* @noinspection PhpMissingBreakStatementInspection */
  2829. case 'comment':
  2830. $matchcount = preg_match_all('/[()"]/', $str, $matches);
  2831. //fallthrough
  2832. case 'text':
  2833. default:
  2834. $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
  2835. break;
  2836. }
  2837. //RFCs specify a maximum line length of 78 chars, however mail() will sometimes
  2838. //corrupt messages with headers longer than 65 chars. See #818
  2839. $lengthsub = 'mail' == $this->Mailer ? 13 : 0;
  2840. $maxlen = static::STD_LINE_LENGTH - $lengthsub;
  2841. // Try to select the encoding which should produce the shortest output
  2842. if ($matchcount > strlen($str) / 3) {
  2843. // More than a third of the content will need encoding, so B encoding will be most efficient
  2844. $encoding = 'B';
  2845. //This calculation is:
  2846. // max line length
  2847. // - shorten to avoid mail() corruption
  2848. // - Q/B encoding char overhead ("` =?<charset>?[QB]?<content>?=`")
  2849. // - charset name length
  2850. $maxlen = static::STD_LINE_LENGTH - $lengthsub - 8 - strlen($this->CharSet);
  2851. if ($this->hasMultiBytes($str)) {
  2852. // Use a custom function which correctly encodes and wraps long
  2853. // multibyte strings without breaking lines within a character
  2854. $encoded = $this->base64EncodeWrapMB($str, "\n");
  2855. } else {
  2856. $encoded = base64_encode($str);
  2857. $maxlen -= $maxlen % 4;
  2858. $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
  2859. }
  2860. $encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet . "?$encoding?\\1?=", $encoded);
  2861. } elseif ($matchcount > 0) {
  2862. //1 or more chars need encoding, use Q-encode
  2863. $encoding = 'Q';
  2864. //Recalc max line length for Q encoding - see comments on B encode
  2865. $maxlen = static::STD_LINE_LENGTH - $lengthsub - 8 - strlen($this->CharSet);
  2866. $encoded = $this->encodeQ($str, $position);
  2867. $encoded = $this->wrapText($encoded, $maxlen, true);
  2868. $encoded = str_replace('=' . static::$LE, "\n", trim($encoded));
  2869. $encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet . "?$encoding?\\1?=", $encoded);
  2870. } elseif (strlen($str) > $maxlen) {
  2871. //No chars need encoding, but line is too long, so fold it
  2872. $encoded = trim($this->wrapText($str, $maxlen, false));
  2873. if ($str == $encoded) {
  2874. //Wrapping nicely didn't work, wrap hard instead
  2875. $encoded = trim(chunk_split($str, static::STD_LINE_LENGTH, static::$LE));
  2876. }
  2877. $encoded = str_replace(static::$LE, "\n", trim($encoded));
  2878. $encoded = preg_replace('/^(.*)$/m', ' \\1', $encoded);
  2879. } else {
  2880. //No reformatting needed
  2881. return $str;
  2882. }
  2883. return trim(static::normalizeBreaks($encoded));
  2884. }
  2885. /**
  2886. * Check if a string contains multi-byte characters.
  2887. *
  2888. * @param string $str multi-byte text to wrap encode
  2889. *
  2890. * @return bool
  2891. */
  2892. public function hasMultiBytes($str)
  2893. {
  2894. if (function_exists('mb_strlen')) {
  2895. return strlen($str) > mb_strlen($str, $this->CharSet);
  2896. }
  2897. // Assume no multibytes (we can't handle without mbstring functions anyway)
  2898. return false;
  2899. }
  2900. /**
  2901. * Does a string contain any 8-bit chars (in any charset)?
  2902. *
  2903. * @param string $text
  2904. *
  2905. * @return bool
  2906. */
  2907. public function has8bitChars($text)
  2908. {
  2909. return (bool) preg_match('/[\x80-\xFF]/', $text);
  2910. }
  2911. /**
  2912. * Encode and wrap long multibyte strings for mail headers
  2913. * without breaking lines within a character.
  2914. * Adapted from a function by paravoid.
  2915. *
  2916. * @see http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283
  2917. *
  2918. * @param string $str multi-byte text to wrap encode
  2919. * @param string $linebreak string to use as linefeed/end-of-line
  2920. *
  2921. * @return string
  2922. */
  2923. public function base64EncodeWrapMB($str, $linebreak = null)
  2924. {
  2925. $start = '=?' . $this->CharSet . '?B?';
  2926. $end = '?=';
  2927. $encoded = '';
  2928. if (null === $linebreak) {
  2929. $linebreak = static::$LE;
  2930. }
  2931. $mb_length = mb_strlen($str, $this->CharSet);
  2932. // Each line must have length <= 75, including $start and $end
  2933. $length = 75 - strlen($start) - strlen($end);
  2934. // Average multi-byte ratio
  2935. $ratio = $mb_length / strlen($str);
  2936. // Base64 has a 4:3 ratio
  2937. $avgLength = floor($length * $ratio * .75);
  2938. for ($i = 0; $i < $mb_length; $i += $offset) {
  2939. $lookBack = 0;
  2940. do {
  2941. $offset = $avgLength - $lookBack;
  2942. $chunk = mb_substr($str, $i, $offset, $this->CharSet);
  2943. $chunk = base64_encode($chunk);
  2944. ++$lookBack;
  2945. } while (strlen($chunk) > $length);
  2946. $encoded .= $chunk . $linebreak;
  2947. }
  2948. // Chomp the last linefeed
  2949. return substr($encoded, 0, -strlen($linebreak));
  2950. }
  2951. /**
  2952. * Encode a string in quoted-printable format.
  2953. * According to RFC2045 section 6.7.
  2954. *
  2955. * @param string $string The text to encode
  2956. *
  2957. * @return string
  2958. */
  2959. public function encodeQP($string)
  2960. {
  2961. return static::normalizeBreaks(quoted_printable_encode($string));
  2962. }
  2963. /**
  2964. * Encode a string using Q encoding.
  2965. *
  2966. * @see http://tools.ietf.org/html/rfc2047#section-4.2
  2967. *
  2968. * @param string $str the text to encode
  2969. * @param string $position Where the text is going to be used, see the RFC for what that means
  2970. *
  2971. * @return string
  2972. */
  2973. public function encodeQ($str, $position = 'text')
  2974. {
  2975. // There should not be any EOL in the string
  2976. $pattern = '';
  2977. $encoded = str_replace(["\r", "\n"], '', $str);
  2978. switch (strtolower($position)) {
  2979. case 'phrase':
  2980. // RFC 2047 section 5.3
  2981. $pattern = '^A-Za-z0-9!*+\/ -';
  2982. break;
  2983. /*
  2984. * RFC 2047 section 5.2.
  2985. * Build $pattern without including delimiters and []
  2986. */
  2987. /* @noinspection PhpMissingBreakStatementInspection */
  2988. case 'comment':
  2989. $pattern = '\(\)"';
  2990. /* Intentional fall through */
  2991. case 'text':
  2992. default:
  2993. // RFC 2047 section 5.1
  2994. // Replace every high ascii, control, =, ? and _ characters
  2995. /** @noinspection SuspiciousAssignmentsInspection */
  2996. $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern;
  2997. break;
  2998. }
  2999. $matches = [];
  3000. if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
  3001. // If the string contains an '=', make sure it's the first thing we replace
  3002. // so as to avoid double-encoding
  3003. $eqkey = array_search('=', $matches[0]);
  3004. if (false !== $eqkey) {
  3005. unset($matches[0][$eqkey]);
  3006. array_unshift($matches[0], '=');
  3007. }
  3008. foreach (array_unique($matches[0]) as $char) {
  3009. $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
  3010. }
  3011. }
  3012. // Replace spaces with _ (more readable than =20)
  3013. // RFC 2047 section 4.2(2)
  3014. return str_replace(' ', '_', $encoded);
  3015. }
  3016. /**
  3017. * Add a string or binary attachment (non-filesystem).
  3018. * This method can be used to attach ascii or binary data,
  3019. * such as a BLOB record from a database.
  3020. *
  3021. * @param string $string String attachment data
  3022. * @param string $filename Name of the attachment
  3023. * @param string $encoding File encoding (see $Encoding)
  3024. * @param string $type File extension (MIME) type
  3025. * @param string $disposition Disposition to use
  3026. */
  3027. public function addStringAttachment(
  3028. $string,
  3029. $filename,
  3030. $encoding = self::ENCODING_BASE64,
  3031. $type = '',
  3032. $disposition = 'attachment'
  3033. ) {
  3034. // If a MIME type is not specified, try to work it out from the file name
  3035. if ('' == $type) {
  3036. $type = static::filenameToType($filename);
  3037. }
  3038. // Append to $attachment array
  3039. $this->attachment[] = [
  3040. 0 => $string,
  3041. 1 => $filename,
  3042. 2 => basename($filename),
  3043. 3 => $encoding,
  3044. 4 => $type,
  3045. 5 => true, // isStringAttachment
  3046. 6 => $disposition,
  3047. 7 => 0,
  3048. ];
  3049. }
  3050. /**
  3051. * Add an embedded (inline) attachment from a file.
  3052. * This can include images, sounds, and just about any other document type.
  3053. * These differ from 'regular' attachments in that they are intended to be
  3054. * displayed inline with the message, not just attached for download.
  3055. * This is used in HTML messages that embed the images
  3056. * the HTML refers to using the $cid value.
  3057. * Never use a user-supplied path to a file!
  3058. *
  3059. * @param string $path Path to the attachment
  3060. * @param string $cid Content ID of the attachment; Use this to reference
  3061. * the content when using an embedded image in HTML
  3062. * @param string $name Overrides the attachment name
  3063. * @param string $encoding File encoding (see $Encoding)
  3064. * @param string $type File MIME type
  3065. * @param string $disposition Disposition to use
  3066. *
  3067. * @return bool True on successfully adding an attachment
  3068. */
  3069. public function addEmbeddedImage($path, $cid, $name = '', $encoding = self::ENCODING_BASE64, $type = '', $disposition = 'inline')
  3070. {
  3071. if (!static::isPermittedPath($path) || !@is_file($path)) {
  3072. $this->setError($this->lang('file_access') . $path);
  3073. return false;
  3074. }
  3075. // If a MIME type is not specified, try to work it out from the file name
  3076. if ('' == $type) {
  3077. $type = static::filenameToType($path);
  3078. }
  3079. $filename = basename($path);
  3080. if ('' == $name) {
  3081. $name = $filename;
  3082. }
  3083. // Append to $attachment array
  3084. $this->attachment[] = [
  3085. 0 => $path,
  3086. 1 => $filename,
  3087. 2 => $name,
  3088. 3 => $encoding,
  3089. 4 => $type,
  3090. 5 => false, // isStringAttachment
  3091. 6 => $disposition,
  3092. 7 => $cid,
  3093. ];
  3094. return true;
  3095. }
  3096. /**
  3097. * Add an embedded stringified attachment.
  3098. * This can include images, sounds, and just about any other document type.
  3099. * If your filename doesn't contain an extension, be sure to set the $type to an appropriate MIME type.
  3100. *
  3101. * @param string $string The attachment binary data
  3102. * @param string $cid Content ID of the attachment; Use this to reference
  3103. * the content when using an embedded image in HTML
  3104. * @param string $name A filename for the attachment. If this contains an extension,
  3105. * PHPMailer will attempt to set a MIME type for the attachment.
  3106. * For example 'file.jpg' would get an 'image/jpeg' MIME type.
  3107. * @param string $encoding File encoding (see $Encoding), defaults to 'base64'
  3108. * @param string $type MIME type - will be used in preference to any automatically derived type
  3109. * @param string $disposition Disposition to use
  3110. *
  3111. * @return bool True on successfully adding an attachment
  3112. */
  3113. public function addStringEmbeddedImage(
  3114. $string,
  3115. $cid,
  3116. $name = '',
  3117. $encoding = self::ENCODING_BASE64,
  3118. $type = '',
  3119. $disposition = 'inline'
  3120. ) {
  3121. // If a MIME type is not specified, try to work it out from the name
  3122. if ('' == $type and !empty($name)) {
  3123. $type = static::filenameToType($name);
  3124. }
  3125. // Append to $attachment array
  3126. $this->attachment[] = [
  3127. 0 => $string,
  3128. 1 => $name,
  3129. 2 => $name,
  3130. 3 => $encoding,
  3131. 4 => $type,
  3132. 5 => true, // isStringAttachment
  3133. 6 => $disposition,
  3134. 7 => $cid,
  3135. ];
  3136. return true;
  3137. }
  3138. /**
  3139. * Check if an embedded attachment is present with this cid.
  3140. *
  3141. * @param string $cid
  3142. *
  3143. * @return bool
  3144. */
  3145. protected function cidExists($cid)
  3146. {
  3147. foreach ($this->attachment as $attachment) {
  3148. if ('inline' == $attachment[6] and $cid == $attachment[7]) {
  3149. return true;
  3150. }
  3151. }
  3152. return false;
  3153. }
  3154. /**
  3155. * Check if an inline attachment is present.
  3156. *
  3157. * @return bool
  3158. */
  3159. public function inlineImageExists()
  3160. {
  3161. foreach ($this->attachment as $attachment) {
  3162. if ('inline' == $attachment[6]) {
  3163. return true;
  3164. }
  3165. }
  3166. return false;
  3167. }
  3168. /**
  3169. * Check if an attachment (non-inline) is present.
  3170. *
  3171. * @return bool
  3172. */
  3173. public function attachmentExists()
  3174. {
  3175. foreach ($this->attachment as $attachment) {
  3176. if ('attachment' == $attachment[6]) {
  3177. return true;
  3178. }
  3179. }
  3180. return false;
  3181. }
  3182. /**
  3183. * Check if this message has an alternative body set.
  3184. *
  3185. * @return bool
  3186. */
  3187. public function alternativeExists()
  3188. {
  3189. return !empty($this->AltBody);
  3190. }
  3191. /**
  3192. * Clear queued addresses of given kind.
  3193. *
  3194. * @param string $kind 'to', 'cc', or 'bcc'
  3195. */
  3196. public function clearQueuedAddresses($kind)
  3197. {
  3198. $this->RecipientsQueue = array_filter(
  3199. $this->RecipientsQueue,
  3200. function ($params) use ($kind) {
  3201. return $params[0] != $kind;
  3202. }
  3203. );
  3204. }
  3205. /**
  3206. * Clear all To recipients.
  3207. */
  3208. public function clearAddresses()
  3209. {
  3210. foreach ($this->to as $to) {
  3211. unset($this->all_recipients[strtolower($to[0])]);
  3212. }
  3213. $this->to = [];
  3214. $this->clearQueuedAddresses('to');
  3215. }
  3216. /**
  3217. * Clear all CC recipients.
  3218. */
  3219. public function clearCCs()
  3220. {
  3221. foreach ($this->cc as $cc) {
  3222. unset($this->all_recipients[strtolower($cc[0])]);
  3223. }
  3224. $this->cc = [];
  3225. $this->clearQueuedAddresses('cc');
  3226. }
  3227. /**
  3228. * Clear all BCC recipients.
  3229. */
  3230. public function clearBCCs()
  3231. {
  3232. foreach ($this->bcc as $bcc) {
  3233. unset($this->all_recipients[strtolower($bcc[0])]);
  3234. }
  3235. $this->bcc = [];
  3236. $this->clearQueuedAddresses('bcc');
  3237. }
  3238. /**
  3239. * Clear all ReplyTo recipients.
  3240. */
  3241. public function clearReplyTos()
  3242. {
  3243. $this->ReplyTo = [];
  3244. $this->ReplyToQueue = [];
  3245. }
  3246. /**
  3247. * Clear all recipient types.
  3248. */
  3249. public function clearAllRecipients()
  3250. {
  3251. $this->to = [];
  3252. $this->cc = [];
  3253. $this->bcc = [];
  3254. $this->all_recipients = [];
  3255. $this->RecipientsQueue = [];
  3256. }
  3257. /**
  3258. * Clear all filesystem, string, and binary attachments.
  3259. */
  3260. public function clearAttachments()
  3261. {
  3262. $this->attachment = [];
  3263. }
  3264. /**
  3265. * Clear all custom headers.
  3266. */
  3267. public function clearCustomHeaders()
  3268. {
  3269. $this->CustomHeader = [];
  3270. }
  3271. /**
  3272. * Add an error message to the error container.
  3273. *
  3274. * @param string $msg
  3275. */
  3276. protected function setError($msg)
  3277. {
  3278. ++$this->error_count;
  3279. if ('smtp' == $this->Mailer and null !== $this->smtp) {
  3280. $lasterror = $this->smtp->getError();
  3281. if (!empty($lasterror['error'])) {
  3282. $msg .= $this->lang('smtp_error') . $lasterror['error'];
  3283. if (!empty($lasterror['detail'])) {
  3284. $msg .= ' Detail: ' . $lasterror['detail'];
  3285. }
  3286. if (!empty($lasterror['smtp_code'])) {
  3287. $msg .= ' SMTP code: ' . $lasterror['smtp_code'];
  3288. }
  3289. if (!empty($lasterror['smtp_code_ex'])) {
  3290. $msg .= ' Additional SMTP info: ' . $lasterror['smtp_code_ex'];
  3291. }
  3292. }
  3293. }
  3294. $this->ErrorInfo = $msg;
  3295. }
  3296. /**
  3297. * Return an RFC 822 formatted date.
  3298. *
  3299. * @return string
  3300. */
  3301. public static function rfcDate()
  3302. {
  3303. // Set the time zone to whatever the default is to avoid 500 errors
  3304. // Will default to UTC if it's not set properly in php.ini
  3305. date_default_timezone_set(@date_default_timezone_get());
  3306. return date('D, j M Y H:i:s O');
  3307. }
  3308. /**
  3309. * Get the server hostname.
  3310. * Returns 'localhost.localdomain' if unknown.
  3311. *
  3312. * @return string
  3313. */
  3314. protected function serverHostname()
  3315. {
  3316. $result = '';
  3317. if (!empty($this->Hostname)) {
  3318. $result = $this->Hostname;
  3319. } elseif (isset($_SERVER) and array_key_exists('SERVER_NAME', $_SERVER)) {
  3320. $result = $_SERVER['SERVER_NAME'];
  3321. } elseif (function_exists('gethostname') and gethostname() !== false) {
  3322. $result = gethostname();
  3323. } elseif (php_uname('n') !== false) {
  3324. $result = php_uname('n');
  3325. }
  3326. if (!static::isValidHost($result)) {
  3327. return 'localhost.localdomain';
  3328. }
  3329. return $result;
  3330. }
  3331. /**
  3332. * Validate whether a string contains a valid value to use as a hostname or IP address.
  3333. * IPv6 addresses must include [], e.g. `[::1]`, not just `::1`.
  3334. *
  3335. * @param string $host The host name or IP address to check
  3336. *
  3337. * @return bool
  3338. */
  3339. public static function isValidHost($host)
  3340. {
  3341. //Simple syntax limits
  3342. if (empty($host)
  3343. or !is_string($host)
  3344. or strlen($host) > 256
  3345. ) {
  3346. return false;
  3347. }
  3348. //Looks like a bracketed IPv6 address
  3349. if (trim($host, '[]') != $host) {
  3350. return (bool) filter_var(trim($host, '[]'), FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
  3351. }
  3352. //If removing all the dots results in a numeric string, it must be an IPv4 address.
  3353. //Need to check this first because otherwise things like `999.0.0.0` are considered valid host names
  3354. if (is_numeric(str_replace('.', '', $host))) {
  3355. //Is it a valid IPv4 address?
  3356. return (bool) filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
  3357. }
  3358. if (filter_var('http://' . $host, FILTER_VALIDATE_URL)) {
  3359. //Is it a syntactically valid hostname?
  3360. return true;
  3361. }
  3362. return false;
  3363. }
  3364. /**
  3365. * Get an error message in the current language.
  3366. *
  3367. * @param string $key
  3368. *
  3369. * @return string
  3370. */
  3371. protected function lang($key)
  3372. {
  3373. if (count($this->language) < 1) {
  3374. $this->setLanguage('en'); // set the default language
  3375. }
  3376. if (array_key_exists($key, $this->language)) {
  3377. if ('smtp_connect_failed' == $key) {
  3378. //Include a link to troubleshooting docs on SMTP connection failure
  3379. //this is by far the biggest cause of support questions
  3380. //but it's usually not PHPMailer's fault.
  3381. return $this->language[$key] . ' https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting';
  3382. }
  3383. return $this->language[$key];
  3384. }
  3385. //Return the key as a fallback
  3386. return $key;
  3387. }
  3388. /**
  3389. * Check if an error occurred.
  3390. *
  3391. * @return bool True if an error did occur
  3392. */
  3393. public function isError()
  3394. {
  3395. return $this->error_count > 0;
  3396. }
  3397. /**
  3398. * Add a custom header.
  3399. * $name value can be overloaded to contain
  3400. * both header name and value (name:value).
  3401. *
  3402. * @param string $name Custom header name
  3403. * @param string|null $value Header value
  3404. */
  3405. public function addCustomHeader($name, $value = null)
  3406. {
  3407. if (null === $value) {
  3408. // Value passed in as name:value
  3409. $this->CustomHeader[] = explode(':', $name, 2);
  3410. } else {
  3411. $this->CustomHeader[] = [$name, $value];
  3412. }
  3413. }
  3414. /**
  3415. * Returns all custom headers.
  3416. *
  3417. * @return array
  3418. */
  3419. public function getCustomHeaders()
  3420. {
  3421. return $this->CustomHeader;
  3422. }
  3423. /**
  3424. * Create a message body from an HTML string.
  3425. * Automatically inlines images and creates a plain-text version by converting the HTML,
  3426. * overwriting any existing values in Body and AltBody.
  3427. * Do not source $message content from user input!
  3428. * $basedir is prepended when handling relative URLs, e.g. <img src="/images/a.png"> and must not be empty
  3429. * will look for an image file in $basedir/images/a.png and convert it to inline.
  3430. * If you don't provide a $basedir, relative paths will be left untouched (and thus probably break in email)
  3431. * Converts data-uri images into embedded attachments.
  3432. * If you don't want to apply these transformations to your HTML, just set Body and AltBody directly.
  3433. *
  3434. * @param string $message HTML message string
  3435. * @param string $basedir Absolute path to a base directory to prepend to relative paths to images
  3436. * @param bool|callable $advanced Whether to use the internal HTML to text converter
  3437. * or your own custom converter @see PHPMailer::html2text()
  3438. *
  3439. * @return string $message The transformed message Body
  3440. */
  3441. public function msgHTML($message, $basedir = '', $advanced = false)
  3442. {
  3443. preg_match_all('/(src|background)=["\'](.*)["\']/Ui', $message, $images);
  3444. if (array_key_exists(2, $images)) {
  3445. if (strlen($basedir) > 1 && '/' != substr($basedir, -1)) {
  3446. // Ensure $basedir has a trailing /
  3447. $basedir .= '/';
  3448. }
  3449. foreach ($images[2] as $imgindex => $url) {
  3450. // Convert data URIs into embedded images
  3451. //e.g. "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
  3452. if (preg_match('#^data:(image/(?:jpe?g|gif|png));?(base64)?,(.+)#', $url, $match)) {
  3453. if (count($match) == 4 and static::ENCODING_BASE64 == $match[2]) {
  3454. $data = base64_decode($match[3]);
  3455. } elseif ('' == $match[2]) {
  3456. $data = rawurldecode($match[3]);
  3457. } else {
  3458. //Not recognised so leave it alone
  3459. continue;
  3460. }
  3461. //Hash the decoded data, not the URL so that the same data-URI image used in multiple places
  3462. //will only be embedded once, even if it used a different encoding
  3463. $cid = hash('sha256', $data) . '@phpmailer.0'; // RFC2392 S 2
  3464. if (!$this->cidExists($cid)) {
  3465. $this->addStringEmbeddedImage($data, $cid, 'embed' . $imgindex, static::ENCODING_BASE64, $match[1]);
  3466. }
  3467. $message = str_replace(
  3468. $images[0][$imgindex],
  3469. $images[1][$imgindex] . '="cid:' . $cid . '"',
  3470. $message
  3471. );
  3472. continue;
  3473. }
  3474. if (// Only process relative URLs if a basedir is provided (i.e. no absolute local paths)
  3475. !empty($basedir)
  3476. // Ignore URLs containing parent dir traversal (..)
  3477. and (strpos($url, '..') === false)
  3478. // Do not change urls that are already inline images
  3479. and 0 !== strpos($url, 'cid:')
  3480. // Do not change absolute URLs, including anonymous protocol
  3481. and !preg_match('#^[a-z][a-z0-9+.-]*:?//#i', $url)
  3482. ) {
  3483. $filename = basename($url);
  3484. $directory = dirname($url);
  3485. if ('.' == $directory) {
  3486. $directory = '';
  3487. }
  3488. $cid = hash('sha256', $url) . '@phpmailer.0'; // RFC2392 S 2
  3489. if (strlen($basedir) > 1 and '/' != substr($basedir, -1)) {
  3490. $basedir .= '/';
  3491. }
  3492. if (strlen($directory) > 1 and '/' != substr($directory, -1)) {
  3493. $directory .= '/';
  3494. }
  3495. if ($this->addEmbeddedImage(
  3496. $basedir . $directory . $filename,
  3497. $cid,
  3498. $filename,
  3499. static::ENCODING_BASE64,
  3500. static::_mime_types((string) static::mb_pathinfo($filename, PATHINFO_EXTENSION))
  3501. )
  3502. ) {
  3503. $message = preg_replace(
  3504. '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui',
  3505. $images[1][$imgindex] . '="cid:' . $cid . '"',
  3506. $message
  3507. );
  3508. }
  3509. }
  3510. }
  3511. }
  3512. $this->isHTML(true);
  3513. // Convert all message body line breaks to LE, makes quoted-printable encoding work much better
  3514. $this->Body = static::normalizeBreaks($message);
  3515. $this->AltBody = static::normalizeBreaks($this->html2text($message, $advanced));
  3516. if (!$this->alternativeExists()) {
  3517. $this->AltBody = 'This is an HTML-only message. To view it, activate HTML in your email application.'
  3518. . static::$LE;
  3519. }
  3520. return $this->Body;
  3521. }
  3522. /**
  3523. * Convert an HTML string into plain text.
  3524. * This is used by msgHTML().
  3525. * Note - older versions of this function used a bundled advanced converter
  3526. * which was removed for license reasons in #232.
  3527. * Example usage:
  3528. *
  3529. * ```php
  3530. * // Use default conversion
  3531. * $plain = $mail->html2text($html);
  3532. * // Use your own custom converter
  3533. * $plain = $mail->html2text($html, function($html) {
  3534. * $converter = new MyHtml2text($html);
  3535. * return $converter->get_text();
  3536. * });
  3537. * ```
  3538. *
  3539. * @param string $html The HTML text to convert
  3540. * @param bool|callable $advanced Any boolean value to use the internal converter,
  3541. * or provide your own callable for custom conversion
  3542. *
  3543. * @return string
  3544. */
  3545. public function html2text($html, $advanced = false)
  3546. {
  3547. if (is_callable($advanced)) {
  3548. return call_user_func($advanced, $html);
  3549. }
  3550. return html_entity_decode(
  3551. trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))),
  3552. ENT_QUOTES,
  3553. $this->CharSet
  3554. );
  3555. }
  3556. /**
  3557. * Get the MIME type for a file extension.
  3558. *
  3559. * @param string $ext File extension
  3560. *
  3561. * @return string MIME type of file
  3562. */
  3563. public static function _mime_types($ext = '')
  3564. {
  3565. $mimes = [
  3566. 'xl' => 'application/excel',
  3567. 'js' => 'application/javascript',
  3568. 'hqx' => 'application/mac-binhex40',
  3569. 'cpt' => 'application/mac-compactpro',
  3570. 'bin' => 'application/macbinary',
  3571. 'doc' => 'application/msword',
  3572. 'word' => 'application/msword',
  3573. 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  3574. 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
  3575. 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
  3576. 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
  3577. 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  3578. 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
  3579. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  3580. 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
  3581. 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
  3582. 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
  3583. 'class' => 'application/octet-stream',
  3584. 'dll' => 'application/octet-stream',
  3585. 'dms' => 'application/octet-stream',
  3586. 'exe' => 'application/octet-stream',
  3587. 'lha' => 'application/octet-stream',
  3588. 'lzh' => 'application/octet-stream',
  3589. 'psd' => 'application/octet-stream',
  3590. 'sea' => 'application/octet-stream',
  3591. 'so' => 'application/octet-stream',
  3592. 'oda' => 'application/oda',
  3593. 'pdf' => 'application/pdf',
  3594. 'ai' => 'application/postscript',
  3595. 'eps' => 'application/postscript',
  3596. 'ps' => 'application/postscript',
  3597. 'smi' => 'application/smil',
  3598. 'smil' => 'application/smil',
  3599. 'mif' => 'application/vnd.mif',
  3600. 'xls' => 'application/vnd.ms-excel',
  3601. 'ppt' => 'application/vnd.ms-powerpoint',
  3602. 'wbxml' => 'application/vnd.wap.wbxml',
  3603. 'wmlc' => 'application/vnd.wap.wmlc',
  3604. 'dcr' => 'application/x-director',
  3605. 'dir' => 'application/x-director',
  3606. 'dxr' => 'application/x-director',
  3607. 'dvi' => 'application/x-dvi',
  3608. 'gtar' => 'application/x-gtar',
  3609. 'php3' => 'application/x-httpd-php',
  3610. 'php4' => 'application/x-httpd-php',
  3611. 'php' => 'application/x-httpd-php',
  3612. 'phtml' => 'application/x-httpd-php',
  3613. 'phps' => 'application/x-httpd-php-source',
  3614. 'swf' => 'application/x-shockwave-flash',
  3615. 'sit' => 'application/x-stuffit',
  3616. 'tar' => 'application/x-tar',
  3617. 'tgz' => 'application/x-tar',
  3618. 'xht' => 'application/xhtml+xml',
  3619. 'xhtml' => 'application/xhtml+xml',
  3620. 'zip' => 'application/zip',
  3621. 'mid' => 'audio/midi',
  3622. 'midi' => 'audio/midi',
  3623. 'mp2' => 'audio/mpeg',
  3624. 'mp3' => 'audio/mpeg',
  3625. 'm4a' => 'audio/mp4',
  3626. 'mpga' => 'audio/mpeg',
  3627. 'aif' => 'audio/x-aiff',
  3628. 'aifc' => 'audio/x-aiff',
  3629. 'aiff' => 'audio/x-aiff',
  3630. 'ram' => 'audio/x-pn-realaudio',
  3631. 'rm' => 'audio/x-pn-realaudio',
  3632. 'rpm' => 'audio/x-pn-realaudio-plugin',
  3633. 'ra' => 'audio/x-realaudio',
  3634. 'wav' => 'audio/x-wav',
  3635. 'mka' => 'audio/x-matroska',
  3636. 'bmp' => 'image/bmp',
  3637. 'gif' => 'image/gif',
  3638. 'jpeg' => 'image/jpeg',
  3639. 'jpe' => 'image/jpeg',
  3640. 'jpg' => 'image/jpeg',
  3641. 'png' => 'image/png',
  3642. 'tiff' => 'image/tiff',
  3643. 'tif' => 'image/tiff',
  3644. 'webp' => 'image/webp',
  3645. 'heif' => 'image/heif',
  3646. 'heifs' => 'image/heif-sequence',
  3647. 'heic' => 'image/heic',
  3648. 'heics' => 'image/heic-sequence',
  3649. 'eml' => 'message/rfc822',
  3650. 'css' => 'text/css',
  3651. 'html' => 'text/html',
  3652. 'htm' => 'text/html',
  3653. 'shtml' => 'text/html',
  3654. 'log' => 'text/plain',
  3655. 'text' => 'text/plain',
  3656. 'txt' => 'text/plain',
  3657. 'rtx' => 'text/richtext',
  3658. 'rtf' => 'text/rtf',
  3659. 'vcf' => 'text/vcard',
  3660. 'vcard' => 'text/vcard',
  3661. 'ics' => 'text/calendar',
  3662. 'xml' => 'text/xml',
  3663. 'xsl' => 'text/xml',
  3664. 'wmv' => 'video/x-ms-wmv',
  3665. 'mpeg' => 'video/mpeg',
  3666. 'mpe' => 'video/mpeg',
  3667. 'mpg' => 'video/mpeg',
  3668. 'mp4' => 'video/mp4',
  3669. 'm4v' => 'video/mp4',
  3670. 'mov' => 'video/quicktime',
  3671. 'qt' => 'video/quicktime',
  3672. 'rv' => 'video/vnd.rn-realvideo',
  3673. 'avi' => 'video/x-msvideo',
  3674. 'movie' => 'video/x-sgi-movie',
  3675. 'webm' => 'video/webm',
  3676. 'mkv' => 'video/x-matroska',
  3677. ];
  3678. $ext = strtolower($ext);
  3679. if (array_key_exists($ext, $mimes)) {
  3680. return $mimes[$ext];
  3681. }
  3682. return 'application/octet-stream';
  3683. }
  3684. /**
  3685. * Map a file name to a MIME type.
  3686. * Defaults to 'application/octet-stream', i.e.. arbitrary binary data.
  3687. *
  3688. * @param string $filename A file name or full path, does not need to exist as a file
  3689. *
  3690. * @return string
  3691. */
  3692. public static function filenameToType($filename)
  3693. {
  3694. // In case the path is a URL, strip any query string before getting extension
  3695. $qpos = strpos($filename, '?');
  3696. if (false !== $qpos) {
  3697. $filename = substr($filename, 0, $qpos);
  3698. }
  3699. $ext = static::mb_pathinfo($filename, PATHINFO_EXTENSION);
  3700. return static::_mime_types($ext);
  3701. }
  3702. /**
  3703. * Multi-byte-safe pathinfo replacement.
  3704. * Drop-in replacement for pathinfo(), but multibyte- and cross-platform-safe.
  3705. *
  3706. * @see http://www.php.net/manual/en/function.pathinfo.php#107461
  3707. *
  3708. * @param string $path A filename or path, does not need to exist as a file
  3709. * @param int|string $options Either a PATHINFO_* constant,
  3710. * or a string name to return only the specified piece
  3711. *
  3712. * @return string|array
  3713. */
  3714. public static function mb_pathinfo($path, $options = null)
  3715. {
  3716. $ret = ['dirname' => '', 'basename' => '', 'extension' => '', 'filename' => ''];
  3717. $pathinfo = [];
  3718. if (preg_match('#^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$#im', $path, $pathinfo)) {
  3719. if (array_key_exists(1, $pathinfo)) {
  3720. $ret['dirname'] = $pathinfo[1];
  3721. }
  3722. if (array_key_exists(2, $pathinfo)) {
  3723. $ret['basename'] = $pathinfo[2];
  3724. }
  3725. if (array_key_exists(5, $pathinfo)) {
  3726. $ret['extension'] = $pathinfo[5];
  3727. }
  3728. if (array_key_exists(3, $pathinfo)) {
  3729. $ret['filename'] = $pathinfo[3];
  3730. }
  3731. }
  3732. switch ($options) {
  3733. case PATHINFO_DIRNAME:
  3734. case 'dirname':
  3735. return $ret['dirname'];
  3736. case PATHINFO_BASENAME:
  3737. case 'basename':
  3738. return $ret['basename'];
  3739. case PATHINFO_EXTENSION:
  3740. case 'extension':
  3741. return $ret['extension'];
  3742. case PATHINFO_FILENAME:
  3743. case 'filename':
  3744. return $ret['filename'];
  3745. default:
  3746. return $ret;
  3747. }
  3748. }
  3749. /**
  3750. * Set or reset instance properties.
  3751. * You should avoid this function - it's more verbose, less efficient, more error-prone and
  3752. * harder to debug than setting properties directly.
  3753. * Usage Example:
  3754. * `$mail->set('SMTPSecure', 'tls');`
  3755. * is the same as:
  3756. * `$mail->SMTPSecure = 'tls';`.
  3757. *
  3758. * @param string $name The property name to set
  3759. * @param mixed $value The value to set the property to
  3760. *
  3761. * @return bool
  3762. */
  3763. public function set($name, $value = '')
  3764. {
  3765. if (property_exists($this, $name)) {
  3766. $this->$name = $value;
  3767. return true;
  3768. }
  3769. $this->setError($this->lang('variable_set') . $name);
  3770. return false;
  3771. }
  3772. /**
  3773. * Strip newlines to prevent header injection.
  3774. *
  3775. * @param string $str
  3776. *
  3777. * @return string
  3778. */
  3779. public function secureHeader($str)
  3780. {
  3781. return trim(str_replace(["\r", "\n"], '', $str));
  3782. }
  3783. /**
  3784. * Normalize line breaks in a string.
  3785. * Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format.
  3786. * Defaults to CRLF (for message bodies) and preserves consecutive breaks.
  3787. *
  3788. * @param string $text
  3789. * @param string $breaktype What kind of line break to use; defaults to static::$LE
  3790. *
  3791. * @return string
  3792. */
  3793. public static function normalizeBreaks($text, $breaktype = null)
  3794. {
  3795. if (null === $breaktype) {
  3796. $breaktype = static::$LE;
  3797. }
  3798. // Normalise to \n
  3799. $text = str_replace(["\r\n", "\r"], "\n", $text);
  3800. // Now convert LE as needed
  3801. if ("\n" !== $breaktype) {
  3802. $text = str_replace("\n", $breaktype, $text);
  3803. }
  3804. return $text;
  3805. }
  3806. /**
  3807. * Return the current line break format string.
  3808. *
  3809. * @return string
  3810. */
  3811. public static function getLE()
  3812. {
  3813. return static::$LE;
  3814. }
  3815. /**
  3816. * Set the line break format string, e.g. "\r\n".
  3817. *
  3818. * @param string $le
  3819. */
  3820. protected static function setLE($le)
  3821. {
  3822. static::$LE = $le;
  3823. }
  3824. /**
  3825. * Set the public and private key files and password for S/MIME signing.
  3826. *
  3827. * @param string $cert_filename
  3828. * @param string $key_filename
  3829. * @param string $key_pass Password for private key
  3830. * @param string $extracerts_filename Optional path to chain certificate
  3831. */
  3832. public function sign($cert_filename, $key_filename, $key_pass, $extracerts_filename = '')
  3833. {
  3834. $this->sign_cert_file = $cert_filename;
  3835. $this->sign_key_file = $key_filename;
  3836. $this->sign_key_pass = $key_pass;
  3837. $this->sign_extracerts_file = $extracerts_filename;
  3838. }
  3839. /**
  3840. * Quoted-Printable-encode a DKIM header.
  3841. *
  3842. * @param string $txt
  3843. *
  3844. * @return string
  3845. */
  3846. public function DKIM_QP($txt)
  3847. {
  3848. $line = '';
  3849. $len = strlen($txt);
  3850. for ($i = 0; $i < $len; ++$i) {
  3851. $ord = ord($txt[$i]);
  3852. if (((0x21 <= $ord) and ($ord <= 0x3A)) or $ord == 0x3C or ((0x3E <= $ord) and ($ord <= 0x7E))) {
  3853. $line .= $txt[$i];
  3854. } else {
  3855. $line .= '=' . sprintf('%02X', $ord);
  3856. }
  3857. }
  3858. return $line;
  3859. }
  3860. /**
  3861. * Generate a DKIM signature.
  3862. *
  3863. * @param string $signHeader
  3864. *
  3865. * @throws Exception
  3866. *
  3867. * @return string The DKIM signature value
  3868. */
  3869. public function DKIM_Sign($signHeader)
  3870. {
  3871. if (!defined('PKCS7_TEXT')) {
  3872. if ($this->exceptions) {
  3873. throw new Exception($this->lang('extension_missing') . 'openssl');
  3874. }
  3875. return '';
  3876. }
  3877. $privKeyStr = !empty($this->DKIM_private_string) ?
  3878. $this->DKIM_private_string :
  3879. file_get_contents($this->DKIM_private);
  3880. if ('' != $this->DKIM_passphrase) {
  3881. $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
  3882. } else {
  3883. $privKey = openssl_pkey_get_private($privKeyStr);
  3884. }
  3885. if (openssl_sign($signHeader, $signature, $privKey, 'sha256WithRSAEncryption')) {
  3886. openssl_pkey_free($privKey);
  3887. return base64_encode($signature);
  3888. }
  3889. openssl_pkey_free($privKey);
  3890. return '';
  3891. }
  3892. /**
  3893. * Generate a DKIM canonicalization header.
  3894. * Uses the 'relaxed' algorithm from RFC6376 section 3.4.2.
  3895. * Canonicalized headers should *always* use CRLF, regardless of mailer setting.
  3896. *
  3897. * @see https://tools.ietf.org/html/rfc6376#section-3.4.2
  3898. *
  3899. * @param string $signHeader Header
  3900. *
  3901. * @return string
  3902. */
  3903. public function DKIM_HeaderC($signHeader)
  3904. {
  3905. //Unfold all header continuation lines
  3906. //Also collapses folded whitespace.
  3907. //Note PCRE \s is too broad a definition of whitespace; RFC5322 defines it as `[ \t]`
  3908. //@see https://tools.ietf.org/html/rfc5322#section-2.2
  3909. //That means this may break if you do something daft like put vertical tabs in your headers.
  3910. $signHeader = preg_replace('/\r\n[ \t]+/', ' ', $signHeader);
  3911. $lines = explode("\r\n", $signHeader);
  3912. foreach ($lines as $key => $line) {
  3913. //If the header is missing a :, skip it as it's invalid
  3914. //This is likely to happen because the explode() above will also split
  3915. //on the trailing LE, leaving an empty line
  3916. if (strpos($line, ':') === false) {
  3917. continue;
  3918. }
  3919. list($heading, $value) = explode(':', $line, 2);
  3920. //Lower-case header name
  3921. $heading = strtolower($heading);
  3922. //Collapse white space within the value
  3923. $value = preg_replace('/[ \t]{2,}/', ' ', $value);
  3924. //RFC6376 is slightly unclear here - it says to delete space at the *end* of each value
  3925. //But then says to delete space before and after the colon.
  3926. //Net result is the same as trimming both ends of the value.
  3927. //by elimination, the same applies to the field name
  3928. $lines[$key] = trim($heading, " \t") . ':' . trim($value, " \t");
  3929. }
  3930. return implode("\r\n", $lines);
  3931. }
  3932. /**
  3933. * Generate a DKIM canonicalization body.
  3934. * Uses the 'simple' algorithm from RFC6376 section 3.4.3.
  3935. * Canonicalized bodies should *always* use CRLF, regardless of mailer setting.
  3936. *
  3937. * @see https://tools.ietf.org/html/rfc6376#section-3.4.3
  3938. *
  3939. * @param string $body Message Body
  3940. *
  3941. * @return string
  3942. */
  3943. public function DKIM_BodyC($body)
  3944. {
  3945. if (empty($body)) {
  3946. return "\r\n";
  3947. }
  3948. // Normalize line endings to CRLF
  3949. $body = static::normalizeBreaks($body, "\r\n");
  3950. //Reduce multiple trailing line breaks to a single one
  3951. return rtrim($body, "\r\n") . "\r\n";
  3952. }
  3953. /**
  3954. * Create the DKIM header and body in a new message header.
  3955. *
  3956. * @param string $headers_line Header lines
  3957. * @param string $subject Subject
  3958. * @param string $body Body
  3959. *
  3960. * @return string
  3961. */
  3962. public function DKIM_Add($headers_line, $subject, $body)
  3963. {
  3964. $DKIMsignatureType = 'rsa-sha256'; // Signature & hash algorithms
  3965. $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
  3966. $DKIMquery = 'dns/txt'; // Query method
  3967. $DKIMtime = time(); // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
  3968. $subject_header = "Subject: $subject";
  3969. $headers = explode(static::$LE, $headers_line);
  3970. $from_header = '';
  3971. $to_header = '';
  3972. $date_header = '';
  3973. $current = '';
  3974. $copiedHeaderFields = '';
  3975. $foundExtraHeaders = [];
  3976. $extraHeaderKeys = '';
  3977. $extraHeaderValues = '';
  3978. $extraCopyHeaderFields = '';
  3979. foreach ($headers as $header) {
  3980. if (strpos($header, 'From:') === 0) {
  3981. $from_header = $header;
  3982. $current = 'from_header';
  3983. } elseif (strpos($header, 'To:') === 0) {
  3984. $to_header = $header;
  3985. $current = 'to_header';
  3986. } elseif (strpos($header, 'Date:') === 0) {
  3987. $date_header = $header;
  3988. $current = 'date_header';
  3989. } elseif (!empty($this->DKIM_extraHeaders)) {
  3990. foreach ($this->DKIM_extraHeaders as $extraHeader) {
  3991. if (strpos($header, $extraHeader . ':') === 0) {
  3992. $headerValue = $header;
  3993. foreach ($this->CustomHeader as $customHeader) {
  3994. if ($customHeader[0] === $extraHeader) {
  3995. $headerValue = trim($customHeader[0]) .
  3996. ': ' .
  3997. $this->encodeHeader(trim($customHeader[1]));
  3998. break;
  3999. }
  4000. }
  4001. $foundExtraHeaders[$extraHeader] = $headerValue;
  4002. $current = '';
  4003. break;
  4004. }
  4005. }
  4006. } else {
  4007. if (!empty($$current) and strpos($header, ' =?') === 0) {
  4008. $$current .= $header;
  4009. } else {
  4010. $current = '';
  4011. }
  4012. }
  4013. }
  4014. foreach ($foundExtraHeaders as $key => $value) {
  4015. $extraHeaderKeys .= ':' . $key;
  4016. $extraHeaderValues .= $value . "\r\n";
  4017. if ($this->DKIM_copyHeaderFields) {
  4018. $extraCopyHeaderFields .= "\t|" . str_replace('|', '=7C', $this->DKIM_QP($value)) . ";\r\n";
  4019. }
  4020. }
  4021. if ($this->DKIM_copyHeaderFields) {
  4022. $from = str_replace('|', '=7C', $this->DKIM_QP($from_header));
  4023. $to = str_replace('|', '=7C', $this->DKIM_QP($to_header));
  4024. $date = str_replace('|', '=7C', $this->DKIM_QP($date_header));
  4025. $subject = str_replace('|', '=7C', $this->DKIM_QP($subject_header));
  4026. $copiedHeaderFields = "\tz=$from\r\n" .
  4027. "\t|$to\r\n" .
  4028. "\t|$date\r\n" .
  4029. "\t|$subject;\r\n" .
  4030. $extraCopyHeaderFields;
  4031. }
  4032. $body = $this->DKIM_BodyC($body);
  4033. $DKIMlen = strlen($body); // Length of body
  4034. $DKIMb64 = base64_encode(pack('H*', hash('sha256', $body))); // Base64 of packed binary SHA-256 hash of body
  4035. if ('' == $this->DKIM_identity) {
  4036. $ident = '';
  4037. } else {
  4038. $ident = ' i=' . $this->DKIM_identity . ';';
  4039. }
  4040. $dkimhdrs = 'DKIM-Signature: v=1; a=' .
  4041. $DKIMsignatureType . '; q=' .
  4042. $DKIMquery . '; l=' .
  4043. $DKIMlen . '; s=' .
  4044. $this->DKIM_selector .
  4045. ";\r\n" .
  4046. "\tt=" . $DKIMtime . '; c=' . $DKIMcanonicalization . ";\r\n" .
  4047. "\th=From:To:Date:Subject" . $extraHeaderKeys . ";\r\n" .
  4048. "\td=" . $this->DKIM_domain . ';' . $ident . "\r\n" .
  4049. $copiedHeaderFields .
  4050. "\tbh=" . $DKIMb64 . ";\r\n" .
  4051. "\tb=";
  4052. $toSign = $this->DKIM_HeaderC(
  4053. $from_header . "\r\n" .
  4054. $to_header . "\r\n" .
  4055. $date_header . "\r\n" .
  4056. $subject_header . "\r\n" .
  4057. $extraHeaderValues .
  4058. $dkimhdrs
  4059. );
  4060. $signed = $this->DKIM_Sign($toSign);
  4061. return static::normalizeBreaks($dkimhdrs . $signed) . static::$LE;
  4062. }
  4063. /**
  4064. * Detect if a string contains a line longer than the maximum line length
  4065. * allowed by RFC 2822 section 2.1.1.
  4066. *
  4067. * @param string $str
  4068. *
  4069. * @return bool
  4070. */
  4071. public static function hasLineLongerThanMax($str)
  4072. {
  4073. return (bool) preg_match('/^(.{' . (self::MAX_LINE_LENGTH + strlen(static::$LE)) . ',})/m', $str);
  4074. }
  4075. /**
  4076. * Allows for public read access to 'to' property.
  4077. * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
  4078. *
  4079. * @return array
  4080. */
  4081. public function getToAddresses()
  4082. {
  4083. return $this->to;
  4084. }
  4085. /**
  4086. * Allows for public read access to 'cc' property.
  4087. * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
  4088. *
  4089. * @return array
  4090. */
  4091. public function getCcAddresses()
  4092. {
  4093. return $this->cc;
  4094. }
  4095. /**
  4096. * Allows for public read access to 'bcc' property.
  4097. * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
  4098. *
  4099. * @return array
  4100. */
  4101. public function getBccAddresses()
  4102. {
  4103. return $this->bcc;
  4104. }
  4105. /**
  4106. * Allows for public read access to 'ReplyTo' property.
  4107. * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
  4108. *
  4109. * @return array
  4110. */
  4111. public function getReplyToAddresses()
  4112. {
  4113. return $this->ReplyTo;
  4114. }
  4115. /**
  4116. * Allows for public read access to 'all_recipients' property.
  4117. * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
  4118. *
  4119. * @return array
  4120. */
  4121. public function getAllRecipientAddresses()
  4122. {
  4123. return $this->all_recipients;
  4124. }
  4125. /**
  4126. * Perform a callback.
  4127. *
  4128. * @param bool $isSent
  4129. * @param array $to
  4130. * @param array $cc
  4131. * @param array $bcc
  4132. * @param string $subject
  4133. * @param string $body
  4134. * @param string $from
  4135. * @param array $extra
  4136. */
  4137. protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from, $extra)
  4138. {
  4139. if (!empty($this->action_function) and is_callable($this->action_function)) {
  4140. call_user_func($this->action_function, $isSent, $to, $cc, $bcc, $subject, $body, $from, $extra);
  4141. }
  4142. }
  4143. /**
  4144. * Get the OAuth instance.
  4145. *
  4146. * @return OAuth
  4147. */
  4148. public function getOAuth()
  4149. {
  4150. return $this->oauth;
  4151. }
  4152. /**
  4153. * Set an OAuth instance.
  4154. *
  4155. * @param OAuth $oauth
  4156. */
  4157. public function setOAuth(OAuth $oauth)
  4158. {
  4159. $this->oauth = $oauth;
  4160. }
  4161. }