Email.php 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 2.0.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Mailer;
  16. use BadMethodCallException;
  17. use Cake\Core\App;
  18. use Cake\Core\Configure;
  19. use Cake\Core\StaticConfigTrait;
  20. use Cake\Filesystem\File;
  21. use Cake\Http\Client\FormDataPart;
  22. use Cake\Log\Log;
  23. use Cake\Utility\Hash;
  24. use Cake\Utility\Security;
  25. use Cake\Utility\Text;
  26. use Cake\View\ViewVarsTrait;
  27. use Closure;
  28. use Exception;
  29. use InvalidArgumentException;
  30. use JsonSerializable;
  31. use LogicException;
  32. use PDO;
  33. use RuntimeException;
  34. use Serializable;
  35. use SimpleXMLElement;
  36. /**
  37. * CakePHP Email class.
  38. *
  39. * This class is used for sending Internet Message Format based
  40. * on the standard outlined in https://www.rfc-editor.org/rfc/rfc2822.txt
  41. *
  42. * ### Configuration
  43. *
  44. * Configuration for Email is managed by Email::config() and Email::configTransport().
  45. * Email::config() can be used to add or read a configuration profile for Email instances.
  46. * Once made configuration profiles can be used to re-use across various email messages your
  47. * application sends.
  48. */
  49. class Email implements JsonSerializable, Serializable
  50. {
  51. use StaticConfigTrait;
  52. use ViewVarsTrait;
  53. /**
  54. * Line length - no should more - RFC 2822 - 2.1.1
  55. *
  56. * @var int
  57. */
  58. const LINE_LENGTH_SHOULD = 78;
  59. /**
  60. * Line length - no must more - RFC 2822 - 2.1.1
  61. *
  62. * @var int
  63. */
  64. const LINE_LENGTH_MUST = 998;
  65. /**
  66. * Type of message - HTML
  67. *
  68. * @var string
  69. */
  70. const MESSAGE_HTML = 'html';
  71. /**
  72. * Type of message - TEXT
  73. *
  74. * @var string
  75. */
  76. const MESSAGE_TEXT = 'text';
  77. /**
  78. * Holds the regex pattern for email validation
  79. *
  80. * @var string
  81. */
  82. const EMAIL_PATTERN = '/^((?:[\p{L}0-9.!#$%&\'*+\/=?^_`{|}~-]+)*@[\p{L}0-9-._]+)$/ui';
  83. /**
  84. * Recipient of the email
  85. *
  86. * @var array
  87. */
  88. protected $_to = [];
  89. /**
  90. * The mail which the email is sent from
  91. *
  92. * @var array
  93. */
  94. protected $_from = [];
  95. /**
  96. * The sender email
  97. *
  98. * @var array
  99. */
  100. protected $_sender = [];
  101. /**
  102. * The email the recipient will reply to
  103. *
  104. * @var array
  105. */
  106. protected $_replyTo = [];
  107. /**
  108. * The read receipt email
  109. *
  110. * @var array
  111. */
  112. protected $_readReceipt = [];
  113. /**
  114. * The mail that will be used in case of any errors like
  115. * - Remote mailserver down
  116. * - Remote user has exceeded his quota
  117. * - Unknown user
  118. *
  119. * @var array
  120. */
  121. protected $_returnPath = [];
  122. /**
  123. * Carbon Copy
  124. *
  125. * List of email's that should receive a copy of the email.
  126. * The Recipient WILL be able to see this list
  127. *
  128. * @var array
  129. */
  130. protected $_cc = [];
  131. /**
  132. * Blind Carbon Copy
  133. *
  134. * List of email's that should receive a copy of the email.
  135. * The Recipient WILL NOT be able to see this list
  136. *
  137. * @var array
  138. */
  139. protected $_bcc = [];
  140. /**
  141. * Message ID
  142. *
  143. * @var bool|string
  144. */
  145. protected $_messageId = true;
  146. /**
  147. * Domain for messageId generation.
  148. * Needs to be manually set for CLI mailing as env('HTTP_HOST') is empty
  149. *
  150. * @var string
  151. */
  152. protected $_domain;
  153. /**
  154. * The subject of the email
  155. *
  156. * @var string
  157. */
  158. protected $_subject = '';
  159. /**
  160. * Associative array of a user defined headers
  161. * Keys will be prefixed 'X-' as per RFC2822 Section 4.7.5
  162. *
  163. * @var array
  164. */
  165. protected $_headers = [];
  166. /**
  167. * Text message
  168. *
  169. * @var string
  170. */
  171. protected $_textMessage = '';
  172. /**
  173. * Html message
  174. *
  175. * @var string
  176. */
  177. protected $_htmlMessage = '';
  178. /**
  179. * Final message to send
  180. *
  181. * @var array
  182. */
  183. protected $_message = [];
  184. /**
  185. * Available formats to be sent.
  186. *
  187. * @var array
  188. */
  189. protected $_emailFormatAvailable = ['text', 'html', 'both'];
  190. /**
  191. * What format should the email be sent in
  192. *
  193. * @var string
  194. */
  195. protected $_emailFormat = 'text';
  196. /**
  197. * The transport instance to use for sending mail.
  198. *
  199. * @var \Cake\Mailer\AbstractTransport|null
  200. */
  201. protected $_transport;
  202. /**
  203. * Charset the email body is sent in
  204. *
  205. * @var string
  206. */
  207. public $charset = 'utf-8';
  208. /**
  209. * Charset the email header is sent in
  210. * If null, the $charset property will be used as default
  211. *
  212. * @var string|null
  213. */
  214. public $headerCharset;
  215. /**
  216. * The email transfer encoding used.
  217. * If null, the $charset property is used for determined the transfer encoding.
  218. *
  219. * @var string|null
  220. */
  221. protected $transferEncoding;
  222. /**
  223. * Available encoding to be set for transfer.
  224. *
  225. * @var array
  226. */
  227. protected $_transferEncodingAvailable = [
  228. '7bit',
  229. '8bit',
  230. 'base64',
  231. 'binary',
  232. 'quoted-printable'
  233. ];
  234. /**
  235. * The application wide charset, used to encode headers and body
  236. *
  237. * @var string|null
  238. */
  239. protected $_appCharset;
  240. /**
  241. * List of files that should be attached to the email.
  242. *
  243. * Only absolute paths
  244. *
  245. * @var array
  246. */
  247. protected $_attachments = [];
  248. /**
  249. * If set, boundary to use for multipart mime messages
  250. *
  251. * @var string|null
  252. */
  253. protected $_boundary;
  254. /**
  255. * Contains the optional priority of the email.
  256. *
  257. * @var int|null
  258. */
  259. protected $_priority;
  260. /**
  261. * An array mapping url schemes to fully qualified Transport class names
  262. *
  263. * @var array
  264. */
  265. protected static $_dsnClassMap = [
  266. 'debug' => 'Cake\Mailer\Transport\DebugTransport',
  267. 'mail' => 'Cake\Mailer\Transport\MailTransport',
  268. 'smtp' => 'Cake\Mailer\Transport\SmtpTransport',
  269. ];
  270. /**
  271. * Configuration profiles for transports.
  272. *
  273. * @var array
  274. */
  275. protected static $_transportConfig = [];
  276. /**
  277. * A copy of the configuration profile for this
  278. * instance. This copy can be modified with Email::profile().
  279. *
  280. * @var array
  281. */
  282. protected $_profile = [];
  283. /**
  284. * 8Bit character sets
  285. *
  286. * @var array
  287. */
  288. protected $_charset8bit = ['UTF-8', 'SHIFT_JIS'];
  289. /**
  290. * Define Content-Type charset name
  291. *
  292. * @var array
  293. */
  294. protected $_contentTypeCharset = [
  295. 'ISO-2022-JP-MS' => 'ISO-2022-JP'
  296. ];
  297. /**
  298. * Regex for email validation
  299. *
  300. * If null, filter_var() will be used. Use the emailPattern() method
  301. * to set a custom pattern.'
  302. *
  303. * @var string
  304. */
  305. protected $_emailPattern = self::EMAIL_PATTERN;
  306. /**
  307. * Constructor
  308. *
  309. * @param array|string|null $config Array of configs, or string to load configs from email.php
  310. */
  311. public function __construct($config = null)
  312. {
  313. $this->_appCharset = Configure::read('App.encoding');
  314. if ($this->_appCharset !== null) {
  315. $this->charset = $this->_appCharset;
  316. }
  317. $this->_domain = preg_replace('/\:\d+$/', '', env('HTTP_HOST'));
  318. if (empty($this->_domain)) {
  319. $this->_domain = php_uname('n');
  320. }
  321. $this->viewBuilder()
  322. ->setClassName('Cake\View\View')
  323. ->setTemplate('')
  324. ->setLayout('default')
  325. ->setHelpers(['Html']);
  326. if ($config === null) {
  327. $config = static::getConfig('default');
  328. }
  329. if ($config) {
  330. $this->setProfile($config);
  331. }
  332. if (empty($this->headerCharset)) {
  333. $this->headerCharset = $this->charset;
  334. }
  335. }
  336. /**
  337. * Clone ViewBuilder instance when email object is cloned.
  338. *
  339. * @return void
  340. */
  341. public function __clone()
  342. {
  343. $this->_viewBuilder = clone $this->viewBuilder();
  344. }
  345. /**
  346. * Sets "from" address.
  347. *
  348. * @param string|array $email Null to get, String with email,
  349. * Array with email as key, name as value or email as value (without name)
  350. * @param string|null $name Name
  351. * @return $this
  352. * @throws \InvalidArgumentException
  353. */
  354. public function setFrom($email, $name = null)
  355. {
  356. return $this->_setEmailSingle('_from', $email, $name, 'From requires only 1 email address.');
  357. }
  358. /**
  359. * Gets "from" address.
  360. *
  361. * @return array
  362. */
  363. public function getFrom()
  364. {
  365. return $this->_from;
  366. }
  367. /**
  368. * From
  369. *
  370. * @deprecated 3.4.0 Use setFrom()/getFrom() instead.
  371. * @param string|array|null $email Null to get, String with email,
  372. * Array with email as key, name as value or email as value (without name)
  373. * @param string|null $name Name
  374. * @return array|$this
  375. * @throws \InvalidArgumentException
  376. */
  377. public function from($email = null, $name = null)
  378. {
  379. deprecationWarning('Email::from() is deprecated. Use Email::setFrom() or Email::getFrom() instead.');
  380. if ($email === null) {
  381. return $this->getFrom();
  382. }
  383. return $this->setFrom($email, $name);
  384. }
  385. /**
  386. * Sets "sender" address.
  387. *
  388. * @param string|array $email String with email,
  389. * Array with email as key, name as value or email as value (without name)
  390. * @param string|null $name Name
  391. * @return $this
  392. * @throws \InvalidArgumentException
  393. */
  394. public function setSender($email, $name = null)
  395. {
  396. return $this->_setEmailSingle('_sender', $email, $name, 'Sender requires only 1 email address.');
  397. }
  398. /**
  399. * Gets "sender" address.
  400. *
  401. * @return array
  402. */
  403. public function getSender()
  404. {
  405. return $this->_sender;
  406. }
  407. /**
  408. * Sender
  409. *
  410. * @deprecated 3.4.0 Use setSender()/getSender() instead.
  411. * @param string|array|null $email Null to get, String with email,
  412. * Array with email as key, name as value or email as value (without name)
  413. * @param string|null $name Name
  414. * @return array|$this
  415. * @throws \InvalidArgumentException
  416. */
  417. public function sender($email = null, $name = null)
  418. {
  419. deprecationWarning('Email::sender() is deprecated. Use Email::setSender() or Email::getSender() instead.');
  420. if ($email === null) {
  421. return $this->getSender();
  422. }
  423. return $this->setSender($email, $name);
  424. }
  425. /**
  426. * Sets "Reply-To" address.
  427. *
  428. * @param string|array $email String with email,
  429. * Array with email as key, name as value or email as value (without name)
  430. * @param string|null $name Name
  431. * @return $this
  432. * @throws \InvalidArgumentException
  433. */
  434. public function setReplyTo($email, $name = null)
  435. {
  436. return $this->_setEmailSingle('_replyTo', $email, $name, 'Reply-To requires only 1 email address.');
  437. }
  438. /**
  439. * Gets "Reply-To" address.
  440. *
  441. * @return array
  442. */
  443. public function getReplyTo()
  444. {
  445. return $this->_replyTo;
  446. }
  447. /**
  448. * Reply-To
  449. *
  450. * @deprecated 3.4.0 Use setReplyTo()/getReplyTo() instead.
  451. * @param string|array|null $email Null to get, String with email,
  452. * Array with email as key, name as value or email as value (without name)
  453. * @param string|null $name Name
  454. * @return array|$this
  455. * @throws \InvalidArgumentException
  456. */
  457. public function replyTo($email = null, $name = null)
  458. {
  459. deprecationWarning('Email::replyTo() is deprecated. Use Email::setReplyTo() or Email::getReplyTo() instead.');
  460. if ($email === null) {
  461. return $this->getReplyTo();
  462. }
  463. return $this->setReplyTo($email, $name);
  464. }
  465. /**
  466. * Sets Read Receipt (Disposition-Notification-To header).
  467. *
  468. * @param string|array $email String with email,
  469. * Array with email as key, name as value or email as value (without name)
  470. * @param string|null $name Name
  471. * @return $this
  472. * @throws \InvalidArgumentException
  473. */
  474. public function setReadReceipt($email, $name = null)
  475. {
  476. return $this->_setEmailSingle('_readReceipt', $email, $name, 'Disposition-Notification-To requires only 1 email address.');
  477. }
  478. /**
  479. * Gets Read Receipt (Disposition-Notification-To header).
  480. *
  481. * @return array
  482. */
  483. public function getReadReceipt()
  484. {
  485. return $this->_readReceipt;
  486. }
  487. /**
  488. * Read Receipt (Disposition-Notification-To header)
  489. *
  490. * @deprecated 3.4.0 Use setReadReceipt()/getReadReceipt() instead.
  491. * @param string|array|null $email Null to get, String with email,
  492. * Array with email as key, name as value or email as value (without name)
  493. * @param string|null $name Name
  494. * @return array|$this
  495. * @throws \InvalidArgumentException
  496. */
  497. public function readReceipt($email = null, $name = null)
  498. {
  499. deprecationWarning('Email::readReceipt() is deprecated. Use Email::setReadReceipt() or Email::getReadReceipt() instead.');
  500. if ($email === null) {
  501. return $this->getReadReceipt();
  502. }
  503. return $this->setReadReceipt($email, $name);
  504. }
  505. /**
  506. * Return Path
  507. *
  508. * @param string|array $email String with email,
  509. * Array with email as key, name as value or email as value (without name)
  510. * @param string|null $name Name
  511. * @return $this
  512. * @throws \InvalidArgumentException
  513. */
  514. public function setReturnPath($email, $name = null)
  515. {
  516. return $this->_setEmailSingle('_returnPath', $email, $name, 'Return-Path requires only 1 email address.');
  517. }
  518. /**
  519. * Gets return path.
  520. *
  521. * @return array
  522. */
  523. public function getReturnPath()
  524. {
  525. return $this->_returnPath;
  526. }
  527. /**
  528. * Return Path
  529. *
  530. * @deprecated 3.4.0 Use setReturnPath()/getReturnPath() instead.
  531. * @param string|array|null $email Null to get, String with email,
  532. * Array with email as key, name as value or email as value (without name)
  533. * @param string|null $name Name
  534. * @return array|$this
  535. * @throws \InvalidArgumentException
  536. */
  537. public function returnPath($email = null, $name = null)
  538. {
  539. deprecationWarning('Email::returnPath() is deprecated. Use Email::setReturnPath() or Email::getReturnPath() instead.');
  540. if ($email === null) {
  541. return $this->getReturnPath();
  542. }
  543. return $this->setReturnPath($email, $name);
  544. }
  545. /**
  546. * Sets "to" address.
  547. *
  548. * @param string|array $email String with email,
  549. * Array with email as key, name as value or email as value (without name)
  550. * @param string|null $name Name
  551. * @return $this
  552. */
  553. public function setTo($email, $name = null)
  554. {
  555. return $this->_setEmail('_to', $email, $name);
  556. }
  557. /**
  558. * Gets "to" address
  559. *
  560. * @return array
  561. */
  562. public function getTo()
  563. {
  564. return $this->_to;
  565. }
  566. /**
  567. * To
  568. *
  569. * @deprecated 3.4.0 Use setTo()/getTo() instead.
  570. * @param string|array|null $email Null to get, String with email,
  571. * Array with email as key, name as value or email as value (without name)
  572. * @param string|null $name Name
  573. * @return array|$this
  574. */
  575. public function to($email = null, $name = null)
  576. {
  577. deprecationWarning('Email::to() is deprecated. Use Email::setTo() or Email::getTo() instead.');
  578. if ($email === null) {
  579. return $this->getTo();
  580. }
  581. return $this->setTo($email, $name);
  582. }
  583. /**
  584. * Add To
  585. *
  586. * @param string|array $email Null to get, String with email,
  587. * Array with email as key, name as value or email as value (without name)
  588. * @param string|null $name Name
  589. * @return $this
  590. */
  591. public function addTo($email, $name = null)
  592. {
  593. return $this->_addEmail('_to', $email, $name);
  594. }
  595. /**
  596. * Sets "cc" address.
  597. *
  598. * @param string|array $email String with email,
  599. * Array with email as key, name as value or email as value (without name)
  600. * @param string|null $name Name
  601. * @return $this
  602. */
  603. public function setCc($email, $name = null)
  604. {
  605. return $this->_setEmail('_cc', $email, $name);
  606. }
  607. /**
  608. * Gets "cc" address.
  609. *
  610. * @return array
  611. */
  612. public function getCc()
  613. {
  614. return $this->_cc;
  615. }
  616. /**
  617. * Cc
  618. *
  619. * @deprecated 3.4.0 Use setCc()/getCc() instead.
  620. * @param string|array|null $email Null to get, String with email,
  621. * Array with email as key, name as value or email as value (without name)
  622. * @param string|null $name Name
  623. * @return array|$this
  624. */
  625. public function cc($email = null, $name = null)
  626. {
  627. deprecationWarning('Email::cc() is deprecated. Use Email::setCc() or Email::getCc() instead.');
  628. if ($email === null) {
  629. return $this->getCc();
  630. }
  631. return $this->setCc($email, $name);
  632. }
  633. /**
  634. * Add Cc
  635. *
  636. * @param string|array $email Null to get, String with email,
  637. * Array with email as key, name as value or email as value (without name)
  638. * @param string|null $name Name
  639. * @return $this
  640. */
  641. public function addCc($email, $name = null)
  642. {
  643. return $this->_addEmail('_cc', $email, $name);
  644. }
  645. /**
  646. * Sets "bcc" address.
  647. *
  648. * @param string|array $email String with email,
  649. * Array with email as key, name as value or email as value (without name)
  650. * @param string|null $name Name
  651. * @return $this
  652. */
  653. public function setBcc($email, $name = null)
  654. {
  655. return $this->_setEmail('_bcc', $email, $name);
  656. }
  657. /**
  658. * Gets "bcc" address.
  659. *
  660. * @return array
  661. */
  662. public function getBcc()
  663. {
  664. return $this->_bcc;
  665. }
  666. /**
  667. * Bcc
  668. *
  669. * @deprecated 3.4.0 Use setBcc()/getBcc() instead.
  670. * @param string|array|null $email Null to get, String with email,
  671. * Array with email as key, name as value or email as value (without name)
  672. * @param string|null $name Name
  673. * @return array|$this
  674. */
  675. public function bcc($email = null, $name = null)
  676. {
  677. deprecationWarning('Email::bcc() is deprecated. Use Email::setBcc() or Email::getBcc() instead.');
  678. if ($email === null) {
  679. return $this->getBcc();
  680. }
  681. return $this->setBcc($email, $name);
  682. }
  683. /**
  684. * Add Bcc
  685. *
  686. * @param string|array $email Null to get, String with email,
  687. * Array with email as key, name as value or email as value (without name)
  688. * @param string|null $name Name
  689. * @return $this
  690. */
  691. public function addBcc($email, $name = null)
  692. {
  693. return $this->_addEmail('_bcc', $email, $name);
  694. }
  695. /**
  696. * Charset setter.
  697. *
  698. * @param string|null $charset Character set.
  699. * @return $this
  700. */
  701. public function setCharset($charset)
  702. {
  703. $this->charset = $charset;
  704. if (!$this->headerCharset) {
  705. $this->headerCharset = $charset;
  706. }
  707. return $this;
  708. }
  709. /**
  710. * Charset getter.
  711. *
  712. * @return string Charset
  713. */
  714. public function getCharset()
  715. {
  716. return $this->charset;
  717. }
  718. /**
  719. * Charset setter/getter
  720. *
  721. * @deprecated 3.4.0 Use setCharset()/getCharset() instead.
  722. * @param string|null $charset Character set.
  723. * @return string Charset
  724. */
  725. public function charset($charset = null)
  726. {
  727. deprecationWarning('Email::charset() is deprecated. Use Email::setCharset() or Email::getCharset() instead.');
  728. if ($charset === null) {
  729. return $this->getCharset();
  730. }
  731. $this->setCharset($charset);
  732. return $this->charset;
  733. }
  734. /**
  735. * HeaderCharset setter.
  736. *
  737. * @param string|null $charset Character set.
  738. * @return $this
  739. */
  740. public function setHeaderCharset($charset)
  741. {
  742. $this->headerCharset = $charset;
  743. return $this;
  744. }
  745. /**
  746. * HeaderCharset getter.
  747. *
  748. * @return string Charset
  749. */
  750. public function getHeaderCharset()
  751. {
  752. return $this->headerCharset;
  753. }
  754. /**
  755. * HeaderCharset setter/getter
  756. *
  757. * @deprecated 3.4.0 Use setHeaderCharset()/getHeaderCharset() instead.
  758. * @param string|null $charset Character set.
  759. * @return string Charset
  760. */
  761. public function headerCharset($charset = null)
  762. {
  763. deprecationWarning('Email::headerCharset() is deprecated. Use Email::setHeaderCharset() or Email::getHeaderCharset() instead.');
  764. if ($charset === null) {
  765. return $this->getHeaderCharset();
  766. }
  767. $this->setHeaderCharset($charset);
  768. return $this->headerCharset;
  769. }
  770. /**
  771. * TransferEncoding setter.
  772. *
  773. * @param string|null $encoding Encoding set.
  774. * @return $this
  775. */
  776. public function setTransferEncoding($encoding)
  777. {
  778. $encoding = strtolower($encoding);
  779. if (!in_array($encoding, $this->_transferEncodingAvailable)) {
  780. throw new InvalidArgumentException(
  781. sprintf(
  782. 'Transfer encoding not available. Can be : %s.',
  783. implode(', ', $this->_transferEncodingAvailable)
  784. )
  785. );
  786. }
  787. $this->transferEncoding = $encoding;
  788. return $this;
  789. }
  790. /**
  791. * TransferEncoding getter.
  792. *
  793. * @return string|null Encoding
  794. */
  795. public function getTransferEncoding()
  796. {
  797. return $this->transferEncoding;
  798. }
  799. /**
  800. * EmailPattern setter/getter
  801. *
  802. * @param string|null $regex The pattern to use for email address validation,
  803. * null to unset the pattern and make use of filter_var() instead.
  804. * @return $this
  805. */
  806. public function setEmailPattern($regex)
  807. {
  808. $this->_emailPattern = $regex;
  809. return $this;
  810. }
  811. /**
  812. * EmailPattern setter/getter
  813. *
  814. * @return string
  815. */
  816. public function getEmailPattern()
  817. {
  818. return $this->_emailPattern;
  819. }
  820. /**
  821. * EmailPattern setter/getter
  822. *
  823. * @deprecated 3.4.0 Use setEmailPattern()/getEmailPattern() instead.
  824. * @param string|bool|null $regex The pattern to use for email address validation,
  825. * null to unset the pattern and make use of filter_var() instead, false or
  826. * nothing to return the current value
  827. * @return string|$this
  828. */
  829. public function emailPattern($regex = false)
  830. {
  831. deprecationWarning('Email::emailPattern() is deprecated. Use Email::setEmailPattern() or Email::getEmailPattern() instead.');
  832. if ($regex === false) {
  833. return $this->getEmailPattern();
  834. }
  835. return $this->setEmailPattern($regex);
  836. }
  837. /**
  838. * Set email
  839. *
  840. * @param string $varName Property name
  841. * @param string|array $email String with email,
  842. * Array with email as key, name as value or email as value (without name)
  843. * @param string $name Name
  844. * @return $this
  845. * @throws \InvalidArgumentException
  846. */
  847. protected function _setEmail($varName, $email, $name)
  848. {
  849. if (!is_array($email)) {
  850. $this->_validateEmail($email, $varName);
  851. if ($name === null) {
  852. $name = $email;
  853. }
  854. $this->{$varName} = [$email => $name];
  855. return $this;
  856. }
  857. $list = [];
  858. foreach ($email as $key => $value) {
  859. if (is_int($key)) {
  860. $key = $value;
  861. }
  862. $this->_validateEmail($key, $varName);
  863. $list[$key] = $value;
  864. }
  865. $this->{$varName} = $list;
  866. return $this;
  867. }
  868. /**
  869. * Validate email address
  870. *
  871. * @param string $email Email address to validate
  872. * @param string $context Which property was set
  873. * @return void
  874. * @throws \InvalidArgumentException If email address does not validate
  875. */
  876. protected function _validateEmail($email, $context)
  877. {
  878. if ($this->_emailPattern === null) {
  879. if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
  880. return;
  881. }
  882. } elseif (preg_match($this->_emailPattern, $email)) {
  883. return;
  884. }
  885. $context = ltrim($context, '_');
  886. if ($email == '') {
  887. throw new InvalidArgumentException(sprintf('The email set for "%s" is empty.', $context));
  888. }
  889. throw new InvalidArgumentException(sprintf('Invalid email set for "%s". You passed "%s".', $context, $email));
  890. }
  891. /**
  892. * Set only 1 email
  893. *
  894. * @param string $varName Property name
  895. * @param string|array $email String with email,
  896. * Array with email as key, name as value or email as value (without name)
  897. * @param string $name Name
  898. * @param string $throwMessage Exception message
  899. * @return $this
  900. * @throws \InvalidArgumentException
  901. */
  902. protected function _setEmailSingle($varName, $email, $name, $throwMessage)
  903. {
  904. if ($email === []) {
  905. $this->{$varName} = $email;
  906. return $this;
  907. }
  908. $current = $this->{$varName};
  909. $this->_setEmail($varName, $email, $name);
  910. if (count($this->{$varName}) !== 1) {
  911. $this->{$varName} = $current;
  912. throw new InvalidArgumentException($throwMessage);
  913. }
  914. return $this;
  915. }
  916. /**
  917. * Add email
  918. *
  919. * @param string $varName Property name
  920. * @param string|array $email String with email,
  921. * Array with email as key, name as value or email as value (without name)
  922. * @param string $name Name
  923. * @return $this
  924. * @throws \InvalidArgumentException
  925. */
  926. protected function _addEmail($varName, $email, $name)
  927. {
  928. if (!is_array($email)) {
  929. $this->_validateEmail($email, $varName);
  930. if ($name === null) {
  931. $name = $email;
  932. }
  933. $this->{$varName}[$email] = $name;
  934. return $this;
  935. }
  936. $list = [];
  937. foreach ($email as $key => $value) {
  938. if (is_int($key)) {
  939. $key = $value;
  940. }
  941. $this->_validateEmail($key, $varName);
  942. $list[$key] = $value;
  943. }
  944. $this->{$varName} = array_merge($this->{$varName}, $list);
  945. return $this;
  946. }
  947. /**
  948. * Sets subject.
  949. *
  950. * @param string $subject Subject string.
  951. * @return $this
  952. */
  953. public function setSubject($subject)
  954. {
  955. $this->_subject = $this->_encode((string)$subject);
  956. return $this;
  957. }
  958. /**
  959. * Gets subject.
  960. *
  961. * @return string
  962. */
  963. public function getSubject()
  964. {
  965. return $this->_subject;
  966. }
  967. /**
  968. * Get/Set Subject.
  969. *
  970. * @deprecated 3.4.0 Use setSubject()/getSubject() instead.
  971. * @param string|null $subject Subject string.
  972. * @return string|$this
  973. */
  974. public function subject($subject = null)
  975. {
  976. deprecationWarning('Email::subject() is deprecated. Use Email::setSubject() or Email::getSubject() instead.');
  977. if ($subject === null) {
  978. return $this->getSubject();
  979. }
  980. return $this->setSubject($subject);
  981. }
  982. /**
  983. * Get original subject without encoding
  984. *
  985. * @return string Original subject
  986. */
  987. public function getOriginalSubject()
  988. {
  989. return $this->_decode($this->_subject);
  990. }
  991. /**
  992. * Sets headers for the message
  993. *
  994. * @param array $headers Associative array containing headers to be set.
  995. * @return $this
  996. */
  997. public function setHeaders(array $headers)
  998. {
  999. $this->_headers = $headers;
  1000. return $this;
  1001. }
  1002. /**
  1003. * Add header for the message
  1004. *
  1005. * @param array $headers Headers to set.
  1006. * @return $this
  1007. */
  1008. public function addHeaders(array $headers)
  1009. {
  1010. $this->_headers = array_merge($this->_headers, $headers);
  1011. return $this;
  1012. }
  1013. /**
  1014. * Get list of headers
  1015. *
  1016. * ### Includes:
  1017. *
  1018. * - `from`
  1019. * - `replyTo`
  1020. * - `readReceipt`
  1021. * - `returnPath`
  1022. * - `to`
  1023. * - `cc`
  1024. * - `bcc`
  1025. * - `subject`
  1026. *
  1027. * @param array $include List of headers.
  1028. * @return array
  1029. */
  1030. public function getHeaders(array $include = [])
  1031. {
  1032. if ($include == array_values($include)) {
  1033. $include = array_fill_keys($include, true);
  1034. }
  1035. $defaults = array_fill_keys(
  1036. [
  1037. 'from', 'sender', 'replyTo', 'readReceipt', 'returnPath',
  1038. 'to', 'cc', 'bcc', 'subject'],
  1039. false
  1040. );
  1041. $include += $defaults;
  1042. $headers = [];
  1043. $relation = [
  1044. 'from' => 'From',
  1045. 'replyTo' => 'Reply-To',
  1046. 'readReceipt' => 'Disposition-Notification-To',
  1047. 'returnPath' => 'Return-Path'
  1048. ];
  1049. foreach ($relation as $var => $header) {
  1050. if ($include[$var]) {
  1051. $var = '_' . $var;
  1052. $headers[$header] = current($this->_formatAddress($this->{$var}));
  1053. }
  1054. }
  1055. if ($include['sender']) {
  1056. if (key($this->_sender) === key($this->_from)) {
  1057. $headers['Sender'] = '';
  1058. } else {
  1059. $headers['Sender'] = current($this->_formatAddress($this->_sender));
  1060. }
  1061. }
  1062. foreach (['to', 'cc', 'bcc'] as $var) {
  1063. if ($include[$var]) {
  1064. $classVar = '_' . $var;
  1065. $headers[ucfirst($var)] = implode(', ', $this->_formatAddress($this->{$classVar}));
  1066. }
  1067. }
  1068. $headers += $this->_headers;
  1069. if (!isset($headers['Date'])) {
  1070. $headers['Date'] = date(DATE_RFC2822);
  1071. }
  1072. if ($this->_messageId !== false) {
  1073. if ($this->_messageId === true) {
  1074. $headers['Message-ID'] = '<' . str_replace('-', '', Text::uuid()) . '@' . $this->_domain . '>';
  1075. } else {
  1076. $headers['Message-ID'] = $this->_messageId;
  1077. }
  1078. }
  1079. if ($this->_priority) {
  1080. $headers['X-Priority'] = $this->_priority;
  1081. }
  1082. if ($include['subject']) {
  1083. $headers['Subject'] = $this->_subject;
  1084. }
  1085. $headers['MIME-Version'] = '1.0';
  1086. if ($this->_attachments) {
  1087. $headers['Content-Type'] = 'multipart/mixed; boundary="' . $this->_boundary . '"';
  1088. } elseif ($this->_emailFormat === 'both') {
  1089. $headers['Content-Type'] = 'multipart/alternative; boundary="' . $this->_boundary . '"';
  1090. } elseif ($this->_emailFormat === 'text') {
  1091. $headers['Content-Type'] = 'text/plain; charset=' . $this->_getContentTypeCharset();
  1092. } elseif ($this->_emailFormat === 'html') {
  1093. $headers['Content-Type'] = 'text/html; charset=' . $this->_getContentTypeCharset();
  1094. }
  1095. $headers['Content-Transfer-Encoding'] = $this->_getContentTransferEncoding();
  1096. return $headers;
  1097. }
  1098. /**
  1099. * Format addresses
  1100. *
  1101. * If the address contains non alphanumeric/whitespace characters, it will
  1102. * be quoted as characters like `:` and `,` are known to cause issues
  1103. * in address header fields.
  1104. *
  1105. * @param array $address Addresses to format.
  1106. * @return array
  1107. */
  1108. protected function _formatAddress($address)
  1109. {
  1110. $return = [];
  1111. foreach ($address as $email => $alias) {
  1112. if ($email === $alias) {
  1113. $return[] = $email;
  1114. } else {
  1115. $encoded = $this->_encode($alias);
  1116. if ($encoded === $alias && preg_match('/[^a-z0-9 ]/i', $encoded)) {
  1117. $encoded = '"' . str_replace('"', '\"', $encoded) . '"';
  1118. }
  1119. $return[] = sprintf('%s <%s>', $encoded, $email);
  1120. }
  1121. }
  1122. return $return;
  1123. }
  1124. /**
  1125. * Sets template.
  1126. *
  1127. * @param string|null $template Template name or null to not use.
  1128. * @return $this
  1129. */
  1130. public function setTemplate($template)
  1131. {
  1132. $this->viewBuilder()->setTemplate($template ?: '');
  1133. return $this;
  1134. }
  1135. /**
  1136. * Gets template.
  1137. *
  1138. * @return string
  1139. */
  1140. public function getTemplate()
  1141. {
  1142. return $this->viewBuilder()->getTemplate();
  1143. }
  1144. /**
  1145. * Sets layout.
  1146. *
  1147. * @param string|null $layout Layout name or null to not use
  1148. * @return $this
  1149. */
  1150. public function setLayout($layout)
  1151. {
  1152. $this->viewBuilder()->setLayout($layout ?: false);
  1153. return $this;
  1154. }
  1155. /**
  1156. * Gets layout.
  1157. *
  1158. * @return string
  1159. */
  1160. public function getLayout()
  1161. {
  1162. return $this->viewBuilder()->getLayout();
  1163. }
  1164. /**
  1165. * Template and layout
  1166. *
  1167. * @deprecated 3.4.0 Use setTemplate()/getTemplate() and setLayout()/getLayout() instead.
  1168. * @param bool|string $template Template name or null to not use
  1169. * @param bool|string $layout Layout name or null to not use
  1170. * @return array|$this
  1171. */
  1172. public function template($template = false, $layout = false)
  1173. {
  1174. deprecationWarning('Email::template() is deprecated. Use Email::setTemplate() or Email::getTemplate() and Email::setLayout() or Email::getLayout() instead.');
  1175. if ($template === false) {
  1176. return [
  1177. 'template' => $this->getTemplate(),
  1178. 'layout' => $this->getLayout()
  1179. ];
  1180. }
  1181. $this->setTemplate($template);
  1182. if ($layout !== false) {
  1183. $this->setLayout($layout);
  1184. }
  1185. return $this;
  1186. }
  1187. /**
  1188. * Sets view class for render.
  1189. *
  1190. * @param string $viewClass View class name.
  1191. * @return $this
  1192. */
  1193. public function setViewRenderer($viewClass)
  1194. {
  1195. $this->viewBuilder()->setClassName($viewClass);
  1196. return $this;
  1197. }
  1198. /**
  1199. * Gets view class for render.
  1200. *
  1201. * @return string
  1202. */
  1203. public function getViewRenderer()
  1204. {
  1205. return $this->viewBuilder()->getClassName();
  1206. }
  1207. /**
  1208. * View class for render
  1209. *
  1210. * @deprecated 3.4.0 Use setViewRenderer()/getViewRenderer() instead.
  1211. * @param string|null $viewClass View class name.
  1212. * @return string|$this
  1213. */
  1214. public function viewRender($viewClass = null)
  1215. {
  1216. deprecationWarning('Email::viewRender() is deprecated. Use Email::setViewRenderer() or Email::getViewRenderer() instead.');
  1217. if ($viewClass === null) {
  1218. return $this->getViewRenderer();
  1219. }
  1220. $this->setViewRenderer($viewClass);
  1221. return $this;
  1222. }
  1223. /**
  1224. * Sets variables to be set on render.
  1225. *
  1226. * @param array $viewVars Variables to set for view.
  1227. * @return $this
  1228. */
  1229. public function setViewVars($viewVars)
  1230. {
  1231. $this->set((array)$viewVars);
  1232. return $this;
  1233. }
  1234. /**
  1235. * Gets variables to be set on render.
  1236. *
  1237. * @return array
  1238. */
  1239. public function getViewVars()
  1240. {
  1241. return $this->viewVars;
  1242. }
  1243. /**
  1244. * Variables to be set on render
  1245. *
  1246. * @deprecated 3.4.0 Use setViewVars()/getViewVars() instead.
  1247. * @param array|null $viewVars Variables to set for view.
  1248. * @return array|$this
  1249. */
  1250. public function viewVars($viewVars = null)
  1251. {
  1252. deprecationWarning('Email::viewVars() is deprecated. Use Email::setViewVars() or Email::getViewVars() instead.');
  1253. if ($viewVars === null) {
  1254. return $this->getViewVars();
  1255. }
  1256. return $this->setViewVars($viewVars);
  1257. }
  1258. /**
  1259. * Sets theme to use when rendering.
  1260. *
  1261. * @param string $theme Theme name.
  1262. * @return $this
  1263. */
  1264. public function setTheme($theme)
  1265. {
  1266. $this->viewBuilder()->setTheme($theme);
  1267. return $this;
  1268. }
  1269. /**
  1270. * Gets theme to use when rendering.
  1271. *
  1272. * @return string
  1273. */
  1274. public function getTheme()
  1275. {
  1276. return $this->viewBuilder()->getTheme();
  1277. }
  1278. /**
  1279. * Theme to use when rendering
  1280. *
  1281. * @deprecated 3.4.0 Use setTheme()/getTheme() instead.
  1282. * @param string|null $theme Theme name.
  1283. * @return string|$this
  1284. */
  1285. public function theme($theme = null)
  1286. {
  1287. deprecationWarning('Email::theme() is deprecated. Use Email::setTheme() or Email::getTheme() instead.');
  1288. if ($theme === null) {
  1289. return $this->getTheme();
  1290. }
  1291. return $this->setTheme($theme);
  1292. }
  1293. /**
  1294. * Sets helpers to be used when rendering.
  1295. *
  1296. * @param array $helpers Helpers list.
  1297. * @return $this
  1298. */
  1299. public function setHelpers(array $helpers)
  1300. {
  1301. $this->viewBuilder()->setHelpers($helpers, false);
  1302. return $this;
  1303. }
  1304. /**
  1305. * Gets helpers to be used when rendering.
  1306. *
  1307. * @return array
  1308. */
  1309. public function getHelpers()
  1310. {
  1311. return $this->viewBuilder()->getHelpers();
  1312. }
  1313. /**
  1314. * Helpers to be used in render
  1315. *
  1316. * @deprecated 3.4.0 Use setHelpers()/getHelpers() instead.
  1317. * @param array|null $helpers Helpers list.
  1318. * @return array|$this
  1319. */
  1320. public function helpers($helpers = null)
  1321. {
  1322. deprecationWarning('Email::helpers() is deprecated. Use Email::setHelpers() or Email::getHelpers() instead.');
  1323. if ($helpers === null) {
  1324. return $this->getHelpers();
  1325. }
  1326. return $this->setHelpers((array)$helpers);
  1327. }
  1328. /**
  1329. * Sets email format.
  1330. *
  1331. * @param string $format Formatting string.
  1332. * @return $this
  1333. * @throws \InvalidArgumentException
  1334. */
  1335. public function setEmailFormat($format)
  1336. {
  1337. if (!in_array($format, $this->_emailFormatAvailable)) {
  1338. throw new InvalidArgumentException('Format not available.');
  1339. }
  1340. $this->_emailFormat = $format;
  1341. return $this;
  1342. }
  1343. /**
  1344. * Gets email format.
  1345. *
  1346. * @return string
  1347. */
  1348. public function getEmailFormat()
  1349. {
  1350. return $this->_emailFormat;
  1351. }
  1352. /**
  1353. * Email format
  1354. *
  1355. * @deprecated 3.4.0 Use setEmailFormat()/getEmailFormat() instead.
  1356. * @param string|null $format Formatting string.
  1357. * @return string|$this
  1358. * @throws \InvalidArgumentException
  1359. */
  1360. public function emailFormat($format = null)
  1361. {
  1362. deprecationWarning('Email::emailFormat() is deprecated. Use Email::setEmailFormat() or Email::getEmailFormat() instead.');
  1363. if ($format === null) {
  1364. return $this->getEmailFormat();
  1365. }
  1366. return $this->setEmailFormat($format);
  1367. }
  1368. /**
  1369. * Sets the transport.
  1370. *
  1371. * When setting the transport you can either use the name
  1372. * of a configured transport or supply a constructed transport.
  1373. *
  1374. * @param string|\Cake\Mailer\AbstractTransport $name Either the name of a configured
  1375. * transport, or a transport instance.
  1376. * @return $this
  1377. * @throws \LogicException When the chosen transport lacks a send method.
  1378. * @throws \InvalidArgumentException When $name is neither a string nor an object.
  1379. */
  1380. public function setTransport($name)
  1381. {
  1382. if (is_string($name)) {
  1383. $transport = $this->_constructTransport($name);
  1384. } elseif (is_object($name)) {
  1385. $transport = $name;
  1386. } else {
  1387. throw new InvalidArgumentException(
  1388. sprintf('The value passed for the "$name" argument must be either a string, or an object, %s given.', gettype($name))
  1389. );
  1390. }
  1391. if (!method_exists($transport, 'send')) {
  1392. throw new LogicException(sprintf('The "%s" do not have send method.', get_class($transport)));
  1393. }
  1394. $this->_transport = $transport;
  1395. return $this;
  1396. }
  1397. /**
  1398. * Gets the transport.
  1399. *
  1400. * @return \Cake\Mailer\AbstractTransport
  1401. */
  1402. public function getTransport()
  1403. {
  1404. return $this->_transport;
  1405. }
  1406. /**
  1407. * Get/set the transport.
  1408. *
  1409. * When setting the transport you can either use the name
  1410. * of a configured transport or supply a constructed transport.
  1411. *
  1412. * @deprecated 3.4.0 Use setTransport()/getTransport() instead.
  1413. * @param string|\Cake\Mailer\AbstractTransport|null $name Either the name of a configured
  1414. * transport, or a transport instance.
  1415. * @return \Cake\Mailer\AbstractTransport|$this
  1416. * @throws \LogicException When the chosen transport lacks a send method.
  1417. * @throws \InvalidArgumentException When $name is neither a string nor an object.
  1418. */
  1419. public function transport($name = null)
  1420. {
  1421. deprecationWarning('Email::transport() is deprecated. Use Email::setTransport() or Email::getTransport() instead.');
  1422. if ($name === null) {
  1423. return $this->getTransport();
  1424. }
  1425. return $this->setTransport($name);
  1426. }
  1427. /**
  1428. * Build a transport instance from configuration data.
  1429. *
  1430. * @param string $name The transport configuration name to build.
  1431. * @return \Cake\Mailer\AbstractTransport
  1432. * @throws \InvalidArgumentException When transport configuration is missing or invalid.
  1433. */
  1434. protected function _constructTransport($name)
  1435. {
  1436. if (!isset(static::$_transportConfig[$name])) {
  1437. throw new InvalidArgumentException(sprintf('Transport config "%s" is missing.', $name));
  1438. }
  1439. if (!isset(static::$_transportConfig[$name]['className'])) {
  1440. throw new InvalidArgumentException(
  1441. sprintf('Transport config "%s" is invalid, the required `className` option is missing', $name)
  1442. );
  1443. }
  1444. $config = static::$_transportConfig[$name];
  1445. if (is_object($config['className'])) {
  1446. if (!$config['className'] instanceof AbstractTransport) {
  1447. throw new InvalidArgumentException(sprintf(
  1448. 'Transport object must be of type "AbstractTransport". Found invalid type: "%s".',
  1449. get_class($config['className'])
  1450. ));
  1451. }
  1452. return $config['className'];
  1453. }
  1454. $className = App::className($config['className'], 'Mailer/Transport', 'Transport');
  1455. if (!$className) {
  1456. $className = App::className($config['className'], 'Network/Email', 'Transport');
  1457. if ($className) {
  1458. trigger_error(
  1459. 'Transports in "Network/Email" are deprecated, use "Mailer/Transport" instead.',
  1460. E_USER_DEPRECATED
  1461. );
  1462. }
  1463. }
  1464. if (!$className) {
  1465. throw new InvalidArgumentException(sprintf('Transport class "%s" not found.', $config['className']));
  1466. }
  1467. if (!method_exists($className, 'send')) {
  1468. throw new InvalidArgumentException(sprintf('The "%s" does not have a send() method.', $className));
  1469. }
  1470. unset($config['className']);
  1471. return new $className($config);
  1472. }
  1473. /**
  1474. * Sets message ID.
  1475. *
  1476. * @param bool|string $message True to generate a new Message-ID, False to ignore (not send in email), String to set as Message-ID.
  1477. * @return $this
  1478. * @throws \InvalidArgumentException
  1479. */
  1480. public function setMessageId($message)
  1481. {
  1482. if (is_bool($message)) {
  1483. $this->_messageId = $message;
  1484. } else {
  1485. if (!preg_match('/^\<.+@.+\>$/', $message)) {
  1486. throw new InvalidArgumentException('Invalid format to Message-ID. The text should be something like "<uuid@server.com>"');
  1487. }
  1488. $this->_messageId = $message;
  1489. }
  1490. return $this;
  1491. }
  1492. /**
  1493. * Gets message ID.
  1494. *
  1495. * @return bool|string
  1496. */
  1497. public function getMessageId()
  1498. {
  1499. return $this->_messageId;
  1500. }
  1501. /**
  1502. * Message-ID
  1503. *
  1504. * @deprecated 3.4.0 Use setMessageId()/getMessageId() instead.
  1505. * @param bool|string|null $message True to generate a new Message-ID, False to ignore (not send in email), String to set as Message-ID
  1506. * @return bool|string|$this
  1507. * @throws \InvalidArgumentException
  1508. */
  1509. public function messageId($message = null)
  1510. {
  1511. deprecationWarning('Email::messageId() is deprecated. Use Email::setMessageId() or Email::getMessageId() instead.');
  1512. if ($message === null) {
  1513. return $this->getMessageId();
  1514. }
  1515. return $this->setMessageId($message);
  1516. }
  1517. /**
  1518. * Sets domain.
  1519. *
  1520. * Domain as top level (the part after @).
  1521. *
  1522. * @param string $domain Manually set the domain for CLI mailing.
  1523. * @return $this
  1524. */
  1525. public function setDomain($domain)
  1526. {
  1527. $this->_domain = $domain;
  1528. return $this;
  1529. }
  1530. /**
  1531. * Gets domain.
  1532. *
  1533. * @return string
  1534. */
  1535. public function getDomain()
  1536. {
  1537. return $this->_domain;
  1538. }
  1539. /**
  1540. * Domain as top level (the part after @)
  1541. *
  1542. * @deprecated 3.4.0 Use setDomain()/getDomain() instead.
  1543. * @param string|null $domain Manually set the domain for CLI mailing
  1544. * @return string|$this
  1545. */
  1546. public function domain($domain = null)
  1547. {
  1548. deprecationWarning('Email::domain() is deprecated. Use Email::setDomain() or Email::getDomain() instead.');
  1549. if ($domain === null) {
  1550. return $this->getDomain();
  1551. }
  1552. return $this->setDomain($domain);
  1553. }
  1554. /**
  1555. * Add attachments to the email message
  1556. *
  1557. * Attachments can be defined in a few forms depending on how much control you need:
  1558. *
  1559. * Attach a single file:
  1560. *
  1561. * ```
  1562. * $email->setAttachments('path/to/file');
  1563. * ```
  1564. *
  1565. * Attach a file with a different filename:
  1566. *
  1567. * ```
  1568. * $email->setAttachments(['custom_name.txt' => 'path/to/file.txt']);
  1569. * ```
  1570. *
  1571. * Attach a file and specify additional properties:
  1572. *
  1573. * ```
  1574. * $email->setAttachments(['custom_name.png' => [
  1575. * 'file' => 'path/to/file',
  1576. * 'mimetype' => 'image/png',
  1577. * 'contentId' => 'abc123',
  1578. * 'contentDisposition' => false
  1579. * ]
  1580. * ]);
  1581. * ```
  1582. *
  1583. * Attach a file from string and specify additional properties:
  1584. *
  1585. * ```
  1586. * $email->setAttachments(['custom_name.png' => [
  1587. * 'data' => file_get_contents('path/to/file'),
  1588. * 'mimetype' => 'image/png'
  1589. * ]
  1590. * ]);
  1591. * ```
  1592. *
  1593. * The `contentId` key allows you to specify an inline attachment. In your email text, you
  1594. * can use `<img src="cid:abc123" />` to display the image inline.
  1595. *
  1596. * The `contentDisposition` key allows you to disable the `Content-Disposition` header, this can improve
  1597. * attachment compatibility with outlook email clients.
  1598. *
  1599. * @param string|array $attachments String with the filename or array with filenames
  1600. * @return $this
  1601. * @throws \InvalidArgumentException
  1602. */
  1603. public function setAttachments($attachments)
  1604. {
  1605. $attach = [];
  1606. foreach ((array)$attachments as $name => $fileInfo) {
  1607. if (!is_array($fileInfo)) {
  1608. $fileInfo = ['file' => $fileInfo];
  1609. }
  1610. if (!isset($fileInfo['file'])) {
  1611. if (!isset($fileInfo['data'])) {
  1612. throw new InvalidArgumentException('No file or data specified.');
  1613. }
  1614. if (is_int($name)) {
  1615. throw new InvalidArgumentException('No filename specified.');
  1616. }
  1617. $fileInfo['data'] = chunk_split(base64_encode($fileInfo['data']), 76, "\r\n");
  1618. } else {
  1619. $fileName = $fileInfo['file'];
  1620. $fileInfo['file'] = realpath($fileInfo['file']);
  1621. if ($fileInfo['file'] === false || !file_exists($fileInfo['file'])) {
  1622. throw new InvalidArgumentException(sprintf('File not found: "%s"', $fileName));
  1623. }
  1624. if (is_int($name)) {
  1625. $name = basename($fileInfo['file']);
  1626. }
  1627. }
  1628. if (!isset($fileInfo['mimetype']) && function_exists('mime_content_type')) {
  1629. $fileInfo['mimetype'] = mime_content_type($fileInfo['file']);
  1630. }
  1631. if (!isset($fileInfo['mimetype'])) {
  1632. $fileInfo['mimetype'] = 'application/octet-stream';
  1633. }
  1634. $attach[$name] = $fileInfo;
  1635. }
  1636. $this->_attachments = $attach;
  1637. return $this;
  1638. }
  1639. /**
  1640. * Gets attachments to the email message.
  1641. *
  1642. * @return array Array of attachments.
  1643. */
  1644. public function getAttachments()
  1645. {
  1646. return $this->_attachments;
  1647. }
  1648. /**
  1649. * Add attachments to the email message
  1650. *
  1651. * Attachments can be defined in a few forms depending on how much control you need:
  1652. *
  1653. * Attach a single file:
  1654. *
  1655. * ```
  1656. * $email->setAttachments('path/to/file');
  1657. * ```
  1658. *
  1659. * Attach a file with a different filename:
  1660. *
  1661. * ```
  1662. * $email->setAttachments(['custom_name.txt' => 'path/to/file.txt']);
  1663. * ```
  1664. *
  1665. * Attach a file and specify additional properties:
  1666. *
  1667. * ```
  1668. * $email->setAttachments(['custom_name.png' => [
  1669. * 'file' => 'path/to/file',
  1670. * 'mimetype' => 'image/png',
  1671. * 'contentId' => 'abc123',
  1672. * 'contentDisposition' => false
  1673. * ]
  1674. * ]);
  1675. * ```
  1676. *
  1677. * Attach a file from string and specify additional properties:
  1678. *
  1679. * ```
  1680. * $email->setAttachments(['custom_name.png' => [
  1681. * 'data' => file_get_contents('path/to/file'),
  1682. * 'mimetype' => 'image/png'
  1683. * ]
  1684. * ]);
  1685. * ```
  1686. *
  1687. * The `contentId` key allows you to specify an inline attachment. In your email text, you
  1688. * can use `<img src="cid:abc123" />` to display the image inline.
  1689. *
  1690. * The `contentDisposition` key allows you to disable the `Content-Disposition` header, this can improve
  1691. * attachment compatibility with outlook email clients.
  1692. *
  1693. * @deprecated 3.4.0 Use setAttachments()/getAttachments() instead.
  1694. * @param string|array|null $attachments String with the filename or array with filenames
  1695. * @return array|$this Either the array of attachments when getting or $this when setting.
  1696. * @throws \InvalidArgumentException
  1697. */
  1698. public function attachments($attachments = null)
  1699. {
  1700. deprecationWarning('Email::attachments() is deprecated. Use Email::setAttachments() or Email::getAttachments() instead.');
  1701. if ($attachments === null) {
  1702. return $this->getAttachments();
  1703. }
  1704. return $this->setAttachments($attachments);
  1705. }
  1706. /**
  1707. * Add attachments
  1708. *
  1709. * @param string|array $attachments String with the filename or array with filenames
  1710. * @return $this
  1711. * @throws \InvalidArgumentException
  1712. * @see \Cake\Mailer\Email::attachments()
  1713. */
  1714. public function addAttachments($attachments)
  1715. {
  1716. $current = $this->_attachments;
  1717. $this->setAttachments($attachments);
  1718. $this->_attachments = array_merge($current, $this->_attachments);
  1719. return $this;
  1720. }
  1721. /**
  1722. * Get generated message (used by transport classes)
  1723. *
  1724. * @param string|null $type Use MESSAGE_* constants or null to return the full message as array
  1725. * @return string|array String if type is given, array if type is null
  1726. */
  1727. public function message($type = null)
  1728. {
  1729. switch ($type) {
  1730. case static::MESSAGE_HTML:
  1731. return $this->_htmlMessage;
  1732. case static::MESSAGE_TEXT:
  1733. return $this->_textMessage;
  1734. }
  1735. return $this->_message;
  1736. }
  1737. /**
  1738. * Sets priority.
  1739. *
  1740. * @param int|null $priority 1 (highest) to 5 (lowest)
  1741. * @return $this
  1742. */
  1743. public function setPriority($priority)
  1744. {
  1745. $this->_priority = $priority;
  1746. return $this;
  1747. }
  1748. /**
  1749. * Gets priority.
  1750. *
  1751. * @return int
  1752. */
  1753. public function getPriority()
  1754. {
  1755. return $this->_priority;
  1756. }
  1757. /**
  1758. * Sets transport configuration.
  1759. *
  1760. * Use this method to define transports to use in delivery profiles.
  1761. * Once defined you cannot edit the configurations, and must use
  1762. * Email::dropTransport() to flush the configuration first.
  1763. *
  1764. * When using an array of configuration data a new transport
  1765. * will be constructed for each message sent. When using a Closure, the
  1766. * closure will be evaluated for each message.
  1767. *
  1768. * The `className` is used to define the class to use for a transport.
  1769. * It can either be a short name, or a fully qualified class name
  1770. *
  1771. * @param string|array $key The configuration name to write. Or
  1772. * an array of multiple transports to set.
  1773. * @param array|\Cake\Mailer\AbstractTransport|null $config Either an array of configuration
  1774. * data, or a transport instance. Null when using key as array.
  1775. * @return void
  1776. * @throws \BadMethodCallException When modifying an existing configuration.
  1777. */
  1778. public static function setConfigTransport($key, $config = null)
  1779. {
  1780. if (is_array($key)) {
  1781. foreach ($key as $name => $settings) {
  1782. static::setConfigTransport($name, $settings);
  1783. }
  1784. return;
  1785. }
  1786. if (isset(static::$_transportConfig[$key])) {
  1787. throw new BadMethodCallException(sprintf('Cannot modify an existing config "%s"', $key));
  1788. }
  1789. if (is_object($config)) {
  1790. $config = ['className' => $config];
  1791. }
  1792. if (isset($config['url'])) {
  1793. $parsed = static::parseDsn($config['url']);
  1794. unset($config['url']);
  1795. $config = $parsed + $config;
  1796. }
  1797. static::$_transportConfig[$key] = $config;
  1798. }
  1799. /**
  1800. * Gets current transport configuration.
  1801. *
  1802. * @param string $key The configuration name to read.
  1803. * @return array|null Transport config.
  1804. */
  1805. public static function getConfigTransport($key)
  1806. {
  1807. return isset(static::$_transportConfig[$key]) ? static::$_transportConfig[$key] : null;
  1808. }
  1809. /**
  1810. * Add or read transport configuration.
  1811. *
  1812. * Use this method to define transports to use in delivery profiles.
  1813. * Once defined you cannot edit the configurations, and must use
  1814. * Email::dropTransport() to flush the configuration first.
  1815. *
  1816. * When using an array of configuration data a new transport
  1817. * will be constructed for each message sent. When using a Closure, the
  1818. * closure will be evaluated for each message.
  1819. *
  1820. * The `className` is used to define the class to use for a transport.
  1821. * It can either be a short name, or a fully qualified classname
  1822. *
  1823. * @deprecated 3.4.0 Use setConfigTransport()/getConfigTransport() instead.
  1824. * @param string|array $key The configuration name to read/write. Or
  1825. * an array of multiple transports to set.
  1826. * @param array|\Cake\Mailer\AbstractTransport|null $config Either an array of configuration
  1827. * data, or a transport instance.
  1828. * @return array|null Either null when setting or an array of data when reading.
  1829. * @throws \BadMethodCallException When modifying an existing configuration.
  1830. */
  1831. public static function configTransport($key, $config = null)
  1832. {
  1833. deprecationWarning('Email::configTransport() is deprecated. Use Email::setConfigTransport() or Email::getConfigTransport() instead.');
  1834. if ($config === null && is_string($key)) {
  1835. return static::getConfigTransport($key);
  1836. }
  1837. if ($config === null && is_array($key)) {
  1838. static::setConfigTransport($key);
  1839. return null;
  1840. }
  1841. static::setConfigTransport($key, $config);
  1842. }
  1843. /**
  1844. * Returns an array containing the named transport configurations
  1845. *
  1846. * @return array Array of configurations.
  1847. */
  1848. public static function configuredTransport()
  1849. {
  1850. return array_keys(static::$_transportConfig);
  1851. }
  1852. /**
  1853. * Delete transport configuration.
  1854. *
  1855. * @param string $key The transport name to remove.
  1856. * @return void
  1857. */
  1858. public static function dropTransport($key)
  1859. {
  1860. unset(static::$_transportConfig[$key]);
  1861. }
  1862. /**
  1863. * Sets the configuration profile to use for this instance.
  1864. *
  1865. * @param string|array $config String with configuration name, or
  1866. * an array with config.
  1867. * @return $this
  1868. */
  1869. public function setProfile($config)
  1870. {
  1871. if (!is_array($config)) {
  1872. $config = (string)$config;
  1873. }
  1874. $this->_applyConfig($config);
  1875. return $this;
  1876. }
  1877. /**
  1878. * Gets the configuration profile to use for this instance.
  1879. *
  1880. * @return string|array
  1881. */
  1882. public function getProfile()
  1883. {
  1884. return $this->_profile;
  1885. }
  1886. /**
  1887. * Get/Set the configuration profile to use for this instance.
  1888. *
  1889. * @deprecated 3.4.0 Use setProfile()/getProfile() instead.
  1890. * @param null|string|array $config String with configuration name, or
  1891. * an array with config or null to return current config.
  1892. * @return string|array|$this
  1893. */
  1894. public function profile($config = null)
  1895. {
  1896. deprecationWarning('Email::profile() is deprecated. Use Email::setProfile() or Email::getProfile() instead.');
  1897. if ($config === null) {
  1898. return $this->getProfile();
  1899. }
  1900. return $this->setProfile($config);
  1901. }
  1902. /**
  1903. * Send an email using the specified content, template and layout
  1904. *
  1905. * @param string|array|null $content String with message or array with messages
  1906. * @return array
  1907. * @throws \BadMethodCallException
  1908. */
  1909. public function send($content = null)
  1910. {
  1911. if (empty($this->_from)) {
  1912. throw new BadMethodCallException('From is not specified.');
  1913. }
  1914. if (empty($this->_to) && empty($this->_cc) && empty($this->_bcc)) {
  1915. throw new BadMethodCallException('You need specify one destination on to, cc or bcc.');
  1916. }
  1917. if (is_array($content)) {
  1918. $content = implode("\n", $content) . "\n";
  1919. }
  1920. $this->_message = $this->_render($this->_wrap($content));
  1921. $transport = $this->getTransport();
  1922. if (!$transport) {
  1923. $msg = 'Cannot send email, transport was not defined. Did you call transport() or define ' .
  1924. ' a transport in the set profile?';
  1925. throw new BadMethodCallException($msg);
  1926. }
  1927. $contents = $transport->send($this);
  1928. $this->_logDelivery($contents);
  1929. return $contents;
  1930. }
  1931. /**
  1932. * Log the email message delivery.
  1933. *
  1934. * @param array $contents The content with 'headers' and 'message' keys.
  1935. * @return void
  1936. */
  1937. protected function _logDelivery($contents)
  1938. {
  1939. if (empty($this->_profile['log'])) {
  1940. return;
  1941. }
  1942. $config = [
  1943. 'level' => 'debug',
  1944. 'scope' => 'email'
  1945. ];
  1946. if ($this->_profile['log'] !== true) {
  1947. if (!is_array($this->_profile['log'])) {
  1948. $this->_profile['log'] = ['level' => $this->_profile['log']];
  1949. }
  1950. $config = $this->_profile['log'] + $config;
  1951. }
  1952. Log::write(
  1953. $config['level'],
  1954. PHP_EOL . $this->flatten($contents['headers']) . PHP_EOL . PHP_EOL . $this->flatten($contents['message']),
  1955. $config['scope']
  1956. );
  1957. }
  1958. /**
  1959. * Converts given value to string
  1960. *
  1961. * @param string|array $value The value to convert
  1962. * @return string
  1963. */
  1964. protected function flatten($value)
  1965. {
  1966. return is_array($value) ? implode(';', $value) : (string)$value;
  1967. }
  1968. /**
  1969. * Static method to fast create an instance of \Cake\Mailer\Email
  1970. *
  1971. * @param string|array|null $to Address to send (see Cake\Mailer\Email::to()). If null, will try to use 'to' from transport config
  1972. * @param string|null $subject String of subject or null to use 'subject' from transport config
  1973. * @param string|array|null $message String with message or array with variables to be used in render
  1974. * @param string|array $transportConfig String to use config from EmailConfig or array with configs
  1975. * @param bool $send Send the email or just return the instance pre-configured
  1976. * @return static Instance of Cake\Mailer\Email
  1977. * @throws \InvalidArgumentException
  1978. */
  1979. public static function deliver($to = null, $subject = null, $message = null, $transportConfig = 'default', $send = true)
  1980. {
  1981. $class = __CLASS__;
  1982. if (is_array($transportConfig) && !isset($transportConfig['transport'])) {
  1983. $transportConfig['transport'] = 'default';
  1984. }
  1985. /* @var \Cake\Mailer\Email $instance */
  1986. $instance = new $class($transportConfig);
  1987. if ($to !== null) {
  1988. $instance->setTo($to);
  1989. }
  1990. if ($subject !== null) {
  1991. $instance->setSubject($subject);
  1992. }
  1993. if (is_array($message)) {
  1994. $instance->setViewVars($message);
  1995. $message = null;
  1996. } elseif ($message === null && array_key_exists('message', $config = $instance->getProfile())) {
  1997. $message = $config['message'];
  1998. }
  1999. if ($send === true) {
  2000. $instance->send($message);
  2001. }
  2002. return $instance;
  2003. }
  2004. /**
  2005. * Apply the config to an instance
  2006. *
  2007. * @param string|array $config Configuration options.
  2008. * @return void
  2009. * @throws \InvalidArgumentException When using a configuration that doesn't exist.
  2010. */
  2011. protected function _applyConfig($config)
  2012. {
  2013. if (is_string($config)) {
  2014. $name = $config;
  2015. $config = static::getConfig($name);
  2016. if (empty($config)) {
  2017. throw new InvalidArgumentException(sprintf('Unknown email configuration "%s".', $name));
  2018. }
  2019. unset($name);
  2020. }
  2021. $this->_profile = array_merge($this->_profile, $config);
  2022. $simpleMethods = [
  2023. 'from', 'sender', 'to', 'replyTo', 'readReceipt', 'returnPath',
  2024. 'cc', 'bcc', 'messageId', 'domain', 'subject', 'attachments',
  2025. 'transport', 'emailFormat', 'emailPattern', 'charset', 'headerCharset'
  2026. ];
  2027. foreach ($simpleMethods as $method) {
  2028. if (isset($config[$method])) {
  2029. $this->{'set' . ucfirst($method)}($config[$method]);
  2030. }
  2031. }
  2032. if (empty($this->headerCharset)) {
  2033. $this->headerCharset = $this->charset;
  2034. }
  2035. if (isset($config['headers'])) {
  2036. $this->setHeaders($config['headers']);
  2037. }
  2038. $viewBuilderMethods = [
  2039. 'template', 'layout', 'theme'
  2040. ];
  2041. foreach ($viewBuilderMethods as $method) {
  2042. if (array_key_exists($method, $config)) {
  2043. $this->viewBuilder()->{'set' . ucfirst($method)}($config[$method]);
  2044. }
  2045. }
  2046. if (array_key_exists('helpers', $config)) {
  2047. $this->viewBuilder()->setHelpers($config['helpers'], false);
  2048. }
  2049. if (array_key_exists('viewRender', $config)) {
  2050. $this->viewBuilder()->setClassName($config['viewRender']);
  2051. }
  2052. if (array_key_exists('viewVars', $config)) {
  2053. $this->set($config['viewVars']);
  2054. }
  2055. }
  2056. /**
  2057. * Reset all the internal variables to be able to send out a new email.
  2058. *
  2059. * @return $this
  2060. */
  2061. public function reset()
  2062. {
  2063. $this->_to = [];
  2064. $this->_from = [];
  2065. $this->_sender = [];
  2066. $this->_replyTo = [];
  2067. $this->_readReceipt = [];
  2068. $this->_returnPath = [];
  2069. $this->_cc = [];
  2070. $this->_bcc = [];
  2071. $this->_messageId = true;
  2072. $this->_subject = '';
  2073. $this->_headers = [];
  2074. $this->_textMessage = '';
  2075. $this->_htmlMessage = '';
  2076. $this->_message = [];
  2077. $this->_emailFormat = 'text';
  2078. $this->_transport = null;
  2079. $this->_priority = null;
  2080. $this->charset = 'utf-8';
  2081. $this->headerCharset = null;
  2082. $this->transferEncoding = null;
  2083. $this->_attachments = [];
  2084. $this->_profile = [];
  2085. $this->_emailPattern = self::EMAIL_PATTERN;
  2086. $this->viewBuilder()->setLayout('default');
  2087. $this->viewBuilder()->setTemplate('');
  2088. $this->viewBuilder()->setClassName('Cake\View\View');
  2089. $this->viewVars = [];
  2090. $this->viewBuilder()->setTheme(false);
  2091. $this->viewBuilder()->setHelpers(['Html'], false);
  2092. return $this;
  2093. }
  2094. /**
  2095. * Encode the specified string using the current charset
  2096. *
  2097. * @param string $text String to encode
  2098. * @return string Encoded string
  2099. */
  2100. protected function _encode($text)
  2101. {
  2102. $restore = mb_internal_encoding();
  2103. mb_internal_encoding($this->_appCharset);
  2104. if (empty($this->headerCharset)) {
  2105. $this->headerCharset = $this->charset;
  2106. }
  2107. $return = mb_encode_mimeheader($text, $this->headerCharset, 'B');
  2108. mb_internal_encoding($restore);
  2109. return $return;
  2110. }
  2111. /**
  2112. * Decode the specified string
  2113. *
  2114. * @param string $text String to decode
  2115. * @return string Decoded string
  2116. */
  2117. protected function _decode($text)
  2118. {
  2119. $restore = mb_internal_encoding();
  2120. mb_internal_encoding($this->_appCharset);
  2121. $return = mb_decode_mimeheader($text);
  2122. mb_internal_encoding($restore);
  2123. return $return;
  2124. }
  2125. /**
  2126. * Translates a string for one charset to another if the App.encoding value
  2127. * differs and the mb_convert_encoding function exists
  2128. *
  2129. * @param string $text The text to be converted
  2130. * @param string $charset the target encoding
  2131. * @return string
  2132. */
  2133. protected function _encodeString($text, $charset)
  2134. {
  2135. if ($this->_appCharset === $charset) {
  2136. return $text;
  2137. }
  2138. return mb_convert_encoding($text, $charset, $this->_appCharset);
  2139. }
  2140. /**
  2141. * Wrap the message to follow the RFC 2822 - 2.1.1
  2142. *
  2143. * @param string $message Message to wrap
  2144. * @param int $wrapLength The line length
  2145. * @return array Wrapped message
  2146. */
  2147. protected function _wrap($message, $wrapLength = Email::LINE_LENGTH_MUST)
  2148. {
  2149. if (strlen($message) === 0) {
  2150. return [''];
  2151. }
  2152. $message = str_replace(["\r\n", "\r"], "\n", $message);
  2153. $lines = explode("\n", $message);
  2154. $formatted = [];
  2155. $cut = ($wrapLength == Email::LINE_LENGTH_MUST);
  2156. foreach ($lines as $line) {
  2157. if (empty($line) && $line !== '0') {
  2158. $formatted[] = '';
  2159. continue;
  2160. }
  2161. if (strlen($line) < $wrapLength) {
  2162. $formatted[] = $line;
  2163. continue;
  2164. }
  2165. if (!preg_match('/<[a-z]+.*>/i', $line)) {
  2166. $formatted = array_merge(
  2167. $formatted,
  2168. explode("\n", wordwrap($line, $wrapLength, "\n", $cut))
  2169. );
  2170. continue;
  2171. }
  2172. $tagOpen = false;
  2173. $tmpLine = $tag = '';
  2174. $tmpLineLength = 0;
  2175. for ($i = 0, $count = strlen($line); $i < $count; $i++) {
  2176. $char = $line[$i];
  2177. if ($tagOpen) {
  2178. $tag .= $char;
  2179. if ($char === '>') {
  2180. $tagLength = strlen($tag);
  2181. if ($tagLength + $tmpLineLength < $wrapLength) {
  2182. $tmpLine .= $tag;
  2183. $tmpLineLength += $tagLength;
  2184. } else {
  2185. if ($tmpLineLength > 0) {
  2186. $formatted = array_merge(
  2187. $formatted,
  2188. explode("\n", wordwrap(trim($tmpLine), $wrapLength, "\n", $cut))
  2189. );
  2190. $tmpLine = '';
  2191. $tmpLineLength = 0;
  2192. }
  2193. if ($tagLength > $wrapLength) {
  2194. $formatted[] = $tag;
  2195. } else {
  2196. $tmpLine = $tag;
  2197. $tmpLineLength = $tagLength;
  2198. }
  2199. }
  2200. $tag = '';
  2201. $tagOpen = false;
  2202. }
  2203. continue;
  2204. }
  2205. if ($char === '<') {
  2206. $tagOpen = true;
  2207. $tag = '<';
  2208. continue;
  2209. }
  2210. if ($char === ' ' && $tmpLineLength >= $wrapLength) {
  2211. $formatted[] = $tmpLine;
  2212. $tmpLineLength = 0;
  2213. continue;
  2214. }
  2215. $tmpLine .= $char;
  2216. $tmpLineLength++;
  2217. if ($tmpLineLength === $wrapLength) {
  2218. $nextChar = $line[$i + 1];
  2219. if ($nextChar === ' ' || $nextChar === '<') {
  2220. $formatted[] = trim($tmpLine);
  2221. $tmpLine = '';
  2222. $tmpLineLength = 0;
  2223. if ($nextChar === ' ') {
  2224. $i++;
  2225. }
  2226. } else {
  2227. $lastSpace = strrpos($tmpLine, ' ');
  2228. if ($lastSpace === false) {
  2229. continue;
  2230. }
  2231. $formatted[] = trim(substr($tmpLine, 0, $lastSpace));
  2232. $tmpLine = substr($tmpLine, $lastSpace + 1);
  2233. $tmpLineLength = strlen($tmpLine);
  2234. }
  2235. }
  2236. }
  2237. if (!empty($tmpLine)) {
  2238. $formatted[] = $tmpLine;
  2239. }
  2240. }
  2241. $formatted[] = '';
  2242. return $formatted;
  2243. }
  2244. /**
  2245. * Create unique boundary identifier
  2246. *
  2247. * @return void
  2248. */
  2249. protected function _createBoundary()
  2250. {
  2251. if ($this->_attachments || $this->_emailFormat === 'both') {
  2252. $this->_boundary = md5(Security::randomBytes(16));
  2253. }
  2254. }
  2255. /**
  2256. * Attach non-embedded files by adding file contents inside boundaries.
  2257. *
  2258. * @param string|null $boundary Boundary to use. If null, will default to $this->_boundary
  2259. * @return array An array of lines to add to the message
  2260. */
  2261. protected function _attachFiles($boundary = null)
  2262. {
  2263. if ($boundary === null) {
  2264. $boundary = $this->_boundary;
  2265. }
  2266. $msg = [];
  2267. foreach ($this->_attachments as $filename => $fileInfo) {
  2268. if (!empty($fileInfo['contentId'])) {
  2269. continue;
  2270. }
  2271. $data = isset($fileInfo['data']) ? $fileInfo['data'] : $this->_readFile($fileInfo['file']);
  2272. $hasDisposition = (
  2273. !isset($fileInfo['contentDisposition']) ||
  2274. $fileInfo['contentDisposition']
  2275. );
  2276. $part = new FormDataPart(false, $data, false);
  2277. if ($hasDisposition) {
  2278. $part->disposition('attachment');
  2279. $part->filename($filename);
  2280. }
  2281. $part->transferEncoding('base64');
  2282. $part->type($fileInfo['mimetype']);
  2283. $msg[] = '--' . $boundary;
  2284. $msg[] = (string)$part;
  2285. $msg[] = '';
  2286. }
  2287. return $msg;
  2288. }
  2289. /**
  2290. * Read the file contents and return a base64 version of the file contents.
  2291. *
  2292. * @param string $path The absolute path to the file to read.
  2293. * @return string File contents in base64 encoding
  2294. */
  2295. protected function _readFile($path)
  2296. {
  2297. $File = new File($path);
  2298. return chunk_split(base64_encode($File->read()));
  2299. }
  2300. /**
  2301. * Attach inline/embedded files to the message.
  2302. *
  2303. * @param string|null $boundary Boundary to use. If null, will default to $this->_boundary
  2304. * @return array An array of lines to add to the message
  2305. */
  2306. protected function _attachInlineFiles($boundary = null)
  2307. {
  2308. if ($boundary === null) {
  2309. $boundary = $this->_boundary;
  2310. }
  2311. $msg = [];
  2312. foreach ($this->_attachments as $filename => $fileInfo) {
  2313. if (empty($fileInfo['contentId'])) {
  2314. continue;
  2315. }
  2316. $data = isset($fileInfo['data']) ? $fileInfo['data'] : $this->_readFile($fileInfo['file']);
  2317. $msg[] = '--' . $boundary;
  2318. $part = new FormDataPart(false, $data, 'inline');
  2319. $part->type($fileInfo['mimetype']);
  2320. $part->transferEncoding('base64');
  2321. $part->contentId($fileInfo['contentId']);
  2322. $part->filename($filename);
  2323. $msg[] = (string)$part;
  2324. $msg[] = '';
  2325. }
  2326. return $msg;
  2327. }
  2328. /**
  2329. * Render the body of the email.
  2330. *
  2331. * @param array $content Content to render
  2332. * @return array Email body ready to be sent
  2333. */
  2334. protected function _render($content)
  2335. {
  2336. $this->_textMessage = $this->_htmlMessage = '';
  2337. $content = implode("\n", $content);
  2338. $rendered = $this->_renderTemplates($content);
  2339. $this->_createBoundary();
  2340. $msg = [];
  2341. $contentIds = array_filter((array)Hash::extract($this->_attachments, '{s}.contentId'));
  2342. $hasInlineAttachments = count($contentIds) > 0;
  2343. $hasAttachments = !empty($this->_attachments);
  2344. $hasMultipleTypes = count($rendered) > 1;
  2345. $multiPart = ($hasAttachments || $hasMultipleTypes);
  2346. $boundary = $relBoundary = $textBoundary = $this->_boundary;
  2347. if ($hasInlineAttachments) {
  2348. $msg[] = '--' . $boundary;
  2349. $msg[] = 'Content-Type: multipart/related; boundary="rel-' . $boundary . '"';
  2350. $msg[] = '';
  2351. $relBoundary = $textBoundary = 'rel-' . $boundary;
  2352. }
  2353. if ($hasMultipleTypes && $hasAttachments) {
  2354. $msg[] = '--' . $relBoundary;
  2355. $msg[] = 'Content-Type: multipart/alternative; boundary="alt-' . $boundary . '"';
  2356. $msg[] = '';
  2357. $textBoundary = 'alt-' . $boundary;
  2358. }
  2359. if (isset($rendered['text'])) {
  2360. if ($multiPart) {
  2361. $msg[] = '--' . $textBoundary;
  2362. $msg[] = 'Content-Type: text/plain; charset=' . $this->_getContentTypeCharset();
  2363. $msg[] = 'Content-Transfer-Encoding: ' . $this->_getContentTransferEncoding();
  2364. $msg[] = '';
  2365. }
  2366. $this->_textMessage = $rendered['text'];
  2367. $content = explode("\n", $this->_textMessage);
  2368. $msg = array_merge($msg, $content);
  2369. $msg[] = '';
  2370. }
  2371. if (isset($rendered['html'])) {
  2372. if ($multiPart) {
  2373. $msg[] = '--' . $textBoundary;
  2374. $msg[] = 'Content-Type: text/html; charset=' . $this->_getContentTypeCharset();
  2375. $msg[] = 'Content-Transfer-Encoding: ' . $this->_getContentTransferEncoding();
  2376. $msg[] = '';
  2377. }
  2378. $this->_htmlMessage = $rendered['html'];
  2379. $content = explode("\n", $this->_htmlMessage);
  2380. $msg = array_merge($msg, $content);
  2381. $msg[] = '';
  2382. }
  2383. if ($textBoundary !== $relBoundary) {
  2384. $msg[] = '--' . $textBoundary . '--';
  2385. $msg[] = '';
  2386. }
  2387. if ($hasInlineAttachments) {
  2388. $attachments = $this->_attachInlineFiles($relBoundary);
  2389. $msg = array_merge($msg, $attachments);
  2390. $msg[] = '';
  2391. $msg[] = '--' . $relBoundary . '--';
  2392. $msg[] = '';
  2393. }
  2394. if ($hasAttachments) {
  2395. $attachments = $this->_attachFiles($boundary);
  2396. $msg = array_merge($msg, $attachments);
  2397. }
  2398. if ($hasAttachments || $hasMultipleTypes) {
  2399. $msg[] = '';
  2400. $msg[] = '--' . $boundary . '--';
  2401. $msg[] = '';
  2402. }
  2403. return $msg;
  2404. }
  2405. /**
  2406. * Gets the text body types that are in this email message
  2407. *
  2408. * @return array Array of types. Valid types are 'text' and 'html'
  2409. */
  2410. protected function _getTypes()
  2411. {
  2412. $types = [$this->_emailFormat];
  2413. if ($this->_emailFormat === 'both') {
  2414. $types = ['html', 'text'];
  2415. }
  2416. return $types;
  2417. }
  2418. /**
  2419. * Build and set all the view properties needed to render the templated emails.
  2420. * If there is no template set, the $content will be returned in a hash
  2421. * of the text content types for the email.
  2422. *
  2423. * @param string $content The content passed in from send() in most cases.
  2424. * @return array The rendered content with html and text keys.
  2425. */
  2426. protected function _renderTemplates($content)
  2427. {
  2428. $types = $this->_getTypes();
  2429. $rendered = [];
  2430. $template = $this->viewBuilder()->getTemplate();
  2431. if (empty($template)) {
  2432. foreach ($types as $type) {
  2433. $rendered[$type] = $this->_encodeString($content, $this->charset);
  2434. }
  2435. return $rendered;
  2436. }
  2437. $View = $this->createView();
  2438. list($templatePlugin) = pluginSplit($View->getTemplate());
  2439. list($layoutPlugin) = pluginSplit($View->getLayout());
  2440. if ($templatePlugin) {
  2441. $View->plugin = $templatePlugin;
  2442. } elseif ($layoutPlugin) {
  2443. $View->plugin = $layoutPlugin;
  2444. }
  2445. if ($View->get('content') === null) {
  2446. $View->set('content', $content);
  2447. }
  2448. foreach ($types as $type) {
  2449. $View->hasRendered = false;
  2450. $View->setTemplatePath('Email' . DIRECTORY_SEPARATOR . $type);
  2451. $View->setLayoutPath('Email' . DIRECTORY_SEPARATOR . $type);
  2452. $render = $View->render();
  2453. $render = str_replace(["\r\n", "\r"], "\n", $render);
  2454. $rendered[$type] = $this->_encodeString($render, $this->charset);
  2455. }
  2456. foreach ($rendered as $type => $content) {
  2457. $rendered[$type] = $this->_wrap($content);
  2458. $rendered[$type] = implode("\n", $rendered[$type]);
  2459. $rendered[$type] = rtrim($rendered[$type], "\n");
  2460. }
  2461. return $rendered;
  2462. }
  2463. /**
  2464. * Return the Content-Transfer Encoding value based
  2465. * on the set transferEncoding or set charset.
  2466. *
  2467. * @return string
  2468. */
  2469. protected function _getContentTransferEncoding()
  2470. {
  2471. if ($this->transferEncoding) {
  2472. return $this->transferEncoding;
  2473. }
  2474. $charset = strtoupper($this->charset);
  2475. if (in_array($charset, $this->_charset8bit)) {
  2476. return '8bit';
  2477. }
  2478. return '7bit';
  2479. }
  2480. /**
  2481. * Return charset value for Content-Type.
  2482. *
  2483. * Checks fallback/compatibility types which include workarounds
  2484. * for legacy japanese character sets.
  2485. *
  2486. * @return string
  2487. */
  2488. protected function _getContentTypeCharset()
  2489. {
  2490. $charset = strtoupper($this->charset);
  2491. if (array_key_exists($charset, $this->_contentTypeCharset)) {
  2492. return strtoupper($this->_contentTypeCharset[$charset]);
  2493. }
  2494. return strtoupper($this->charset);
  2495. }
  2496. /**
  2497. * Serializes the email object to a value that can be natively serialized and re-used
  2498. * to clone this email instance.
  2499. *
  2500. * It has certain limitations for viewVars that are good to know:
  2501. *
  2502. * - ORM\Query executed and stored as resultset
  2503. * - SimpleXMLElements stored as associative array
  2504. * - Exceptions stored as strings
  2505. * - Resources, \Closure and \PDO are not supported.
  2506. *
  2507. * @return array Serializable array of configuration properties.
  2508. * @throws \Exception When a view var object can not be properly serialized.
  2509. */
  2510. public function jsonSerialize()
  2511. {
  2512. $properties = [
  2513. '_to', '_from', '_sender', '_replyTo', '_cc', '_bcc', '_subject',
  2514. '_returnPath', '_readReceipt', '_emailFormat', '_emailPattern', '_domain',
  2515. '_attachments', '_messageId', '_headers', '_appCharset', 'viewVars', 'charset', 'headerCharset'
  2516. ];
  2517. $array = ['viewConfig' => $this->viewBuilder()->jsonSerialize()];
  2518. foreach ($properties as $property) {
  2519. $array[$property] = $this->{$property};
  2520. }
  2521. array_walk($array['_attachments'], function (&$item, $key) {
  2522. if (!empty($item['file'])) {
  2523. $item['data'] = $this->_readFile($item['file']);
  2524. unset($item['file']);
  2525. }
  2526. });
  2527. array_walk_recursive($array['viewVars'], [$this, '_checkViewVars']);
  2528. return array_filter($array, function ($i) {
  2529. return !is_array($i) && strlen($i) || !empty($i);
  2530. });
  2531. }
  2532. /**
  2533. * Iterates through hash to clean up and normalize.
  2534. *
  2535. * @param mixed $item Reference to the view var value.
  2536. * @param string $key View var key.
  2537. * @return void
  2538. */
  2539. protected function _checkViewVars(&$item, $key)
  2540. {
  2541. if ($item instanceof Exception) {
  2542. $item = (string)$item;
  2543. }
  2544. if (is_resource($item) ||
  2545. $item instanceof Closure ||
  2546. $item instanceof PDO
  2547. ) {
  2548. throw new RuntimeException(sprintf(
  2549. 'Failed serializing the `%s` %s in the `%s` view var',
  2550. is_resource($item) ? get_resource_type($item) : get_class($item),
  2551. is_resource($item) ? 'resource' : 'object',
  2552. $key
  2553. ));
  2554. }
  2555. }
  2556. /**
  2557. * Configures an email instance object from serialized config.
  2558. *
  2559. * @param array $config Email configuration array.
  2560. * @return $this Configured email instance.
  2561. */
  2562. public function createFromArray($config)
  2563. {
  2564. if (isset($config['viewConfig'])) {
  2565. $this->viewBuilder()->createFromArray($config['viewConfig']);
  2566. unset($config['viewConfig']);
  2567. }
  2568. foreach ($config as $property => $value) {
  2569. $this->{$property} = $value;
  2570. }
  2571. return $this;
  2572. }
  2573. /**
  2574. * Serializes the Email object.
  2575. *
  2576. * @return string
  2577. */
  2578. public function serialize()
  2579. {
  2580. $array = $this->jsonSerialize();
  2581. array_walk_recursive($array, function (&$item, $key) {
  2582. if ($item instanceof SimpleXMLElement) {
  2583. $item = json_decode(json_encode((array)$item), true);
  2584. }
  2585. });
  2586. return serialize($array);
  2587. }
  2588. /**
  2589. * Unserializes the Email object.
  2590. *
  2591. * @param string $data Serialized string.
  2592. * @return static Configured email instance.
  2593. */
  2594. public function unserialize($data)
  2595. {
  2596. return $this->createFromArray(unserialize($data));
  2597. }
  2598. }