class.phpmailer.php 136 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883
  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') . $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') . $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') . $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') . $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 (!empty($this->AltBody)) {
  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 != '') {
  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 $this->MIMEHeader . $this->mailHeader . 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, change to quoted-printable transfer encoding
  1964. if (self::hasLineLongerThanMax($this->AltBody)) {
  1965. $altBodyEncoding = 'quoted-printable';
  1966. }
  1967. //Use this as a preamble in all multipart message types
  1968. $mimepre = "This is a multi-part message in MIME format." . $this->LE . $this->LE;
  1969. switch ($this->message_type) {
  1970. case 'inline':
  1971. $body .= $mimepre;
  1972. $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
  1973. $body .= $this->encodeString($this->Body, $bodyEncoding);
  1974. $body .= $this->LE . $this->LE;
  1975. $body .= $this->attachAll('inline', $this->boundary[1]);
  1976. break;
  1977. case 'attach':
  1978. $body .= $mimepre;
  1979. $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
  1980. $body .= $this->encodeString($this->Body, $bodyEncoding);
  1981. $body .= $this->LE . $this->LE;
  1982. $body .= $this->attachAll('attachment', $this->boundary[1]);
  1983. break;
  1984. case 'inline_attach':
  1985. $body .= $mimepre;
  1986. $body .= $this->textLine('--' . $this->boundary[1]);
  1987. $body .= $this->headerLine('Content-Type', 'multipart/related;');
  1988. $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  1989. $body .= $this->LE;
  1990. $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding);
  1991. $body .= $this->encodeString($this->Body, $bodyEncoding);
  1992. $body .= $this->LE . $this->LE;
  1993. $body .= $this->attachAll('inline', $this->boundary[2]);
  1994. $body .= $this->LE;
  1995. $body .= $this->attachAll('attachment', $this->boundary[1]);
  1996. break;
  1997. case 'alt':
  1998. $body .= $mimepre;
  1999. $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  2000. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  2001. $body .= $this->LE . $this->LE;
  2002. $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, 'text/html', $bodyEncoding);
  2003. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2004. $body .= $this->LE . $this->LE;
  2005. if (!empty($this->Ical)) {
  2006. $body .= $this->getBoundary($this->boundary[1], '', 'text/calendar; method=REQUEST', '');
  2007. $body .= $this->encodeString($this->Ical, $this->Encoding);
  2008. $body .= $this->LE . $this->LE;
  2009. }
  2010. $body .= $this->endBoundary($this->boundary[1]);
  2011. break;
  2012. case 'alt_inline':
  2013. $body .= $mimepre;
  2014. $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  2015. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  2016. $body .= $this->LE . $this->LE;
  2017. $body .= $this->textLine('--' . $this->boundary[1]);
  2018. $body .= $this->headerLine('Content-Type', 'multipart/related;');
  2019. $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  2020. $body .= $this->LE;
  2021. $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
  2022. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2023. $body .= $this->LE . $this->LE;
  2024. $body .= $this->attachAll('inline', $this->boundary[2]);
  2025. $body .= $this->LE;
  2026. $body .= $this->endBoundary($this->boundary[1]);
  2027. break;
  2028. case 'alt_attach':
  2029. $body .= $mimepre;
  2030. $body .= $this->textLine('--' . $this->boundary[1]);
  2031. $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
  2032. $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  2033. $body .= $this->LE;
  2034. $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  2035. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  2036. $body .= $this->LE . $this->LE;
  2037. $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
  2038. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2039. $body .= $this->LE . $this->LE;
  2040. $body .= $this->endBoundary($this->boundary[2]);
  2041. $body .= $this->LE;
  2042. $body .= $this->attachAll('attachment', $this->boundary[1]);
  2043. break;
  2044. case 'alt_inline_attach':
  2045. $body .= $mimepre;
  2046. $body .= $this->textLine('--' . $this->boundary[1]);
  2047. $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
  2048. $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  2049. $body .= $this->LE;
  2050. $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  2051. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  2052. $body .= $this->LE . $this->LE;
  2053. $body .= $this->textLine('--' . $this->boundary[2]);
  2054. $body .= $this->headerLine('Content-Type', 'multipart/related;');
  2055. $body .= $this->textLine("\tboundary=\"" . $this->boundary[3] . '"');
  2056. $body .= $this->LE;
  2057. $body .= $this->getBoundary($this->boundary[3], $bodyCharSet, 'text/html', $bodyEncoding);
  2058. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2059. $body .= $this->LE . $this->LE;
  2060. $body .= $this->attachAll('inline', $this->boundary[3]);
  2061. $body .= $this->LE;
  2062. $body .= $this->endBoundary($this->boundary[2]);
  2063. $body .= $this->LE;
  2064. $body .= $this->attachAll('attachment', $this->boundary[1]);
  2065. break;
  2066. default:
  2067. // catch case 'plain' and case ''
  2068. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2069. break;
  2070. }
  2071. if ($this->isError()) {
  2072. $body = '';
  2073. } elseif ($this->sign_key_file) {
  2074. try {
  2075. if (!defined('PKCS7_TEXT')) {
  2076. throw new phpmailerException($this->lang('extension_missing') . 'openssl');
  2077. }
  2078. // @TODO would be nice to use php://temp streams here, but need to wrap for PHP < 5.1
  2079. $file = tempnam(sys_get_temp_dir(), 'mail');
  2080. if (false === file_put_contents($file, $body)) {
  2081. throw new phpmailerException($this->lang('signing') . ' Could not write temp file');
  2082. }
  2083. $signed = tempnam(sys_get_temp_dir(), 'signed');
  2084. //Workaround for PHP bug https://bugs.php.net/bug.php?id=69197
  2085. if (empty($this->sign_extracerts_file)) {
  2086. $sign = @openssl_pkcs7_sign(
  2087. $file,
  2088. $signed,
  2089. 'file://' . realpath($this->sign_cert_file),
  2090. array('file://' . realpath($this->sign_key_file), $this->sign_key_pass),
  2091. null
  2092. );
  2093. } else {
  2094. $sign = @openssl_pkcs7_sign(
  2095. $file,
  2096. $signed,
  2097. 'file://' . realpath($this->sign_cert_file),
  2098. array('file://' . realpath($this->sign_key_file), $this->sign_key_pass),
  2099. null,
  2100. PKCS7_DETACHED,
  2101. $this->sign_extracerts_file
  2102. );
  2103. }
  2104. if ($sign) {
  2105. @unlink($file);
  2106. $body = file_get_contents($signed);
  2107. @unlink($signed);
  2108. //The message returned by openssl contains both headers and body, so need to split them up
  2109. $parts = explode("\n\n", $body, 2);
  2110. $this->MIMEHeader .= $parts[0] . $this->LE . $this->LE;
  2111. $body = $parts[1];
  2112. } else {
  2113. @unlink($file);
  2114. @unlink($signed);
  2115. throw new phpmailerException($this->lang('signing') . openssl_error_string());
  2116. }
  2117. } catch (phpmailerException $exc) {
  2118. $body = '';
  2119. if ($this->exceptions) {
  2120. throw $exc;
  2121. }
  2122. }
  2123. }
  2124. return $body;
  2125. }
  2126. /**
  2127. * Return the start of a message boundary.
  2128. * @access protected
  2129. * @param string $boundary
  2130. * @param string $charSet
  2131. * @param string $contentType
  2132. * @param string $encoding
  2133. * @return string
  2134. */
  2135. protected function getBoundary($boundary, $charSet, $contentType, $encoding)
  2136. {
  2137. $result = '';
  2138. if ($charSet == '') {
  2139. $charSet = $this->CharSet;
  2140. }
  2141. if ($contentType == '') {
  2142. $contentType = $this->ContentType;
  2143. }
  2144. if ($encoding == '') {
  2145. $encoding = $this->Encoding;
  2146. }
  2147. $result .= $this->textLine('--' . $boundary);
  2148. $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet);
  2149. $result .= $this->LE;
  2150. // RFC1341 part 5 says 7bit is assumed if not specified
  2151. if ($encoding != '7bit') {
  2152. $result .= $this->headerLine('Content-Transfer-Encoding', $encoding);
  2153. }
  2154. $result .= $this->LE;
  2155. return $result;
  2156. }
  2157. /**
  2158. * Return the end of a message boundary.
  2159. * @access protected
  2160. * @param string $boundary
  2161. * @return string
  2162. */
  2163. protected function endBoundary($boundary)
  2164. {
  2165. return $this->LE . '--' . $boundary . '--' . $this->LE;
  2166. }
  2167. /**
  2168. * Set the message type.
  2169. * PHPMailer only supports some preset message types,
  2170. * not arbitrary MIME structures.
  2171. * @access protected
  2172. * @return void
  2173. */
  2174. protected function setMessageType()
  2175. {
  2176. $type = array();
  2177. if ($this->alternativeExists()) {
  2178. $type[] = 'alt';
  2179. }
  2180. if ($this->inlineImageExists()) {
  2181. $type[] = 'inline';
  2182. }
  2183. if ($this->attachmentExists()) {
  2184. $type[] = 'attach';
  2185. }
  2186. $this->message_type = implode('_', $type);
  2187. if ($this->message_type == '') {
  2188. $this->message_type = 'plain';
  2189. }
  2190. }
  2191. /**
  2192. * Format a header line.
  2193. * @access public
  2194. * @param string $name
  2195. * @param string $value
  2196. * @return string
  2197. */
  2198. public function headerLine($name, $value)
  2199. {
  2200. return $name . ': ' . $value . $this->LE;
  2201. }
  2202. /**
  2203. * Return a formatted mail line.
  2204. * @access public
  2205. * @param string $value
  2206. * @return string
  2207. */
  2208. public function textLine($value)
  2209. {
  2210. return $value . $this->LE;
  2211. }
  2212. /**
  2213. * Add an attachment from a path on the filesystem.
  2214. * Returns false if the file could not be found or read.
  2215. * @param string $path Path to the attachment.
  2216. * @param string $name Overrides the attachment name.
  2217. * @param string $encoding File encoding (see $Encoding).
  2218. * @param string $type File extension (MIME) type.
  2219. * @param string $disposition Disposition to use
  2220. * @throws phpmailerException
  2221. * @return boolean
  2222. */
  2223. public function addAttachment($path, $name = '', $encoding = 'base64', $type = '', $disposition = 'attachment')
  2224. {
  2225. try {
  2226. if (!@is_file($path)) {
  2227. throw new phpmailerException($this->lang('file_access') . $path, self::STOP_CONTINUE);
  2228. }
  2229. // If a MIME type is not specified, try to work it out from the file name
  2230. if ($type == '') {
  2231. $type = self::filenameToType($path);
  2232. }
  2233. $filename = basename($path);
  2234. if ($name == '') {
  2235. $name = $filename;
  2236. }
  2237. $this->attachment[] = array(
  2238. 0 => $path,
  2239. 1 => $filename,
  2240. 2 => $name,
  2241. 3 => $encoding,
  2242. 4 => $type,
  2243. 5 => false, // isStringAttachment
  2244. 6 => $disposition,
  2245. 7 => 0
  2246. );
  2247. } catch (phpmailerException $exc) {
  2248. $this->setError($exc->getMessage());
  2249. $this->edebug($exc->getMessage());
  2250. if ($this->exceptions) {
  2251. throw $exc;
  2252. }
  2253. return false;
  2254. }
  2255. return true;
  2256. }
  2257. /**
  2258. * Return the array of attachments.
  2259. * @return array
  2260. */
  2261. public function getAttachments()
  2262. {
  2263. return $this->attachment;
  2264. }
  2265. /**
  2266. * Attach all file, string, and binary attachments to the message.
  2267. * Returns an empty string on failure.
  2268. * @access protected
  2269. * @param string $disposition_type
  2270. * @param string $boundary
  2271. * @return string
  2272. */
  2273. protected function attachAll($disposition_type, $boundary)
  2274. {
  2275. // Return text of body
  2276. $mime = array();
  2277. $cidUniq = array();
  2278. $incl = array();
  2279. // Add all attachments
  2280. foreach ($this->attachment as $attachment) {
  2281. // Check if it is a valid disposition_filter
  2282. if ($attachment[6] == $disposition_type) {
  2283. // Check for string attachment
  2284. $string = '';
  2285. $path = '';
  2286. $bString = $attachment[5];
  2287. if ($bString) {
  2288. $string = $attachment[0];
  2289. } else {
  2290. $path = $attachment[0];
  2291. }
  2292. $inclhash = md5(serialize($attachment));
  2293. if (in_array($inclhash, $incl)) {
  2294. continue;
  2295. }
  2296. $incl[] = $inclhash;
  2297. $name = $attachment[2];
  2298. $encoding = $attachment[3];
  2299. $type = $attachment[4];
  2300. $disposition = $attachment[6];
  2301. $cid = $attachment[7];
  2302. if ($disposition == 'inline' && array_key_exists($cid, $cidUniq)) {
  2303. continue;
  2304. }
  2305. $cidUniq[$cid] = true;
  2306. $mime[] = sprintf('--%s%s', $boundary, $this->LE);
  2307. //Only include a filename property if we have one
  2308. if (!empty($name)) {
  2309. $mime[] = sprintf(
  2310. 'Content-Type: %s; name="%s"%s',
  2311. $type,
  2312. $this->encodeHeader($this->secureHeader($name)),
  2313. $this->LE
  2314. );
  2315. } else {
  2316. $mime[] = sprintf(
  2317. 'Content-Type: %s%s',
  2318. $type,
  2319. $this->LE
  2320. );
  2321. }
  2322. // RFC1341 part 5 says 7bit is assumed if not specified
  2323. if ($encoding != '7bit') {
  2324. $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, $this->LE);
  2325. }
  2326. if ($disposition == 'inline') {
  2327. $mime[] = sprintf('Content-ID: <%s>%s', $cid, $this->LE);
  2328. }
  2329. // If a filename contains any of these chars, it should be quoted,
  2330. // but not otherwise: RFC2183 & RFC2045 5.1
  2331. // Fixes a warning in IETF's msglint MIME checker
  2332. // Allow for bypassing the Content-Disposition header totally
  2333. if (!(empty($disposition))) {
  2334. $encoded_name = $this->encodeHeader($this->secureHeader($name));
  2335. if (preg_match('/[ \(\)<>@,;:\\"\/\[\]\?=]/', $encoded_name)) {
  2336. $mime[] = sprintf(
  2337. 'Content-Disposition: %s; filename="%s"%s',
  2338. $disposition,
  2339. $encoded_name,
  2340. $this->LE . $this->LE
  2341. );
  2342. } else {
  2343. if (!empty($encoded_name)) {
  2344. $mime[] = sprintf(
  2345. 'Content-Disposition: %s; filename=%s%s',
  2346. $disposition,
  2347. $encoded_name,
  2348. $this->LE . $this->LE
  2349. );
  2350. } else {
  2351. $mime[] = sprintf(
  2352. 'Content-Disposition: %s%s',
  2353. $disposition,
  2354. $this->LE . $this->LE
  2355. );
  2356. }
  2357. }
  2358. } else {
  2359. $mime[] = $this->LE;
  2360. }
  2361. // Encode as string attachment
  2362. if ($bString) {
  2363. $mime[] = $this->encodeString($string, $encoding);
  2364. if ($this->isError()) {
  2365. return '';
  2366. }
  2367. $mime[] = $this->LE . $this->LE;
  2368. } else {
  2369. $mime[] = $this->encodeFile($path, $encoding);
  2370. if ($this->isError()) {
  2371. return '';
  2372. }
  2373. $mime[] = $this->LE . $this->LE;
  2374. }
  2375. }
  2376. }
  2377. $mime[] = sprintf('--%s--%s', $boundary, $this->LE);
  2378. return implode('', $mime);
  2379. }
  2380. /**
  2381. * Encode a file attachment in requested format.
  2382. * Returns an empty string on failure.
  2383. * @param string $path The full path to the file
  2384. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  2385. * @throws phpmailerException
  2386. * @access protected
  2387. * @return string
  2388. */
  2389. protected function encodeFile($path, $encoding = 'base64')
  2390. {
  2391. try {
  2392. if (!is_readable($path)) {
  2393. throw new phpmailerException($this->lang('file_open') . $path, self::STOP_CONTINUE);
  2394. }
  2395. $magic_quotes = get_magic_quotes_runtime();
  2396. if ($magic_quotes) {
  2397. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  2398. set_magic_quotes_runtime(false);
  2399. } else {
  2400. //Doesn't exist in PHP 5.4, but we don't need to check because
  2401. //get_magic_quotes_runtime always returns false in 5.4+
  2402. //so it will never get here
  2403. ini_set('magic_quotes_runtime', false);
  2404. }
  2405. }
  2406. $file_buffer = file_get_contents($path);
  2407. $file_buffer = $this->encodeString($file_buffer, $encoding);
  2408. if ($magic_quotes) {
  2409. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  2410. set_magic_quotes_runtime($magic_quotes);
  2411. } else {
  2412. ini_set('magic_quotes_runtime', $magic_quotes);
  2413. }
  2414. }
  2415. return $file_buffer;
  2416. } catch (Exception $exc) {
  2417. $this->setError($exc->getMessage());
  2418. return '';
  2419. }
  2420. }
  2421. /**
  2422. * Encode a string in requested format.
  2423. * Returns an empty string on failure.
  2424. * @param string $str The text to encode
  2425. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  2426. * @access public
  2427. * @return string
  2428. */
  2429. public function encodeString($str, $encoding = 'base64')
  2430. {
  2431. $encoded = '';
  2432. switch (strtolower($encoding)) {
  2433. case 'base64':
  2434. $encoded = chunk_split(base64_encode($str), 76, $this->LE);
  2435. break;
  2436. case '7bit':
  2437. case '8bit':
  2438. $encoded = $this->fixEOL($str);
  2439. // Make sure it ends with a line break
  2440. if (substr($encoded, -(strlen($this->LE))) != $this->LE) {
  2441. $encoded .= $this->LE;
  2442. }
  2443. break;
  2444. case 'binary':
  2445. $encoded = $str;
  2446. break;
  2447. case 'quoted-printable':
  2448. $encoded = $this->encodeQP($str);
  2449. break;
  2450. default:
  2451. $this->setError($this->lang('encoding') . $encoding);
  2452. break;
  2453. }
  2454. return $encoded;
  2455. }
  2456. /**
  2457. * Encode a header string optimally.
  2458. * Picks shortest of Q, B, quoted-printable or none.
  2459. * @access public
  2460. * @param string $str
  2461. * @param string $position
  2462. * @return string
  2463. */
  2464. public function encodeHeader($str, $position = 'text')
  2465. {
  2466. $matchcount = 0;
  2467. switch (strtolower($position)) {
  2468. case 'phrase':
  2469. if (!preg_match('/[\200-\377]/', $str)) {
  2470. // Can't use addslashes as we don't know the value of magic_quotes_sybase
  2471. $encoded = addcslashes($str, "\0..\37\177\\\"");
  2472. if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
  2473. return ($encoded);
  2474. } else {
  2475. return ("\"$encoded\"");
  2476. }
  2477. }
  2478. $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
  2479. break;
  2480. /** @noinspection PhpMissingBreakStatementInspection */
  2481. case 'comment':
  2482. $matchcount = preg_match_all('/[()"]/', $str, $matches);
  2483. // Intentional fall-through
  2484. case 'text':
  2485. default:
  2486. $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
  2487. break;
  2488. }
  2489. //There are no chars that need encoding
  2490. if ($matchcount == 0) {
  2491. return ($str);
  2492. }
  2493. $maxlen = 75 - 7 - strlen($this->CharSet);
  2494. // Try to select the encoding which should produce the shortest output
  2495. if ($matchcount > strlen($str) / 3) {
  2496. // More than a third of the content will need encoding, so B encoding will be most efficient
  2497. $encoding = 'B';
  2498. if (function_exists('mb_strlen') && $this->hasMultiBytes($str)) {
  2499. // Use a custom function which correctly encodes and wraps long
  2500. // multibyte strings without breaking lines within a character
  2501. $encoded = $this->base64EncodeWrapMB($str, "\n");
  2502. } else {
  2503. $encoded = base64_encode($str);
  2504. $maxlen -= $maxlen % 4;
  2505. $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
  2506. }
  2507. } else {
  2508. $encoding = 'Q';
  2509. $encoded = $this->encodeQ($str, $position);
  2510. $encoded = $this->wrapText($encoded, $maxlen, true);
  2511. $encoded = str_replace('=' . self::CRLF, "\n", trim($encoded));
  2512. }
  2513. $encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet . "?$encoding?\\1?=", $encoded);
  2514. $encoded = trim(str_replace("\n", $this->LE, $encoded));
  2515. return $encoded;
  2516. }
  2517. /**
  2518. * Check if a string contains multi-byte characters.
  2519. * @access public
  2520. * @param string $str multi-byte text to wrap encode
  2521. * @return boolean
  2522. */
  2523. public function hasMultiBytes($str)
  2524. {
  2525. if (function_exists('mb_strlen')) {
  2526. return (strlen($str) > mb_strlen($str, $this->CharSet));
  2527. } else { // Assume no multibytes (we can't handle without mbstring functions anyway)
  2528. return false;
  2529. }
  2530. }
  2531. /**
  2532. * Does a string contain any 8-bit chars (in any charset)?
  2533. * @param string $text
  2534. * @return boolean
  2535. */
  2536. public function has8bitChars($text)
  2537. {
  2538. return (boolean)preg_match('/[\x80-\xFF]/', $text);
  2539. }
  2540. /**
  2541. * Encode and wrap long multibyte strings for mail headers
  2542. * without breaking lines within a character.
  2543. * Adapted from a function by paravoid
  2544. * @link http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283
  2545. * @access public
  2546. * @param string $str multi-byte text to wrap encode
  2547. * @param string $linebreak string to use as linefeed/end-of-line
  2548. * @return string
  2549. */
  2550. public function base64EncodeWrapMB($str, $linebreak = null)
  2551. {
  2552. $start = '=?' . $this->CharSet . '?B?';
  2553. $end = '?=';
  2554. $encoded = '';
  2555. if ($linebreak === null) {
  2556. $linebreak = $this->LE;
  2557. }
  2558. $mb_length = mb_strlen($str, $this->CharSet);
  2559. // Each line must have length <= 75, including $start and $end
  2560. $length = 75 - strlen($start) - strlen($end);
  2561. // Average multi-byte ratio
  2562. $ratio = $mb_length / strlen($str);
  2563. // Base64 has a 4:3 ratio
  2564. $avgLength = floor($length * $ratio * .75);
  2565. for ($i = 0; $i < $mb_length; $i += $offset) {
  2566. $lookBack = 0;
  2567. do {
  2568. $offset = $avgLength - $lookBack;
  2569. $chunk = mb_substr($str, $i, $offset, $this->CharSet);
  2570. $chunk = base64_encode($chunk);
  2571. $lookBack++;
  2572. } while (strlen($chunk) > $length);
  2573. $encoded .= $chunk . $linebreak;
  2574. }
  2575. // Chomp the last linefeed
  2576. $encoded = substr($encoded, 0, -strlen($linebreak));
  2577. return $encoded;
  2578. }
  2579. /**
  2580. * Encode a string in quoted-printable format.
  2581. * According to RFC2045 section 6.7.
  2582. * @access public
  2583. * @param string $string The text to encode
  2584. * @param integer $line_max Number of chars allowed on a line before wrapping
  2585. * @return string
  2586. * @link http://www.php.net/manual/en/function.quoted-printable-decode.php#89417 Adapted from this comment
  2587. */
  2588. public function encodeQP($string, $line_max = 76)
  2589. {
  2590. // Use native function if it's available (>= PHP5.3)
  2591. if (function_exists('quoted_printable_encode')) {
  2592. return quoted_printable_encode($string);
  2593. }
  2594. // Fall back to a pure PHP implementation
  2595. $string = str_replace(
  2596. array('%20', '%0D%0A.', '%0D%0A', '%'),
  2597. array(' ', "\r\n=2E", "\r\n", '='),
  2598. rawurlencode($string)
  2599. );
  2600. return preg_replace('/[^\r\n]{' . ($line_max - 3) . '}[^=\r\n]{2}/', "$0=\r\n", $string);
  2601. }
  2602. /**
  2603. * Backward compatibility wrapper for an old QP encoding function that was removed.
  2604. * @see PHPMailer::encodeQP()
  2605. * @access public
  2606. * @param string $string
  2607. * @param integer $line_max
  2608. * @param boolean $space_conv
  2609. * @return string
  2610. * @deprecated Use encodeQP instead.
  2611. */
  2612. public function encodeQPphp(
  2613. $string,
  2614. $line_max = 76,
  2615. /** @noinspection PhpUnusedParameterInspection */ $space_conv = false
  2616. ) {
  2617. return $this->encodeQP($string, $line_max);
  2618. }
  2619. /**
  2620. * Encode a string using Q encoding.
  2621. * @link http://tools.ietf.org/html/rfc2047
  2622. * @param string $str the text to encode
  2623. * @param string $position Where the text is going to be used, see the RFC for what that means
  2624. * @access public
  2625. * @return string
  2626. */
  2627. public function encodeQ($str, $position = 'text')
  2628. {
  2629. // There should not be any EOL in the string
  2630. $pattern = '';
  2631. $encoded = str_replace(array("\r", "\n"), '', $str);
  2632. switch (strtolower($position)) {
  2633. case 'phrase':
  2634. // RFC 2047 section 5.3
  2635. $pattern = '^A-Za-z0-9!*+\/ -';
  2636. break;
  2637. /** @noinspection PhpMissingBreakStatementInspection */
  2638. case 'comment':
  2639. // RFC 2047 section 5.2
  2640. $pattern = '\(\)"';
  2641. // intentional fall-through
  2642. // for this reason we build the $pattern without including delimiters and []
  2643. case 'text':
  2644. default:
  2645. // RFC 2047 section 5.1
  2646. // Replace every high ascii, control, =, ? and _ characters
  2647. $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern;
  2648. break;
  2649. }
  2650. $matches = array();
  2651. if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
  2652. // If the string contains an '=', make sure it's the first thing we replace
  2653. // so as to avoid double-encoding
  2654. $eqkey = array_search('=', $matches[0]);
  2655. if (false !== $eqkey) {
  2656. unset($matches[0][$eqkey]);
  2657. array_unshift($matches[0], '=');
  2658. }
  2659. foreach (array_unique($matches[0]) as $char) {
  2660. $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
  2661. }
  2662. }
  2663. // Replace every spaces to _ (more readable than =20)
  2664. return str_replace(' ', '_', $encoded);
  2665. }
  2666. /**
  2667. * Add a string or binary attachment (non-filesystem).
  2668. * This method can be used to attach ascii or binary data,
  2669. * such as a BLOB record from a database.
  2670. * @param string $string String attachment data.
  2671. * @param string $filename Name of the attachment.
  2672. * @param string $encoding File encoding (see $Encoding).
  2673. * @param string $type File extension (MIME) type.
  2674. * @param string $disposition Disposition to use
  2675. * @return void
  2676. */
  2677. public function addStringAttachment(
  2678. $string,
  2679. $filename,
  2680. $encoding = 'base64',
  2681. $type = '',
  2682. $disposition = 'attachment'
  2683. ) {
  2684. // If a MIME type is not specified, try to work it out from the file name
  2685. if ($type == '') {
  2686. $type = self::filenameToType($filename);
  2687. }
  2688. // Append to $attachment array
  2689. $this->attachment[] = array(
  2690. 0 => $string,
  2691. 1 => $filename,
  2692. 2 => basename($filename),
  2693. 3 => $encoding,
  2694. 4 => $type,
  2695. 5 => true, // isStringAttachment
  2696. 6 => $disposition,
  2697. 7 => 0
  2698. );
  2699. }
  2700. /**
  2701. * Add an embedded (inline) attachment from a file.
  2702. * This can include images, sounds, and just about any other document type.
  2703. * These differ from 'regular' attachments in that they are intended to be
  2704. * displayed inline with the message, not just attached for download.
  2705. * This is used in HTML messages that embed the images
  2706. * the HTML refers to using the $cid value.
  2707. * @param string $path Path to the attachment.
  2708. * @param string $cid Content ID of the attachment; Use this to reference
  2709. * the content when using an embedded image in HTML.
  2710. * @param string $name Overrides the attachment name.
  2711. * @param string $encoding File encoding (see $Encoding).
  2712. * @param string $type File MIME type.
  2713. * @param string $disposition Disposition to use
  2714. * @return boolean True on successfully adding an attachment
  2715. */
  2716. public function addEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline')
  2717. {
  2718. if (!@is_file($path)) {
  2719. $this->setError($this->lang('file_access') . $path);
  2720. return false;
  2721. }
  2722. // If a MIME type is not specified, try to work it out from the file name
  2723. if ($type == '') {
  2724. $type = self::filenameToType($path);
  2725. }
  2726. $filename = basename($path);
  2727. if ($name == '') {
  2728. $name = $filename;
  2729. }
  2730. // Append to $attachment array
  2731. $this->attachment[] = array(
  2732. 0 => $path,
  2733. 1 => $filename,
  2734. 2 => $name,
  2735. 3 => $encoding,
  2736. 4 => $type,
  2737. 5 => false, // isStringAttachment
  2738. 6 => $disposition,
  2739. 7 => $cid
  2740. );
  2741. return true;
  2742. }
  2743. /**
  2744. * Add an embedded stringified attachment.
  2745. * This can include images, sounds, and just about any other document type.
  2746. * Be sure to set the $type to an image type for images:
  2747. * JPEG images use 'image/jpeg', GIF uses 'image/gif', PNG uses 'image/png'.
  2748. * @param string $string The attachment binary data.
  2749. * @param string $cid Content ID of the attachment; Use this to reference
  2750. * the content when using an embedded image in HTML.
  2751. * @param string $name
  2752. * @param string $encoding File encoding (see $Encoding).
  2753. * @param string $type MIME type.
  2754. * @param string $disposition Disposition to use
  2755. * @return boolean True on successfully adding an attachment
  2756. */
  2757. public function addStringEmbeddedImage(
  2758. $string,
  2759. $cid,
  2760. $name = '',
  2761. $encoding = 'base64',
  2762. $type = '',
  2763. $disposition = 'inline'
  2764. ) {
  2765. // If a MIME type is not specified, try to work it out from the name
  2766. if ($type == '' and !empty($name)) {
  2767. $type = self::filenameToType($name);
  2768. }
  2769. // Append to $attachment array
  2770. $this->attachment[] = array(
  2771. 0 => $string,
  2772. 1 => $name,
  2773. 2 => $name,
  2774. 3 => $encoding,
  2775. 4 => $type,
  2776. 5 => true, // isStringAttachment
  2777. 6 => $disposition,
  2778. 7 => $cid
  2779. );
  2780. return true;
  2781. }
  2782. /**
  2783. * Check if an inline attachment is present.
  2784. * @access public
  2785. * @return boolean
  2786. */
  2787. public function inlineImageExists()
  2788. {
  2789. foreach ($this->attachment as $attachment) {
  2790. if ($attachment[6] == 'inline') {
  2791. return true;
  2792. }
  2793. }
  2794. return false;
  2795. }
  2796. /**
  2797. * Check if an attachment (non-inline) is present.
  2798. * @return boolean
  2799. */
  2800. public function attachmentExists()
  2801. {
  2802. foreach ($this->attachment as $attachment) {
  2803. if ($attachment[6] == 'attachment') {
  2804. return true;
  2805. }
  2806. }
  2807. return false;
  2808. }
  2809. /**
  2810. * Check if this message has an alternative body set.
  2811. * @return boolean
  2812. */
  2813. public function alternativeExists()
  2814. {
  2815. return !empty($this->AltBody);
  2816. }
  2817. /**
  2818. * Clear queued addresses of given kind.
  2819. * @access protected
  2820. * @param string $kind 'to', 'cc', or 'bcc'
  2821. * @return void
  2822. */
  2823. public function clearQueuedAddresses($kind)
  2824. {
  2825. $RecipientsQueue = $this->RecipientsQueue;
  2826. foreach ($RecipientsQueue as $address => $params) {
  2827. if ($params[0] == $kind) {
  2828. unset($this->RecipientsQueue[$address]);
  2829. }
  2830. }
  2831. }
  2832. /**
  2833. * Clear all To recipients.
  2834. * @return void
  2835. */
  2836. public function clearAddresses()
  2837. {
  2838. foreach ($this->to as $to) {
  2839. unset($this->all_recipients[strtolower($to[0])]);
  2840. }
  2841. $this->to = array();
  2842. $this->clearQueuedAddresses('to');
  2843. }
  2844. /**
  2845. * Clear all CC recipients.
  2846. * @return void
  2847. */
  2848. public function clearCCs()
  2849. {
  2850. foreach ($this->cc as $cc) {
  2851. unset($this->all_recipients[strtolower($cc[0])]);
  2852. }
  2853. $this->cc = array();
  2854. $this->clearQueuedAddresses('cc');
  2855. }
  2856. /**
  2857. * Clear all BCC recipients.
  2858. * @return void
  2859. */
  2860. public function clearBCCs()
  2861. {
  2862. foreach ($this->bcc as $bcc) {
  2863. unset($this->all_recipients[strtolower($bcc[0])]);
  2864. }
  2865. $this->bcc = array();
  2866. $this->clearQueuedAddresses('bcc');
  2867. }
  2868. /**
  2869. * Clear all ReplyTo recipients.
  2870. * @return void
  2871. */
  2872. public function clearReplyTos()
  2873. {
  2874. $this->ReplyTo = array();
  2875. $this->ReplyToQueue = array();
  2876. }
  2877. /**
  2878. * Clear all recipient types.
  2879. * @return void
  2880. */
  2881. public function clearAllRecipients()
  2882. {
  2883. $this->to = array();
  2884. $this->cc = array();
  2885. $this->bcc = array();
  2886. $this->all_recipients = array();
  2887. $this->RecipientsQueue = array();
  2888. }
  2889. /**
  2890. * Clear all filesystem, string, and binary attachments.
  2891. * @return void
  2892. */
  2893. public function clearAttachments()
  2894. {
  2895. $this->attachment = array();
  2896. }
  2897. /**
  2898. * Clear all custom headers.
  2899. * @return void
  2900. */
  2901. public function clearCustomHeaders()
  2902. {
  2903. $this->CustomHeader = array();
  2904. }
  2905. /**
  2906. * Add an error message to the error container.
  2907. * @access protected
  2908. * @param string $msg
  2909. * @return void
  2910. */
  2911. protected function setError($msg)
  2912. {
  2913. $this->error_count++;
  2914. if ($this->Mailer == 'smtp' and !is_null($this->smtp)) {
  2915. $lasterror = $this->smtp->getError();
  2916. if (!empty($lasterror['error'])) {
  2917. $msg .= $this->lang('smtp_error') . $lasterror['error'];
  2918. if (!empty($lasterror['detail'])) {
  2919. $msg .= ' Detail: '. $lasterror['detail'];
  2920. }
  2921. if (!empty($lasterror['smtp_code'])) {
  2922. $msg .= ' SMTP code: ' . $lasterror['smtp_code'];
  2923. }
  2924. if (!empty($lasterror['smtp_code_ex'])) {
  2925. $msg .= ' Additional SMTP info: ' . $lasterror['smtp_code_ex'];
  2926. }
  2927. }
  2928. }
  2929. $this->ErrorInfo = $msg;
  2930. }
  2931. /**
  2932. * Return an RFC 822 formatted date.
  2933. * @access public
  2934. * @return string
  2935. * @static
  2936. */
  2937. public static function rfcDate()
  2938. {
  2939. // Set the time zone to whatever the default is to avoid 500 errors
  2940. // Will default to UTC if it's not set properly in php.ini
  2941. date_default_timezone_set(@date_default_timezone_get());
  2942. return date('D, j M Y H:i:s O');
  2943. }
  2944. /**
  2945. * Get the server hostname.
  2946. * Returns 'localhost.localdomain' if unknown.
  2947. * @access protected
  2948. * @return string
  2949. */
  2950. protected function serverHostname()
  2951. {
  2952. $result = 'localhost.localdomain';
  2953. if (!empty($this->Hostname)) {
  2954. $result = $this->Hostname;
  2955. } elseif (isset($_SERVER) and array_key_exists('SERVER_NAME', $_SERVER) and !empty($_SERVER['SERVER_NAME'])) {
  2956. $result = $_SERVER['SERVER_NAME'];
  2957. } elseif (function_exists('gethostname') && gethostname() !== false) {
  2958. $result = gethostname();
  2959. } elseif (php_uname('n') !== false) {
  2960. $result = php_uname('n');
  2961. }
  2962. return $result;
  2963. }
  2964. /**
  2965. * Get an error message in the current language.
  2966. * @access protected
  2967. * @param string $key
  2968. * @return string
  2969. */
  2970. protected function lang($key)
  2971. {
  2972. if (count($this->language) < 1) {
  2973. $this->setLanguage('en'); // set the default language
  2974. }
  2975. if (array_key_exists($key, $this->language)) {
  2976. if ($key == 'smtp_connect_failed') {
  2977. //Include a link to troubleshooting docs on SMTP connection failure
  2978. //this is by far the biggest cause of support questions
  2979. //but it's usually not PHPMailer's fault.
  2980. return $this->language[$key] . ' https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting';
  2981. }
  2982. return $this->language[$key];
  2983. } else {
  2984. //Return the key as a fallback
  2985. return $key;
  2986. }
  2987. }
  2988. /**
  2989. * Check if an error occurred.
  2990. * @access public
  2991. * @return boolean True if an error did occur.
  2992. */
  2993. public function isError()
  2994. {
  2995. return ($this->error_count > 0);
  2996. }
  2997. /**
  2998. * Ensure consistent line endings in a string.
  2999. * Changes every end of line from CRLF, CR or LF to $this->LE.
  3000. * @access public
  3001. * @param string $str String to fixEOL
  3002. * @return string
  3003. */
  3004. public function fixEOL($str)
  3005. {
  3006. // Normalise to \n
  3007. $nstr = str_replace(array("\r\n", "\r"), "\n", $str);
  3008. // Now convert LE as needed
  3009. if ($this->LE !== "\n") {
  3010. $nstr = str_replace("\n", $this->LE, $nstr);
  3011. }
  3012. return $nstr;
  3013. }
  3014. /**
  3015. * Add a custom header.
  3016. * $name value can be overloaded to contain
  3017. * both header name and value (name:value)
  3018. * @access public
  3019. * @param string $name Custom header name
  3020. * @param string $value Header value
  3021. * @return void
  3022. */
  3023. public function addCustomHeader($name, $value = null)
  3024. {
  3025. if ($value === null) {
  3026. // Value passed in as name:value
  3027. $this->CustomHeader[] = explode(':', $name, 2);
  3028. } else {
  3029. $this->CustomHeader[] = array($name, $value);
  3030. }
  3031. }
  3032. /**
  3033. * Returns all custom headers.
  3034. * @return array
  3035. */
  3036. public function getCustomHeaders()
  3037. {
  3038. return $this->CustomHeader;
  3039. }
  3040. /**
  3041. * Create a message from an HTML string.
  3042. * Automatically makes modifications for inline images and backgrounds
  3043. * and creates a plain-text version by converting the HTML.
  3044. * Overwrites any existing values in $this->Body and $this->AltBody
  3045. * @access public
  3046. * @param string $message HTML message string
  3047. * @param string $basedir baseline directory for path
  3048. * @param boolean|callable $advanced Whether to use the internal HTML to text converter
  3049. * or your own custom converter @see PHPMailer::html2text()
  3050. * @return string $message
  3051. */
  3052. public function msgHTML($message, $basedir = '', $advanced = false)
  3053. {
  3054. preg_match_all('/(src|background)=["\'](.*)["\']/Ui', $message, $images);
  3055. if (array_key_exists(2, $images)) {
  3056. foreach ($images[2] as $imgindex => $url) {
  3057. // Convert data URIs into embedded images
  3058. if (preg_match('#^data:(image[^;,]*)(;base64)?,#', $url, $match)) {
  3059. $data = substr($url, strpos($url, ','));
  3060. if ($match[2]) {
  3061. $data = base64_decode($data);
  3062. } else {
  3063. $data = rawurldecode($data);
  3064. }
  3065. $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2
  3066. if ($this->addStringEmbeddedImage($data, $cid, 'embed' . $imgindex, 'base64', $match[1])) {
  3067. $message = str_replace(
  3068. $images[0][$imgindex],
  3069. $images[1][$imgindex] . '="cid:' . $cid . '"',
  3070. $message
  3071. );
  3072. }
  3073. } elseif (substr($url, 0, 4) !== 'cid:' && !preg_match('#^[A-z]+://#', $url)) {
  3074. // Do not change urls for absolute images (thanks to corvuscorax)
  3075. // Do not change urls that are already inline images
  3076. $filename = basename($url);
  3077. $directory = dirname($url);
  3078. if ($directory == '.') {
  3079. $directory = '';
  3080. }
  3081. $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2
  3082. if (strlen($basedir) > 1 && substr($basedir, -1) != '/') {
  3083. $basedir .= '/';
  3084. }
  3085. if (strlen($directory) > 1 && substr($directory, -1) != '/') {
  3086. $directory .= '/';
  3087. }
  3088. if ($this->addEmbeddedImage(
  3089. $basedir . $directory . $filename,
  3090. $cid,
  3091. $filename,
  3092. 'base64',
  3093. self::_mime_types((string)self::mb_pathinfo($filename, PATHINFO_EXTENSION))
  3094. )
  3095. ) {
  3096. $message = preg_replace(
  3097. '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui',
  3098. $images[1][$imgindex] . '="cid:' . $cid . '"',
  3099. $message
  3100. );
  3101. }
  3102. }
  3103. }
  3104. }
  3105. $this->isHTML(true);
  3106. // Convert all message body line breaks to CRLF, makes quoted-printable encoding work much better
  3107. $this->Body = $this->normalizeBreaks($message);
  3108. $this->AltBody = $this->normalizeBreaks($this->html2text($message, $advanced));
  3109. if (empty($this->AltBody)) {
  3110. $this->AltBody = 'To view this email message, open it in a program that understands HTML!' .
  3111. self::CRLF . self::CRLF;
  3112. }
  3113. return $this->Body;
  3114. }
  3115. /**
  3116. * Convert an HTML string into plain text.
  3117. * This is used by msgHTML().
  3118. * Note - older versions of this function used a bundled advanced converter
  3119. * which was been removed for license reasons in #232
  3120. * Example usage:
  3121. * <code>
  3122. * // Use default conversion
  3123. * $plain = $mail->html2text($html);
  3124. * // Use your own custom converter
  3125. * $plain = $mail->html2text($html, function($html) {
  3126. * $converter = new MyHtml2text($html);
  3127. * return $converter->get_text();
  3128. * });
  3129. * </code>
  3130. * @param string $html The HTML text to convert
  3131. * @param boolean|callable $advanced Any boolean value to use the internal converter,
  3132. * or provide your own callable for custom conversion.
  3133. * @return string
  3134. */
  3135. public function html2text($html, $advanced = false)
  3136. {
  3137. if (is_callable($advanced)) {
  3138. return call_user_func($advanced, $html);
  3139. }
  3140. return html_entity_decode(
  3141. trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))),
  3142. ENT_QUOTES,
  3143. $this->CharSet
  3144. );
  3145. }
  3146. /**
  3147. * Get the MIME type for a file extension.
  3148. * @param string $ext File extension
  3149. * @access public
  3150. * @return string MIME type of file.
  3151. * @static
  3152. */
  3153. public static function _mime_types($ext = '')
  3154. {
  3155. $mimes = array(
  3156. 'xl' => 'application/excel',
  3157. 'js' => 'application/javascript',
  3158. 'hqx' => 'application/mac-binhex40',
  3159. 'cpt' => 'application/mac-compactpro',
  3160. 'bin' => 'application/macbinary',
  3161. 'doc' => 'application/msword',
  3162. 'word' => 'application/msword',
  3163. 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  3164. 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
  3165. 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
  3166. 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
  3167. 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  3168. 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
  3169. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  3170. 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
  3171. 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
  3172. 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
  3173. 'class' => 'application/octet-stream',
  3174. 'dll' => 'application/octet-stream',
  3175. 'dms' => 'application/octet-stream',
  3176. 'exe' => 'application/octet-stream',
  3177. 'lha' => 'application/octet-stream',
  3178. 'lzh' => 'application/octet-stream',
  3179. 'psd' => 'application/octet-stream',
  3180. 'sea' => 'application/octet-stream',
  3181. 'so' => 'application/octet-stream',
  3182. 'oda' => 'application/oda',
  3183. 'pdf' => 'application/pdf',
  3184. 'ai' => 'application/postscript',
  3185. 'eps' => 'application/postscript',
  3186. 'ps' => 'application/postscript',
  3187. 'smi' => 'application/smil',
  3188. 'smil' => 'application/smil',
  3189. 'mif' => 'application/vnd.mif',
  3190. 'xls' => 'application/vnd.ms-excel',
  3191. 'ppt' => 'application/vnd.ms-powerpoint',
  3192. 'wbxml' => 'application/vnd.wap.wbxml',
  3193. 'wmlc' => 'application/vnd.wap.wmlc',
  3194. 'dcr' => 'application/x-director',
  3195. 'dir' => 'application/x-director',
  3196. 'dxr' => 'application/x-director',
  3197. 'dvi' => 'application/x-dvi',
  3198. 'gtar' => 'application/x-gtar',
  3199. 'php3' => 'application/x-httpd-php',
  3200. 'php4' => 'application/x-httpd-php',
  3201. 'php' => 'application/x-httpd-php',
  3202. 'phtml' => 'application/x-httpd-php',
  3203. 'phps' => 'application/x-httpd-php-source',
  3204. 'swf' => 'application/x-shockwave-flash',
  3205. 'sit' => 'application/x-stuffit',
  3206. 'tar' => 'application/x-tar',
  3207. 'tgz' => 'application/x-tar',
  3208. 'xht' => 'application/xhtml+xml',
  3209. 'xhtml' => 'application/xhtml+xml',
  3210. 'zip' => 'application/zip',
  3211. 'mid' => 'audio/midi',
  3212. 'midi' => 'audio/midi',
  3213. 'mp2' => 'audio/mpeg',
  3214. 'mp3' => 'audio/mpeg',
  3215. 'mpga' => 'audio/mpeg',
  3216. 'aif' => 'audio/x-aiff',
  3217. 'aifc' => 'audio/x-aiff',
  3218. 'aiff' => 'audio/x-aiff',
  3219. 'ram' => 'audio/x-pn-realaudio',
  3220. 'rm' => 'audio/x-pn-realaudio',
  3221. 'rpm' => 'audio/x-pn-realaudio-plugin',
  3222. 'ra' => 'audio/x-realaudio',
  3223. 'wav' => 'audio/x-wav',
  3224. 'bmp' => 'image/bmp',
  3225. 'gif' => 'image/gif',
  3226. 'jpeg' => 'image/jpeg',
  3227. 'jpe' => 'image/jpeg',
  3228. 'jpg' => 'image/jpeg',
  3229. 'png' => 'image/png',
  3230. 'tiff' => 'image/tiff',
  3231. 'tif' => 'image/tiff',
  3232. 'eml' => 'message/rfc822',
  3233. 'css' => 'text/css',
  3234. 'html' => 'text/html',
  3235. 'htm' => 'text/html',
  3236. 'shtml' => 'text/html',
  3237. 'log' => 'text/plain',
  3238. 'text' => 'text/plain',
  3239. 'txt' => 'text/plain',
  3240. 'rtx' => 'text/richtext',
  3241. 'rtf' => 'text/rtf',
  3242. 'vcf' => 'text/vcard',
  3243. 'vcard' => 'text/vcard',
  3244. 'xml' => 'text/xml',
  3245. 'xsl' => 'text/xml',
  3246. 'mpeg' => 'video/mpeg',
  3247. 'mpe' => 'video/mpeg',
  3248. 'mpg' => 'video/mpeg',
  3249. 'mov' => 'video/quicktime',
  3250. 'qt' => 'video/quicktime',
  3251. 'rv' => 'video/vnd.rn-realvideo',
  3252. 'avi' => 'video/x-msvideo',
  3253. 'movie' => 'video/x-sgi-movie'
  3254. );
  3255. if (array_key_exists(strtolower($ext), $mimes)) {
  3256. return $mimes[strtolower($ext)];
  3257. }
  3258. return 'application/octet-stream';
  3259. }
  3260. /**
  3261. * Map a file name to a MIME type.
  3262. * Defaults to 'application/octet-stream', i.e.. arbitrary binary data.
  3263. * @param string $filename A file name or full path, does not need to exist as a file
  3264. * @return string
  3265. * @static
  3266. */
  3267. public static function filenameToType($filename)
  3268. {
  3269. // In case the path is a URL, strip any query string before getting extension
  3270. $qpos = strpos($filename, '?');
  3271. if (false !== $qpos) {
  3272. $filename = substr($filename, 0, $qpos);
  3273. }
  3274. $pathinfo = self::mb_pathinfo($filename);
  3275. return self::_mime_types($pathinfo['extension']);
  3276. }
  3277. /**
  3278. * Multi-byte-safe pathinfo replacement.
  3279. * Drop-in replacement for pathinfo(), but multibyte-safe, cross-platform-safe, old-version-safe.
  3280. * Works similarly to the one in PHP >= 5.2.0
  3281. * @link http://www.php.net/manual/en/function.pathinfo.php#107461
  3282. * @param string $path A filename or path, does not need to exist as a file
  3283. * @param integer|string $options Either a PATHINFO_* constant,
  3284. * or a string name to return only the specified piece, allows 'filename' to work on PHP < 5.2
  3285. * @return string|array
  3286. * @static
  3287. */
  3288. public static function mb_pathinfo($path, $options = null)
  3289. {
  3290. $ret = array('dirname' => '', 'basename' => '', 'extension' => '', 'filename' => '');
  3291. $pathinfo = array();
  3292. if (preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', $path, $pathinfo)) {
  3293. if (array_key_exists(1, $pathinfo)) {
  3294. $ret['dirname'] = $pathinfo[1];
  3295. }
  3296. if (array_key_exists(2, $pathinfo)) {
  3297. $ret['basename'] = $pathinfo[2];
  3298. }
  3299. if (array_key_exists(5, $pathinfo)) {
  3300. $ret['extension'] = $pathinfo[5];
  3301. }
  3302. if (array_key_exists(3, $pathinfo)) {
  3303. $ret['filename'] = $pathinfo[3];
  3304. }
  3305. }
  3306. switch ($options) {
  3307. case PATHINFO_DIRNAME:
  3308. case 'dirname':
  3309. return $ret['dirname'];
  3310. case PATHINFO_BASENAME:
  3311. case 'basename':
  3312. return $ret['basename'];
  3313. case PATHINFO_EXTENSION:
  3314. case 'extension':
  3315. return $ret['extension'];
  3316. case PATHINFO_FILENAME:
  3317. case 'filename':
  3318. return $ret['filename'];
  3319. default:
  3320. return $ret;
  3321. }
  3322. }
  3323. /**
  3324. * Set or reset instance properties.
  3325. * You should avoid this function - it's more verbose, less efficient, more error-prone and
  3326. * harder to debug than setting properties directly.
  3327. * Usage Example:
  3328. * `$mail->set('SMTPSecure', 'tls');`
  3329. * is the same as:
  3330. * `$mail->SMTPSecure = 'tls';`
  3331. * @access public
  3332. * @param string $name The property name to set
  3333. * @param mixed $value The value to set the property to
  3334. * @return boolean
  3335. * @TODO Should this not be using the __set() magic function?
  3336. */
  3337. public function set($name, $value = '')
  3338. {
  3339. if (property_exists($this, $name)) {
  3340. $this->$name = $value;
  3341. return true;
  3342. } else {
  3343. $this->setError($this->lang('variable_set') . $name);
  3344. return false;
  3345. }
  3346. }
  3347. /**
  3348. * Strip newlines to prevent header injection.
  3349. * @access public
  3350. * @param string $str
  3351. * @return string
  3352. */
  3353. public function secureHeader($str)
  3354. {
  3355. return trim(str_replace(array("\r", "\n"), '', $str));
  3356. }
  3357. /**
  3358. * Normalize line breaks in a string.
  3359. * Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format.
  3360. * Defaults to CRLF (for message bodies) and preserves consecutive breaks.
  3361. * @param string $text
  3362. * @param string $breaktype What kind of line break to use, defaults to CRLF
  3363. * @return string
  3364. * @access public
  3365. * @static
  3366. */
  3367. public static function normalizeBreaks($text, $breaktype = "\r\n")
  3368. {
  3369. return preg_replace('/(\r\n|\r|\n)/ms', $breaktype, $text);
  3370. }
  3371. /**
  3372. * Set the public and private key files and password for S/MIME signing.
  3373. * @access public
  3374. * @param string $cert_filename
  3375. * @param string $key_filename
  3376. * @param string $key_pass Password for private key
  3377. * @param string $extracerts_filename Optional path to chain certificate
  3378. */
  3379. public function sign($cert_filename, $key_filename, $key_pass, $extracerts_filename = '')
  3380. {
  3381. $this->sign_cert_file = $cert_filename;
  3382. $this->sign_key_file = $key_filename;
  3383. $this->sign_key_pass = $key_pass;
  3384. $this->sign_extracerts_file = $extracerts_filename;
  3385. }
  3386. /**
  3387. * Quoted-Printable-encode a DKIM header.
  3388. * @access public
  3389. * @param string $txt
  3390. * @return string
  3391. */
  3392. public function DKIM_QP($txt)
  3393. {
  3394. $line = '';
  3395. for ($i = 0; $i < strlen($txt); $i++) {
  3396. $ord = ord($txt[$i]);
  3397. if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) {
  3398. $line .= $txt[$i];
  3399. } else {
  3400. $line .= '=' . sprintf('%02X', $ord);
  3401. }
  3402. }
  3403. return $line;
  3404. }
  3405. /**
  3406. * Generate a DKIM signature.
  3407. * @access public
  3408. * @param string $signHeader
  3409. * @throws phpmailerException
  3410. * @return string
  3411. */
  3412. public function DKIM_Sign($signHeader)
  3413. {
  3414. if (!defined('PKCS7_TEXT')) {
  3415. if ($this->exceptions) {
  3416. throw new phpmailerException($this->lang('extension_missing') . 'openssl');
  3417. }
  3418. return '';
  3419. }
  3420. $privKeyStr = file_get_contents($this->DKIM_private);
  3421. if ($this->DKIM_passphrase != '') {
  3422. $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
  3423. } else {
  3424. $privKey = $privKeyStr;
  3425. }
  3426. if (openssl_sign($signHeader, $signature, $privKey)) {
  3427. return base64_encode($signature);
  3428. }
  3429. return '';
  3430. }
  3431. /**
  3432. * Generate a DKIM canonicalization header.
  3433. * @access public
  3434. * @param string $signHeader Header
  3435. * @return string
  3436. */
  3437. public function DKIM_HeaderC($signHeader)
  3438. {
  3439. $signHeader = preg_replace('/\r\n\s+/', ' ', $signHeader);
  3440. $lines = explode("\r\n", $signHeader);
  3441. foreach ($lines as $key => $line) {
  3442. list($heading, $value) = explode(':', $line, 2);
  3443. $heading = strtolower($heading);
  3444. $value = preg_replace('/\s+/', ' ', $value); // Compress useless spaces
  3445. $lines[$key] = $heading . ':' . trim($value); // Don't forget to remove WSP around the value
  3446. }
  3447. $signHeader = implode("\r\n", $lines);
  3448. return $signHeader;
  3449. }
  3450. /**
  3451. * Generate a DKIM canonicalization body.
  3452. * @access public
  3453. * @param string $body Message Body
  3454. * @return string
  3455. */
  3456. public function DKIM_BodyC($body)
  3457. {
  3458. if ($body == '') {
  3459. return "\r\n";
  3460. }
  3461. // stabilize line endings
  3462. $body = str_replace("\r\n", "\n", $body);
  3463. $body = str_replace("\n", "\r\n", $body);
  3464. // END stabilize line endings
  3465. while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") {
  3466. $body = substr($body, 0, strlen($body) - 2);
  3467. }
  3468. return $body;
  3469. }
  3470. /**
  3471. * Create the DKIM header and body in a new message header.
  3472. * @access public
  3473. * @param string $headers_line Header lines
  3474. * @param string $subject Subject
  3475. * @param string $body Body
  3476. * @return string
  3477. */
  3478. public function DKIM_Add($headers_line, $subject, $body)
  3479. {
  3480. $DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms
  3481. $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
  3482. $DKIMquery = 'dns/txt'; // Query method
  3483. $DKIMtime = time(); // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
  3484. $subject_header = "Subject: $subject";
  3485. $headers = explode($this->LE, $headers_line);
  3486. $from_header = '';
  3487. $to_header = '';
  3488. $current = '';
  3489. foreach ($headers as $header) {
  3490. if (strpos($header, 'From:') === 0) {
  3491. $from_header = $header;
  3492. $current = 'from_header';
  3493. } elseif (strpos($header, 'To:') === 0) {
  3494. $to_header = $header;
  3495. $current = 'to_header';
  3496. } else {
  3497. if (!empty($$current) && strpos($header, ' =?') === 0) {
  3498. $$current .= $header;
  3499. } else {
  3500. $current = '';
  3501. }
  3502. }
  3503. }
  3504. $from = str_replace('|', '=7C', $this->DKIM_QP($from_header));
  3505. $to = str_replace('|', '=7C', $this->DKIM_QP($to_header));
  3506. $subject = str_replace(
  3507. '|',
  3508. '=7C',
  3509. $this->DKIM_QP($subject_header)
  3510. ); // Copied header fields (dkim-quoted-printable)
  3511. $body = $this->DKIM_BodyC($body);
  3512. $DKIMlen = strlen($body); // Length of body
  3513. $DKIMb64 = base64_encode(pack('H*', sha1($body))); // Base64 of packed binary SHA-1 hash of body
  3514. if ('' == $this->DKIM_identity) {
  3515. $ident = '';
  3516. } else {
  3517. $ident = ' i=' . $this->DKIM_identity . ';';
  3518. }
  3519. $dkimhdrs = 'DKIM-Signature: v=1; a=' .
  3520. $DKIMsignatureType . '; q=' .
  3521. $DKIMquery . '; l=' .
  3522. $DKIMlen . '; s=' .
  3523. $this->DKIM_selector .
  3524. ";\r\n" .
  3525. "\tt=" . $DKIMtime . '; c=' . $DKIMcanonicalization . ";\r\n" .
  3526. "\th=From:To:Subject;\r\n" .
  3527. "\td=" . $this->DKIM_domain . ';' . $ident . "\r\n" .
  3528. "\tz=$from\r\n" .
  3529. "\t|$to\r\n" .
  3530. "\t|$subject;\r\n" .
  3531. "\tbh=" . $DKIMb64 . ";\r\n" .
  3532. "\tb=";
  3533. $toSign = $this->DKIM_HeaderC(
  3534. $from_header . "\r\n" .
  3535. $to_header . "\r\n" .
  3536. $subject_header . "\r\n" .
  3537. $dkimhdrs
  3538. );
  3539. $signed = $this->DKIM_Sign($toSign);
  3540. return $dkimhdrs . $signed . "\r\n";
  3541. }
  3542. /**
  3543. * Detect if a string contains a line longer than the maximum line length allowed.
  3544. * @param string $str
  3545. * @return boolean
  3546. * @static
  3547. */
  3548. public static function hasLineLongerThanMax($str)
  3549. {
  3550. //+2 to include CRLF line break for a 1000 total
  3551. return (boolean)preg_match('/^(.{'.(self::MAX_LINE_LENGTH + 2).',})/m', $str);
  3552. }
  3553. /**
  3554. * Allows for public read access to 'to' property.
  3555. * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included.
  3556. * @access public
  3557. * @return array
  3558. */
  3559. public function getToAddresses()
  3560. {
  3561. return $this->to;
  3562. }
  3563. /**
  3564. * Allows for public read access to 'cc' property.
  3565. * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included.
  3566. * @access public
  3567. * @return array
  3568. */
  3569. public function getCcAddresses()
  3570. {
  3571. return $this->cc;
  3572. }
  3573. /**
  3574. * Allows for public read access to 'bcc' property.
  3575. * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included.
  3576. * @access public
  3577. * @return array
  3578. */
  3579. public function getBccAddresses()
  3580. {
  3581. return $this->bcc;
  3582. }
  3583. /**
  3584. * Allows for public read access to 'ReplyTo' property.
  3585. * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included.
  3586. * @access public
  3587. * @return array
  3588. */
  3589. public function getReplyToAddresses()
  3590. {
  3591. return $this->ReplyTo;
  3592. }
  3593. /**
  3594. * Allows for public read access to 'all_recipients' property.
  3595. * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included.
  3596. * @access public
  3597. * @return array
  3598. */
  3599. public function getAllRecipientAddresses()
  3600. {
  3601. return $this->all_recipients;
  3602. }
  3603. /**
  3604. * Perform a callback.
  3605. * @param boolean $isSent
  3606. * @param array $to
  3607. * @param array $cc
  3608. * @param array $bcc
  3609. * @param string $subject
  3610. * @param string $body
  3611. * @param string $from
  3612. */
  3613. protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from)
  3614. {
  3615. if (!empty($this->action_function) && is_callable($this->action_function)) {
  3616. $params = array($isSent, $to, $cc, $bcc, $subject, $body, $from);
  3617. call_user_func_array($this->action_function, $params);
  3618. }
  3619. }
  3620. }
  3621. /**
  3622. * PHPMailer exception handler
  3623. * @package PHPMailer
  3624. */
  3625. class phpmailerException extends Exception
  3626. {
  3627. /**
  3628. * Prettify error message output
  3629. * @return string
  3630. */
  3631. public function errorMessage()
  3632. {
  3633. $errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n";
  3634. return $errorMsg;
  3635. }
  3636. }