class.phpmailer.php 136 KB

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