EmailTest.php 99 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE
  9. * Redistributions of files must retain the above copyright notice
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 2.0.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\Mailer;
  17. use Cake\Core\Configure;
  18. use Cake\Log\Log;
  19. use Cake\Mailer\Email;
  20. use Cake\Mailer\Mailer;
  21. use Cake\Mailer\Message;
  22. use Cake\Mailer\TransportFactory;
  23. use Cake\TestSuite\TestCase;
  24. use Cake\View\Exception\MissingTemplateException;
  25. use Exception;
  26. use SimpleXmlElement;
  27. use TestApp\Mailer\TestEmail;
  28. use function Cake\Core\env;
  29. /**
  30. * EmailTest class
  31. */
  32. class EmailTest extends TestCase
  33. {
  34. protected $fixtures = ['core.Users'];
  35. /**
  36. * @var \TestApp\Mailer\TestEmail
  37. */
  38. protected $Email;
  39. /**
  40. * @var array
  41. */
  42. protected $transports = [];
  43. /**
  44. * setUp
  45. */
  46. public function setUp(): void
  47. {
  48. parent::setUp();
  49. $this->Email = new TestEmail();
  50. $this->transports = [
  51. 'debug' => [
  52. 'className' => 'Debug',
  53. ],
  54. 'badClassName' => [
  55. 'className' => 'TestFalse',
  56. ],
  57. ];
  58. TransportFactory::setConfig($this->transports);
  59. }
  60. /**
  61. * tearDown method
  62. */
  63. public function tearDown(): void
  64. {
  65. parent::tearDown();
  66. Log::drop('email');
  67. Email::drop('default');
  68. Email::drop('test');
  69. TransportFactory::drop('debug');
  70. TransportFactory::drop('badClassName');
  71. TransportFactory::drop('test_smtp');
  72. }
  73. /**
  74. * testFrom method
  75. */
  76. public function testFrom(): void
  77. {
  78. $this->assertSame([], $this->Email->getFrom());
  79. $this->Email->setFrom('cake@cakephp.org');
  80. $expected = ['cake@cakephp.org' => 'cake@cakephp.org'];
  81. $this->assertSame($expected, $this->Email->getFrom());
  82. $this->Email->setFrom(['cake@cakephp.org']);
  83. $this->assertSame($expected, $this->Email->getFrom());
  84. $this->Email->setFrom('cake@cakephp.org', 'CakePHP');
  85. $expected = ['cake@cakephp.org' => 'CakePHP'];
  86. $this->assertSame($expected, $this->Email->getFrom());
  87. $result = $this->Email->setFrom(['cake@cakephp.org' => 'CakePHP']);
  88. $this->assertSame($expected, $this->Email->getFrom());
  89. $this->assertSame($this->Email, $result);
  90. $this->expectException(\InvalidArgumentException::class);
  91. $result = $this->Email->setFrom(['cake@cakephp.org' => 'CakePHP', 'fail@cakephp.org' => 'From can only be one address']);
  92. }
  93. /**
  94. * Test that from addresses using colons work.
  95. */
  96. public function testFromWithColonsAndQuotes(): void
  97. {
  98. $address = [
  99. 'info@example.com' => '70:20:00 " Forum',
  100. ];
  101. $this->Email->setFrom($address);
  102. $this->assertEquals($address, $this->Email->getFrom());
  103. $this->Email->setTo('info@example.com')
  104. ->setSubject('Test email')
  105. ->setTransport('debug');
  106. $result = $this->Email->send();
  107. $this->assertStringContainsString('From: "70:20:00 \" Forum" <info@example.com>', $result['headers']);
  108. }
  109. /**
  110. * testSender method
  111. */
  112. public function testSender(): void
  113. {
  114. $this->Email->reset();
  115. $this->assertSame([], $this->Email->getSender());
  116. $this->Email->setSender('cake@cakephp.org', 'Name');
  117. $expected = ['cake@cakephp.org' => 'Name'];
  118. $this->assertSame($expected, $this->Email->getSender());
  119. $headers = $this->Email->getHeaders(['from' => true, 'sender' => true]);
  120. $this->assertSame('', $headers['From']);
  121. $this->assertSame('Name <cake@cakephp.org>', $headers['Sender']);
  122. $this->Email->setFrom('cake@cakephp.org', 'CakePHP');
  123. $headers = $this->Email->getHeaders(['from' => true, 'sender' => true]);
  124. $this->assertSame('CakePHP <cake@cakephp.org>', $headers['From']);
  125. $this->assertSame('', $headers['Sender']);
  126. }
  127. /**
  128. * testTo method
  129. */
  130. public function testTo(): void
  131. {
  132. $this->assertSame([], $this->Email->getTo());
  133. $result = $this->Email->setTo('cake@cakephp.org');
  134. $expected = ['cake@cakephp.org' => 'cake@cakephp.org'];
  135. $this->assertSame($expected, $this->Email->getTo());
  136. $this->assertSame($this->Email, $result);
  137. $this->Email->setTo('cake@cakephp.org', 'CakePHP');
  138. $expected = ['cake@cakephp.org' => 'CakePHP'];
  139. $this->assertSame($expected, $this->Email->getTo());
  140. $list = [
  141. 'root@localhost' => 'root',
  142. 'bjørn@hammeröath.com' => 'Bjorn',
  143. 'cake.php@cakephp.org' => 'Cake PHP',
  144. 'cake-php@googlegroups.com' => 'Cake Groups',
  145. 'root@cakephp.org',
  146. ];
  147. $this->Email->setTo($list);
  148. $expected = [
  149. 'root@localhost' => 'root',
  150. 'bjørn@hammeröath.com' => 'Bjorn',
  151. 'cake.php@cakephp.org' => 'Cake PHP',
  152. 'cake-php@googlegroups.com' => 'Cake Groups',
  153. 'root@cakephp.org' => 'root@cakephp.org',
  154. ];
  155. $this->assertSame($expected, $this->Email->getTo());
  156. $this->Email->addTo('jrbasso@cakephp.org');
  157. $this->Email->addTo('mark_story@cakephp.org', 'Mark Story');
  158. $this->Email->addTo('foobar@ætdcadsl.dk');
  159. $result = $this->Email->addTo(['phpnut@cakephp.org' => 'PhpNut', 'jose_zap@cakephp.org']);
  160. $expected = [
  161. 'root@localhost' => 'root',
  162. 'bjørn@hammeröath.com' => 'Bjorn',
  163. 'cake.php@cakephp.org' => 'Cake PHP',
  164. 'cake-php@googlegroups.com' => 'Cake Groups',
  165. 'root@cakephp.org' => 'root@cakephp.org',
  166. 'jrbasso@cakephp.org' => 'jrbasso@cakephp.org',
  167. 'mark_story@cakephp.org' => 'Mark Story',
  168. 'foobar@ætdcadsl.dk' => 'foobar@ætdcadsl.dk',
  169. 'phpnut@cakephp.org' => 'PhpNut',
  170. 'jose_zap@cakephp.org' => 'jose_zap@cakephp.org',
  171. ];
  172. $this->assertSame($expected, $this->Email->getTo());
  173. $this->assertSame($this->Email, $result);
  174. }
  175. /**
  176. * test to address with _ in domain name
  177. */
  178. public function testToUnderscoreDomain(): void
  179. {
  180. $result = $this->Email->setTo('cake@cake_php.org');
  181. $expected = ['cake@cake_php.org' => 'cake@cake_php.org'];
  182. $this->assertSame($expected, $this->Email->getTo());
  183. $this->assertSame($this->Email, $result);
  184. }
  185. /**
  186. * Data provider function for testBuildInvalidData
  187. *
  188. * @return array
  189. */
  190. public static function invalidEmails(): array
  191. {
  192. return [
  193. [''],
  194. ['string'],
  195. ['<tag>'],
  196. [['ok@cakephp.org', '1.0', '', 'string']],
  197. ];
  198. }
  199. /**
  200. * testBuildInvalidData
  201. *
  202. * @dataProvider invalidEmails
  203. * @param array|string $value
  204. */
  205. public function testInvalidEmail($value): void
  206. {
  207. $this->expectException(\InvalidArgumentException::class);
  208. $this->Email->setTo($value);
  209. }
  210. /**
  211. * testBuildInvalidData
  212. *
  213. * @dataProvider invalidEmails
  214. * @param array|string $value
  215. */
  216. public function testInvalidEmailAdd($value): void
  217. {
  218. $this->expectException(\InvalidArgumentException::class);
  219. $this->Email->addTo($value);
  220. }
  221. /**
  222. * test emailPattern method
  223. */
  224. public function testEmailPattern(): void
  225. {
  226. $regex = '/.+@.+\..+/i';
  227. $this->assertSame($regex, $this->Email->setEmailPattern($regex)->getEmailPattern());
  228. }
  229. /**
  230. * Tests that it is possible to set email regex configuration to a CakeEmail object
  231. */
  232. public function testConfigEmailPattern(): void
  233. {
  234. $regex = '/.+@.+\..+/i';
  235. $email = new Email(['emailPattern' => $regex]);
  236. $this->assertSame($regex, $email->getEmailPattern());
  237. }
  238. /**
  239. * Tests that it is possible set custom email validation
  240. */
  241. public function testCustomEmailValidation(): void
  242. {
  243. $regex = '/^[\.a-z0-9!#$%&\'*+\/=?^_`{|}~-]+@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]{2,6}$/i';
  244. $this->Email->setEmailPattern($regex)->setTo('pass.@example.com');
  245. $this->assertSame([
  246. 'pass.@example.com' => 'pass.@example.com',
  247. ], $this->Email->getTo());
  248. $this->Email->addTo('pass..old.docomo@example.com');
  249. $this->assertSame([
  250. 'pass.@example.com' => 'pass.@example.com',
  251. 'pass..old.docomo@example.com' => 'pass..old.docomo@example.com',
  252. ], $this->Email->getTo());
  253. $this->Email->reset();
  254. $emails = [
  255. 'pass.@example.com',
  256. 'pass..old.docomo@example.com',
  257. ];
  258. $additionalEmails = [
  259. '.extend.@example.com',
  260. '.docomo@example.com',
  261. ];
  262. $this->Email->setEmailPattern($regex)->setTo($emails);
  263. $this->assertSame([
  264. 'pass.@example.com' => 'pass.@example.com',
  265. 'pass..old.docomo@example.com' => 'pass..old.docomo@example.com',
  266. ], $this->Email->getTo());
  267. $this->Email->addTo($additionalEmails);
  268. $this->assertSame([
  269. 'pass.@example.com' => 'pass.@example.com',
  270. 'pass..old.docomo@example.com' => 'pass..old.docomo@example.com',
  271. '.extend.@example.com' => '.extend.@example.com',
  272. '.docomo@example.com' => '.docomo@example.com',
  273. ], $this->Email->getTo());
  274. }
  275. /**
  276. * Tests not found transport class name exception
  277. */
  278. public function testClassNameException(): void
  279. {
  280. $this->expectException(\BadMethodCallException::class);
  281. $this->expectExceptionMessage('Mailer transport TestFalse is not available.');
  282. $email = new Email();
  283. $email->setTransport('badClassName');
  284. }
  285. /**
  286. * Tests that it is possible to unset the email pattern and make use of filter_var() instead.
  287. */
  288. public function testUnsetEmailPattern(): void
  289. {
  290. $this->expectException(\InvalidArgumentException::class);
  291. $this->expectExceptionMessage('Invalid email set for "to". You passed "fail.@example.com".');
  292. $email = new Email();
  293. $this->assertSame(Email::EMAIL_PATTERN, $email->getEmailPattern());
  294. $email->setEmailPattern(null);
  295. $this->assertNull($email->getEmailPattern());
  296. $email->setTo('pass@example.com');
  297. $email->setTo('fail.@example.com');
  298. }
  299. /**
  300. * Tests that passing an empty string throws an InvalidArgumentException.
  301. */
  302. public function testEmptyTo(): void
  303. {
  304. $this->expectException(\InvalidArgumentException::class);
  305. $this->expectExceptionMessage('The email set for "to" is empty.');
  306. $email = new Email();
  307. $email->setTo('');
  308. }
  309. /**
  310. * testFormatAddress method
  311. */
  312. public function testFormatAddress(): void
  313. {
  314. $result = $this->Email->getMessage()->fmtAddress(['cake@cakephp.org' => 'cake@cakephp.org']);
  315. $expected = ['cake@cakephp.org'];
  316. $this->assertSame($expected, $result);
  317. $result = $this->Email->getMessage()->fmtAddress([
  318. 'cake@cakephp.org' => 'cake@cakephp.org',
  319. 'php@cakephp.org' => 'php@cakephp.org',
  320. ]);
  321. $expected = ['cake@cakephp.org', 'php@cakephp.org'];
  322. $this->assertSame($expected, $result);
  323. $result = $this->Email->getMessage()->fmtAddress([
  324. 'cake@cakephp.org' => 'CakePHP',
  325. 'php@cakephp.org' => 'Cake',
  326. ]);
  327. $expected = ['CakePHP <cake@cakephp.org>', 'Cake <php@cakephp.org>'];
  328. $this->assertSame($expected, $result);
  329. $result = $this->Email->getMessage()->fmtAddress(['me@example.com' => 'Last, First']);
  330. $expected = ['"Last, First" <me@example.com>'];
  331. $this->assertSame($expected, $result);
  332. $result = $this->Email->getMessage()->fmtAddress(['me@example.com' => '"Last" First']);
  333. $expected = ['"\"Last\" First" <me@example.com>'];
  334. $this->assertSame($expected, $result);
  335. // See https://datatracker.ietf.org/doc/html/rfc5322#section-3.2.4
  336. $result = $this->Email->getMessage()->fmtAddress(['me@example.com' => 'Quotes: " Backslashes: \\']);
  337. $expected = ['"Quotes: \\" Backslashes: \\\\" <me@example.com>'];
  338. $this->assertSame($expected, $result);
  339. $result = $this->Email->getMessage()->fmtAddress(['me@example.com' => 'Last First']);
  340. $expected = ['Last First <me@example.com>'];
  341. $this->assertSame($expected, $result);
  342. $result = $this->Email->getMessage()->fmtAddress(['cake@cakephp.org' => 'ÄÖÜTest']);
  343. $expected = ['=?UTF-8?B?w4TDlsOcVGVzdA==?= <cake@cakephp.org>'];
  344. $this->assertSame($expected, $result);
  345. $result = $this->Email->getMessage()->fmtAddress(['cake@cakephp.org' => '日本語Test']);
  346. $expected = ['=?UTF-8?B?5pel5pys6KqeVGVzdA==?= <cake@cakephp.org>'];
  347. $this->assertSame($expected, $result);
  348. $result = $this->Email->getMessage()->fmtAddress(['cake@cakephp.org' => 'Test <test@test.local>, Über']);
  349. $expected = ['"Test <test@test.local>, =?UTF-8?B?w5xiZXI=?=" <cake@cakephp.org>'];
  350. $this->assertSame($expected, $result);
  351. }
  352. /**
  353. * testFormatAddressJapanese
  354. */
  355. public function testFormatAddressJapanese(): void
  356. {
  357. $this->Email->setHeaderCharset('ISO-2022-JP');
  358. $result = $this->Email->getMessage()->fmtAddress(['cake@cakephp.org' => '日本語Test']);
  359. $expected = ['=?ISO-2022-JP?B?GyRCRnxLXDhsGyhCVGVzdA==?= <cake@cakephp.org>'];
  360. $this->assertSame($expected, $result);
  361. $result = $this->Email->getMessage()->fmtAddress(['cake@cakephp.org' => '寿限無寿限無五劫の擦り切れ海砂利水魚の水行末雲来末風来末食う寝る処に住む処やぶら小路の藪柑子パイポパイポパイポのシューリンガンシューリンガンのグーリンダイグーリンダイのポンポコピーのポンポコナーの長久命の長助']);
  362. $expected = ["\"=?ISO-2022-JP?B?GyRCPHc4Qkw1PHc4Qkw1OF45ZSROOyQkakBaJGwzJDo9TXg/ZTV7GyhC?=\r\n" .
  363. " =?ISO-2022-JP?B?GyRCJE4/ZTlUS3YxQE1oS3ZJd01oS3Y/KSQmPzIkaz1oJEs9OyRgGyhC?=\r\n" .
  364. " =?ISO-2022-JP?B?GyRCPWgkZCRWJGk+Lk8pJE5pLjQ7O1IlUSUkJV0lUSUkJV0lUSUkGyhC?=\r\n" .
  365. " =?ISO-2022-JP?B?GyRCJV0kTiU3JWUhPCVqJXMlLCVzJTclZSE8JWolcyUsJXMkTiUwGyhC?=\r\n" .
  366. " =?ISO-2022-JP?B?GyRCITwlaiVzJUAlJCUwITwlaiVzJUAlJCROJV0lcyVdJTMlVCE8GyhC?=\r\n" .
  367. ' =?ISO-2022-JP?B?GyRCJE4lXSVzJV0lMyVKITwkTkQ5NVdMPyRORDk9dRsoQg==?=" <cake@cakephp.org>'];
  368. $this->assertSame($expected, $result);
  369. }
  370. /**
  371. * testAddresses method
  372. */
  373. public function testAddresses(): void
  374. {
  375. $this->Email->reset();
  376. $this->Email->setFrom('cake@cakephp.org', 'CakePHP');
  377. $this->Email->setReplyTo('replyto@cakephp.org', 'ReplyTo CakePHP');
  378. $this->Email->setReadReceipt('readreceipt@cakephp.org', 'ReadReceipt CakePHP');
  379. $this->Email->setReturnPath('returnpath@cakephp.org', 'ReturnPath CakePHP');
  380. $this->Email->setTo('to@cakephp.org', 'To, CakePHP');
  381. $this->Email->setCc('cc@cakephp.org', 'Cc CakePHP');
  382. $this->Email->setBcc('bcc@cakephp.org', 'Bcc CakePHP');
  383. $this->Email->addTo('to2@cakephp.org', 'To2 CakePHP');
  384. $this->Email->addCc('cc2@cakephp.org', 'Cc2 CakePHP');
  385. $this->Email->addBcc('bcc2@cakephp.org', 'Bcc2 CakePHP');
  386. $this->Email->addReplyTo('replyto2@cakephp.org', 'ReplyTo2 CakePHP');
  387. $this->assertSame($this->Email->getFrom(), ['cake@cakephp.org' => 'CakePHP']);
  388. $this->assertSame($this->Email->getReplyTo(), ['replyto@cakephp.org' => 'ReplyTo CakePHP', 'replyto2@cakephp.org' => 'ReplyTo2 CakePHP']);
  389. $this->assertSame($this->Email->getReadReceipt(), ['readreceipt@cakephp.org' => 'ReadReceipt CakePHP']);
  390. $this->assertSame($this->Email->getReturnPath(), ['returnpath@cakephp.org' => 'ReturnPath CakePHP']);
  391. $this->assertSame($this->Email->getTo(), ['to@cakephp.org' => 'To, CakePHP', 'to2@cakephp.org' => 'To2 CakePHP']);
  392. $this->assertSame($this->Email->getCc(), ['cc@cakephp.org' => 'Cc CakePHP', 'cc2@cakephp.org' => 'Cc2 CakePHP']);
  393. $this->assertSame($this->Email->getBcc(), ['bcc@cakephp.org' => 'Bcc CakePHP', 'bcc2@cakephp.org' => 'Bcc2 CakePHP']);
  394. $headers = $this->Email->getHeaders(array_fill_keys(['from', 'replyTo', 'readReceipt', 'returnPath', 'to', 'cc', 'bcc'], true));
  395. $this->assertSame($headers['From'], 'CakePHP <cake@cakephp.org>');
  396. $this->assertSame($headers['Reply-To'], 'ReplyTo CakePHP <replyto@cakephp.org>, ReplyTo2 CakePHP <replyto2@cakephp.org>');
  397. $this->assertSame($headers['Disposition-Notification-To'], 'ReadReceipt CakePHP <readreceipt@cakephp.org>');
  398. $this->assertSame($headers['Return-Path'], 'ReturnPath CakePHP <returnpath@cakephp.org>');
  399. $this->assertSame($headers['To'], '"To, CakePHP" <to@cakephp.org>, To2 CakePHP <to2@cakephp.org>');
  400. $this->assertSame($headers['Cc'], 'Cc CakePHP <cc@cakephp.org>, Cc2 CakePHP <cc2@cakephp.org>');
  401. $this->assertSame($headers['Bcc'], 'Bcc CakePHP <bcc@cakephp.org>, Bcc2 CakePHP <bcc2@cakephp.org>');
  402. $this->Email->setReplyTo(['replyto@cakephp.org' => 'ReplyTo CakePHP', 'replyto2@cakephp.org' => 'ReplyTo2 CakePHP']);
  403. $this->assertSame($this->Email->getReplyTo(), ['replyto@cakephp.org' => 'ReplyTo CakePHP', 'replyto2@cakephp.org' => 'ReplyTo2 CakePHP']);
  404. $headers = $this->Email->getHeaders(array_fill_keys(['replyTo'], true));
  405. $this->assertSame($headers['Reply-To'], 'ReplyTo CakePHP <replyto@cakephp.org>, ReplyTo2 CakePHP <replyto2@cakephp.org>');
  406. }
  407. /**
  408. * test reset addresses method
  409. */
  410. public function testResetAddresses(): void
  411. {
  412. $this->Email->reset();
  413. $this->Email
  414. ->setFrom('cake@cakephp.org', 'CakePHP')
  415. ->setReplyTo('replyto@cakephp.org', 'ReplyTo CakePHP')
  416. ->setReadReceipt('readreceipt@cakephp.org', 'ReadReceipt CakePHP')
  417. ->setReturnPath('returnpath@cakephp.org', 'ReturnPath CakePHP')
  418. ->setTo('to@cakephp.org', 'To, CakePHP')
  419. ->setCc('cc@cakephp.org', 'Cc CakePHP')
  420. ->setBcc('bcc@cakephp.org', 'Bcc CakePHP');
  421. $this->assertNotEmpty($this->Email->getFrom());
  422. $this->assertNotEmpty($this->Email->getReplyTo());
  423. $this->assertNotEmpty($this->Email->getReadReceipt());
  424. $this->assertNotEmpty($this->Email->getReturnPath());
  425. $this->assertNotEmpty($this->Email->getTo());
  426. $this->assertNotEmpty($this->Email->getCc());
  427. $this->assertNotEmpty($this->Email->getBcc());
  428. $this->Email
  429. ->setFrom([])
  430. ->setReplyTo([])
  431. ->setReadReceipt([])
  432. ->setReturnPath([])
  433. ->setTo([])
  434. ->setCc([])
  435. ->setBcc([]);
  436. $this->assertEmpty($this->Email->getFrom());
  437. $this->assertEmpty($this->Email->getReplyTo());
  438. $this->assertEmpty($this->Email->getReadReceipt());
  439. $this->assertEmpty($this->Email->getReturnPath());
  440. $this->assertEmpty($this->Email->getTo());
  441. $this->assertEmpty($this->Email->getCc());
  442. $this->assertEmpty($this->Email->getBcc());
  443. }
  444. /**
  445. * testMessageId method
  446. */
  447. public function testMessageId(): void
  448. {
  449. $this->Email->setMessageId(true);
  450. $result = $this->Email->getHeaders();
  451. $this->assertArrayHasKey('Message-ID', $result);
  452. $this->Email->setMessageId(false);
  453. $result = $this->Email->getHeaders();
  454. $this->assertArrayNotHasKey('Message-ID', $result);
  455. $result = $this->Email->setMessageId('<my-email@localhost>');
  456. $this->assertSame($this->Email, $result);
  457. $result = $this->Email->getHeaders();
  458. $this->assertSame('<my-email@localhost>', $result['Message-ID']);
  459. $result = $this->Email->getMessageId();
  460. $this->assertSame('<my-email@localhost>', $result);
  461. }
  462. public function testAutoMessageIdIsIdempotent(): void
  463. {
  464. $headers = $this->Email->getHeaders();
  465. $this->assertArrayHasKey('Message-ID', $headers);
  466. $regeneratedHeaders = $this->Email->getHeaders();
  467. $this->assertSame($headers['Message-ID'], $regeneratedHeaders['Message-ID']);
  468. }
  469. public function testPriority(): void
  470. {
  471. $this->Email->setPriority(4);
  472. $this->assertSame(4, $this->Email->getPriority());
  473. $result = $this->Email->getHeaders();
  474. $this->assertArrayHasKey('X-Priority', $result);
  475. }
  476. /**
  477. * testMessageIdInvalid method
  478. */
  479. public function testMessageIdInvalid(): void
  480. {
  481. $this->expectException(\InvalidArgumentException::class);
  482. $this->Email->setMessageId('my-email@localhost');
  483. }
  484. /**
  485. * testDomain method
  486. */
  487. public function testDomain(): void
  488. {
  489. $result = $this->Email->getDomain();
  490. $expected = env('HTTP_HOST') ? env('HTTP_HOST') : php_uname('n');
  491. $this->assertSame($expected, $result);
  492. $this->Email->setDomain('example.org');
  493. $result = $this->Email->getDomain();
  494. $expected = 'example.org';
  495. $this->assertSame($expected, $result);
  496. }
  497. /**
  498. * testMessageIdWithDomain method
  499. */
  500. public function testMessageIdWithDomain(): void
  501. {
  502. $this->Email->setDomain('example.org');
  503. $result = $this->Email->getHeaders();
  504. $expected = '@example.org>';
  505. $this->assertTextContains($expected, $result['Message-ID']);
  506. $_SERVER['HTTP_HOST'] = 'example.org';
  507. $result = $this->Email->getHeaders();
  508. $this->assertTextContains('example.org', $result['Message-ID']);
  509. $_SERVER['HTTP_HOST'] = 'example.org:81';
  510. $result = $this->Email->getHeaders();
  511. $this->assertTextNotContains(':81', $result['Message-ID']);
  512. }
  513. /**
  514. * testSubject method
  515. */
  516. public function testSubject(): void
  517. {
  518. $this->Email->setSubject('You have a new message.');
  519. $this->assertSame('You have a new message.', $this->Email->getSubject());
  520. $this->Email->setSubject('You have a new message, I think.');
  521. $this->assertSame($this->Email->getSubject(), 'You have a new message, I think.');
  522. $this->Email->setSubject('1');
  523. $this->assertSame('1', $this->Email->getSubject());
  524. $input = 'هذه رسالة بعنوان طويل مرسل للمستلم';
  525. $this->Email->setSubject($input);
  526. $expected = '=?UTF-8?B?2YfYsNmHINix2LPYp9mE2Kkg2KjYudmG2YjYp9mGINi32YjZitmEINmF2LE=?=' . "\r\n" . ' =?UTF-8?B?2LPZhCDZhNmE2YXYs9iq2YTZhQ==?=';
  527. $this->assertSame($expected, $this->Email->getSubject());
  528. $this->assertSame($input, $this->Email->getOriginalSubject());
  529. }
  530. /**
  531. * testSubjectJapanese
  532. */
  533. public function testSubjectJapanese(): void
  534. {
  535. mb_internal_encoding('UTF-8');
  536. $this->Email->setHeaderCharset('ISO-2022-JP');
  537. $this->Email->setSubject('日本語のSubjectにも対応するよ');
  538. $expected = '=?ISO-2022-JP?B?GyRCRnxLXDhsJE4bKEJTdWJqZWN0GyRCJEskYkJQMX4kOSRrJGgbKEI=?=';
  539. $this->assertSame($expected, $this->Email->getSubject());
  540. $this->Email->setSubject('長い長い長いSubjectの場合はfoldingするのが正しいんだけどいったいどうなるんだろう?');
  541. $expected = "=?ISO-2022-JP?B?GyRCRDkkJEQ5JCREOSQkGyhCU3ViamVjdBskQiROPmw5ZyRPGyhCZm9s?=\r\n" .
  542. " =?ISO-2022-JP?B?ZGluZxskQiQ5JGskTiQsQDUkNyQkJHMkQCQxJEkkJCRDJD8kJCRJGyhC?=\r\n" .
  543. ' =?ISO-2022-JP?B?GyRCJCYkSiRrJHMkQCRtJCYhKRsoQg==?=';
  544. $this->assertSame($expected, $this->Email->getSubject());
  545. }
  546. /**
  547. * testHeaders method
  548. */
  549. public function testHeaders(): void
  550. {
  551. $this->Email->setMessageId(false);
  552. $this->Email->setHeaders(['X-Something' => 'nice']);
  553. $expected = [
  554. 'X-Something' => 'nice',
  555. 'Date' => date(DATE_RFC2822),
  556. 'MIME-Version' => '1.0',
  557. 'Content-Type' => 'text/plain; charset=UTF-8',
  558. 'Content-Transfer-Encoding' => '8bit',
  559. ];
  560. $this->assertSame($expected, $this->Email->getHeaders());
  561. $this->Email->addHeaders(['X-Something' => 'very nice', 'X-Other' => 'cool']);
  562. $expected = [
  563. 'X-Something' => 'very nice',
  564. 'X-Other' => 'cool',
  565. 'Date' => date(DATE_RFC2822),
  566. 'MIME-Version' => '1.0',
  567. 'Content-Type' => 'text/plain; charset=UTF-8',
  568. 'Content-Transfer-Encoding' => '8bit',
  569. ];
  570. $this->assertSame($expected, $this->Email->getHeaders());
  571. $this->Email->setFrom('cake@cakephp.org');
  572. $this->assertSame($expected, $this->Email->getHeaders());
  573. $expected = [
  574. 'From' => 'cake@cakephp.org',
  575. 'X-Something' => 'very nice',
  576. 'X-Other' => 'cool',
  577. 'Date' => date(DATE_RFC2822),
  578. 'MIME-Version' => '1.0',
  579. 'Content-Type' => 'text/plain; charset=UTF-8',
  580. 'Content-Transfer-Encoding' => '8bit',
  581. ];
  582. $this->assertSame($expected, $this->Email->getHeaders(['from' => true]));
  583. $this->Email->setFrom('cake@cakephp.org', 'CakePHP');
  584. $expected['From'] = 'CakePHP <cake@cakephp.org>';
  585. $this->assertSame($expected, $this->Email->getHeaders(['from' => true]));
  586. $this->Email->setTo(['cake@cakephp.org', 'php@cakephp.org' => 'CakePHP']);
  587. $expected = [
  588. 'From' => 'CakePHP <cake@cakephp.org>',
  589. 'To' => 'cake@cakephp.org, CakePHP <php@cakephp.org>',
  590. 'X-Something' => 'very nice',
  591. 'X-Other' => 'cool',
  592. 'Date' => date(DATE_RFC2822),
  593. 'MIME-Version' => '1.0',
  594. 'Content-Type' => 'text/plain; charset=UTF-8',
  595. 'Content-Transfer-Encoding' => '8bit',
  596. ];
  597. $this->assertSame($expected, $this->Email->getHeaders(['from' => true, 'to' => true]));
  598. $this->Email->setCharset('ISO-2022-JP');
  599. $expected = [
  600. 'From' => 'CakePHP <cake@cakephp.org>',
  601. 'To' => 'cake@cakephp.org, CakePHP <php@cakephp.org>',
  602. 'X-Something' => 'very nice',
  603. 'X-Other' => 'cool',
  604. 'Date' => date(DATE_RFC2822),
  605. 'MIME-Version' => '1.0',
  606. 'Content-Type' => 'text/plain; charset=ISO-2022-JP',
  607. 'Content-Transfer-Encoding' => '7bit',
  608. ];
  609. $this->assertSame($expected, $this->Email->getHeaders(['from' => true, 'to' => true]));
  610. $result = $this->Email->setHeaders([]);
  611. $this->assertInstanceOf('Cake\Mailer\Email', $result);
  612. $this->Email->setHeaders(['o:tag' => ['foo']]);
  613. $this->Email->addHeaders(['o:tag' => ['bar']]);
  614. $result = $this->Email->getHeaders();
  615. $this->assertEquals(['foo', 'bar'], $result['o:tag']);
  616. }
  617. /**
  618. * testTemplate method
  619. */
  620. public function testTemplate(): void
  621. {
  622. $this->Email->viewBuilder()->setTemplate('template');
  623. $this->assertSame('template', $this->Email->viewBuilder()->getTemplate());
  624. }
  625. /**
  626. * testLayout method
  627. */
  628. public function testLayout(): void
  629. {
  630. $this->Email->viewBuilder()->setLayout('layout');
  631. $this->assertSame('layout', $this->Email->viewBuilder()->getLayout());
  632. }
  633. /**
  634. * testTheme method
  635. */
  636. public function testTheme(): void
  637. {
  638. $this->assertNull($this->Email->viewBuilder()->getTheme());
  639. $this->Email->viewBuilder()->setTheme('default');
  640. $expected = 'default';
  641. $this->assertSame($expected, $this->Email->viewBuilder()->getTheme());
  642. }
  643. /**
  644. * testViewVars method
  645. */
  646. public function testViewVars(): void
  647. {
  648. $this->assertSame([], $this->Email->getViewVars());
  649. $this->Email->setViewVars(['value' => 12345]);
  650. $this->assertSame(['value' => 12345], $this->Email->getViewVars());
  651. $this->Email->setViewVars(['name' => 'CakePHP']);
  652. $this->assertEquals(['value' => 12345, 'name' => 'CakePHP'], $this->Email->getViewVars());
  653. $this->Email->setViewVars(['value' => 4567]);
  654. $this->assertSame(['value' => 4567, 'name' => 'CakePHP'], $this->Email->getViewVars());
  655. }
  656. /**
  657. * testAttachments method
  658. */
  659. public function testSetAttachments(): void
  660. {
  661. $this->Email->setAttachments([CAKE . 'basics.php']);
  662. $expected = [
  663. 'basics.php' => [
  664. 'file' => CAKE . 'basics.php',
  665. 'mimetype' => 'text/x-php',
  666. ],
  667. ];
  668. $this->assertSame($expected, $this->Email->getAttachments());
  669. $this->Email->setAttachments([]);
  670. $this->assertSame([], $this->Email->getAttachments());
  671. $this->Email->setAttachments([
  672. ['file' => CAKE . 'basics.php', 'mimetype' => 'text/plain'],
  673. ]);
  674. $this->Email->addAttachments([CORE_PATH . 'config' . DS . 'bootstrap.php']);
  675. $this->Email->addAttachments([CORE_PATH . 'config' . DS . 'bootstrap.php']);
  676. $this->Email->addAttachments([
  677. 'other.txt' => CORE_PATH . 'config' . DS . 'bootstrap.php',
  678. 'license' => CORE_PATH . 'LICENSE',
  679. ]);
  680. $expected = [
  681. 'basics.php' => ['file' => CAKE . 'basics.php', 'mimetype' => 'text/plain'],
  682. 'bootstrap.php' => ['file' => CORE_PATH . 'config' . DS . 'bootstrap.php', 'mimetype' => 'text/x-php'],
  683. 'other.txt' => ['file' => CORE_PATH . 'config' . DS . 'bootstrap.php', 'mimetype' => 'text/x-php'],
  684. 'license' => ['file' => CORE_PATH . 'LICENSE', 'mimetype' => 'text/plain'],
  685. ];
  686. $this->assertSame($expected, $this->Email->getAttachments());
  687. $this->expectException(\InvalidArgumentException::class);
  688. $this->Email->setAttachments([['nofile' => CAKE . 'basics.php', 'mimetype' => 'text/plain']]);
  689. }
  690. /**
  691. * Test send() with no template and data string attachment and no mimetype
  692. */
  693. public function testSetAttachmentDataNoMimetype(): void
  694. {
  695. $this->Email->setAttachments(['cake.icon.gif' => [
  696. 'data' => 'test',
  697. ]]);
  698. $result = $this->Email->getAttachments();
  699. $expected = [
  700. 'cake.icon.gif' => [
  701. 'data' => base64_encode('test') . "\r\n",
  702. 'mimetype' => 'application/octet-stream',
  703. ],
  704. ];
  705. $this->assertSame($expected, $this->Email->getAttachments());
  706. }
  707. /**
  708. * testTransport method
  709. */
  710. public function testTransport(): void
  711. {
  712. $result = $this->Email->setTransport('debug');
  713. $this->assertSame($this->Email, $result);
  714. $result = $this->Email->getTransport();
  715. $this->assertInstanceOf('Cake\Mailer\Transport\DebugTransport', $result);
  716. $instance = $this->getMockBuilder('Cake\Mailer\Transport\DebugTransport')->getMock();
  717. $this->Email->setTransport($instance);
  718. $this->assertSame($instance, $this->Email->getTransport());
  719. }
  720. /**
  721. * Test that using unknown transports fails.
  722. */
  723. public function testTransportInvalid(): void
  724. {
  725. $this->expectException(\InvalidArgumentException::class);
  726. $this->expectExceptionMessage('The "Invalid" transport configuration does not exist');
  727. $this->Email->setTransport('Invalid');
  728. }
  729. /**
  730. * Test that using classes with no send method fails.
  731. */
  732. public function testTransportInstanceInvalid(): void
  733. {
  734. $this->expectException(\LogicException::class);
  735. $this->Email->setTransport(new \stdClass());
  736. }
  737. /**
  738. * Test that using unknown transports fails.
  739. */
  740. public function testTransportTypeInvalid(): void
  741. {
  742. $this->expectException(\InvalidArgumentException::class);
  743. $this->expectExceptionMessage('The value passed for the "$name" argument must be either a string, or an object, integer given.');
  744. $this->Email->setTransport(123);
  745. }
  746. /**
  747. * Test reading/writing configuration profiles.
  748. */
  749. public function testConfig(): void
  750. {
  751. $settings = [
  752. 'to' => 'mark@example.com',
  753. 'from' => 'noreply@example.com',
  754. ];
  755. Email::setConfig('test', $settings);
  756. $this->assertEquals($settings, Email::getConfig('test'), 'Should be the same.');
  757. $email = new Email('test');
  758. $this->assertContains($settings['to'], $email->getTo());
  759. }
  760. /**
  761. * Test that exceptions are raised on duplicate config set.
  762. */
  763. public function testConfigErrorOnDuplicate(): void
  764. {
  765. $this->expectException(\BadMethodCallException::class);
  766. $settings = [
  767. 'to' => 'mark@example.com',
  768. 'from' => 'noreply@example.com',
  769. ];
  770. Email::setConfig('test', $settings);
  771. Email::setConfig('test', $settings);
  772. }
  773. /**
  774. * test profile method
  775. */
  776. public function testProfile(): void
  777. {
  778. $config = ['test' => 'ok', 'test2' => true];
  779. $this->Email->setProfile($config);
  780. $this->assertSame($this->Email->getProfile(), $config);
  781. $config = ['test' => 'test@example.com'];
  782. $this->Email->setProfile($config);
  783. $expected = ['test' => 'test@example.com', 'test2' => true];
  784. $this->assertSame($expected, $this->Email->getProfile());
  785. }
  786. /**
  787. * test that default profile is used by constructor if available.
  788. */
  789. public function testDefaultProfile(): void
  790. {
  791. $config = ['test' => 'ok', 'test2' => true];
  792. Configure::write('Email.default', $config);
  793. Email::setConfig(Configure::consume('Email'));
  794. $Email = new Email();
  795. $this->assertSame($Email->getProfile(), $config);
  796. Configure::delete('Email');
  797. Email::drop('default');
  798. }
  799. /**
  800. * Test that using an invalid profile fails.
  801. */
  802. public function testProfileInvalid(): void
  803. {
  804. $this->expectException(\InvalidArgumentException::class);
  805. $this->expectExceptionMessage('Unknown email configuration "derp".');
  806. $email = new Email();
  807. $email->setProfile('derp');
  808. }
  809. /**
  810. * testConfigString method
  811. */
  812. public function testUseConfigString(): void
  813. {
  814. $config = [
  815. 'from' => ['some@example.com' => 'My website'],
  816. 'to' => ['test@example.com' => 'Testname'],
  817. 'subject' => 'Test mail subject',
  818. 'transport' => 'debug',
  819. 'theme' => 'TestTheme',
  820. 'helpers' => ['Html', 'Form'],
  821. ];
  822. Email::setConfig('test', $config);
  823. $this->Email->setProfile('test');
  824. $result = $this->Email->getTo();
  825. $this->assertEquals($config['to'], $result);
  826. $result = $this->Email->getFrom();
  827. $this->assertEquals($config['from'], $result);
  828. $result = $this->Email->getSubject();
  829. $this->assertSame($config['subject'], $result);
  830. $result = $this->Email->viewBuilder()->getTheme();
  831. $this->assertSame($config['theme'], $result);
  832. $result = $this->Email->getTransport();
  833. $this->assertInstanceOf('Cake\Mailer\Transport\DebugTransport', $result);
  834. $result = $this->Email->viewBuilder()->getHelpers();
  835. $this->assertEquals($config['helpers'], $result);
  836. }
  837. /**
  838. * Calling send() with no parameters should not overwrite the view variables.
  839. */
  840. public function testSendWithNoContentDoesNotOverwriteViewVar(): void
  841. {
  842. $this->Email->reset();
  843. $this->Email->setTransport('debug');
  844. $this->Email->setFrom('cake@cakephp.org');
  845. $this->Email->setTo('you@cakephp.org');
  846. $this->Email->setSubject('My title');
  847. $this->Email->setEmailFormat('text');
  848. $this->Email->viewBuilder()->setTemplate('default');
  849. $this->Email->setViewVars([
  850. 'content' => 'A message to you',
  851. ]);
  852. $result = $this->Email->send();
  853. $this->assertStringContainsString('A message to you', $result['message']);
  854. }
  855. /**
  856. * testSendWithContent method
  857. */
  858. public function testSendWithContent(): void
  859. {
  860. $this->Email->reset();
  861. $this->Email->setTransport('debug');
  862. $this->Email->setFrom('cake@cakephp.org');
  863. $this->Email->setTo(['you@cakephp.org' => 'You']);
  864. $this->Email->setSubject('My title');
  865. $this->Email->setProfile(['empty']);
  866. $result = $this->Email->send("Here is my body, with multi lines.\nThis is the second line.\r\n\r\nAnd the last.");
  867. $expected = ['headers', 'message'];
  868. $this->assertEquals($expected, array_keys($result));
  869. $expected = "Here is my body, with multi lines.\r\nThis is the second line.\r\n\r\nAnd the last.\r\n\r\n";
  870. $this->assertSame($expected, $result['message']);
  871. $this->assertStringContainsString('Date: ', $result['headers']);
  872. $this->assertStringContainsString('Message-ID: ', $result['headers']);
  873. $this->assertStringContainsString('To: ', $result['headers']);
  874. $result = $this->Email->send('Other body');
  875. $expected = "Other body\r\n\r\n";
  876. $this->assertSame($expected, $result['message']);
  877. $this->assertStringContainsString('Message-ID: ', $result['headers']);
  878. $this->assertStringContainsString('To: ', $result['headers']);
  879. $this->Email->reset();
  880. $this->Email->setTransport('debug');
  881. $this->Email->setFrom('cake@cakephp.org');
  882. $this->Email->setTo(['you@cakephp.org' => 'You']);
  883. $this->Email->setSubject('My title');
  884. $this->Email->setProfile(['empty']);
  885. $result = $this->Email->send(['Sending content', 'As array']);
  886. $expected = "Sending content\r\nAs array\r\n\r\n";
  887. $this->assertSame($expected, $result['message']);
  888. }
  889. /**
  890. * test send without a transport method
  891. */
  892. public function testSendWithoutTransport(): void
  893. {
  894. $this->expectException(\BadMethodCallException::class);
  895. $this->expectExceptionMessage('Cannot send email, transport was not defined.');
  896. $this->Email->setTo('cake@cakephp.org');
  897. $this->Email->setFrom('cake@cakephp.org');
  898. $this->Email->setSubject('My title');
  899. $this->Email->send('Forgot to set To');
  900. }
  901. /**
  902. * Test send() with no template.
  903. */
  904. public function testSendNoTemplateWithAttachments(): void
  905. {
  906. $this->Email->setTransport('debug');
  907. $this->Email->setFrom('cake@cakephp.org');
  908. $this->Email->setTo('cake@cakephp.org');
  909. $this->Email->setSubject('My title');
  910. $this->Email->setEmailFormat('text');
  911. $this->Email->setAttachments([CAKE . 'basics.php']);
  912. $result = $this->Email->send('Hello');
  913. $boundary = $this->Email->getBoundary();
  914. $this->assertStringContainsString('Content-Type: multipart/mixed; boundary="' . $boundary . '"', $result['headers']);
  915. $expected = "--$boundary\r\n" .
  916. "Content-Type: text/plain; charset=UTF-8\r\n" .
  917. "Content-Transfer-Encoding: 8bit\r\n" .
  918. "\r\n" .
  919. 'Hello' .
  920. "\r\n" .
  921. "\r\n" .
  922. "\r\n" .
  923. "--$boundary\r\n" .
  924. "Content-Disposition: attachment; filename=\"basics.php\"\r\n" .
  925. "Content-Type: text/x-php\r\n" .
  926. "Content-Transfer-Encoding: base64\r\n" .
  927. "\r\n";
  928. $this->assertStringContainsString($expected, $result['message']);
  929. }
  930. /**
  931. * Test send() with no template and data string attachment
  932. */
  933. public function testSendNoTemplateWithDataStringAttachment(): void
  934. {
  935. $this->Email->setTransport('debug');
  936. $this->Email->setFrom('cake@cakephp.org');
  937. $this->Email->setTo('cake@cakephp.org');
  938. $this->Email->setSubject('My title');
  939. $this->Email->setEmailFormat('text');
  940. $data = file_get_contents(TEST_APP . 'webroot/img/cake.power.gif');
  941. $this->Email->setAttachments(['cake.icon.gif' => [
  942. 'data' => $data,
  943. 'mimetype' => 'image/gif',
  944. ]]);
  945. $result = $this->Email->send('Hello');
  946. $boundary = $this->Email->getBoundary();
  947. $this->assertStringContainsString('Content-Type: multipart/mixed; boundary="' . $boundary . '"', $result['headers']);
  948. $expected = "--$boundary\r\n" .
  949. "Content-Type: text/plain; charset=UTF-8\r\n" .
  950. "Content-Transfer-Encoding: 8bit\r\n" .
  951. "\r\n" .
  952. 'Hello' .
  953. "\r\n" .
  954. "\r\n" .
  955. "\r\n" .
  956. "--$boundary\r\n" .
  957. "Content-Disposition: attachment; filename=\"cake.icon.gif\"\r\n" .
  958. "Content-Type: image/gif\r\n" .
  959. "Content-Transfer-Encoding: base64\r\n\r\n";
  960. $expected .= chunk_split(base64_encode($data), 76, "\r\n");
  961. $this->assertStringContainsString($expected, $result['message']);
  962. }
  963. /**
  964. * Test send() with no template as both
  965. */
  966. public function testSendNoTemplateWithAttachmentsAsBoth(): void
  967. {
  968. $this->Email->setTransport('debug');
  969. $this->Email->setFrom('cake@cakephp.org');
  970. $this->Email->setTo('cake@cakephp.org');
  971. $this->Email->setSubject('My title');
  972. $this->Email->setEmailFormat('both');
  973. $this->Email->setAttachments([CORE_PATH . 'VERSION.txt']);
  974. $result = $this->Email->send('Hello');
  975. $boundary = $this->Email->getBoundary();
  976. $this->assertStringContainsString('Content-Type: multipart/mixed; boundary="' . $boundary . '"', $result['headers']);
  977. $expected = "--$boundary\r\n" .
  978. "Content-Type: multipart/alternative; boundary=\"alt-$boundary\"\r\n" .
  979. "\r\n" .
  980. "--alt-$boundary\r\n" .
  981. "Content-Type: text/plain; charset=UTF-8\r\n" .
  982. "Content-Transfer-Encoding: 8bit\r\n" .
  983. "\r\n" .
  984. 'Hello' .
  985. "\r\n" .
  986. "\r\n" .
  987. "\r\n" .
  988. "--alt-$boundary\r\n" .
  989. "Content-Type: text/html; charset=UTF-8\r\n" .
  990. "Content-Transfer-Encoding: 8bit\r\n" .
  991. "\r\n" .
  992. 'Hello' .
  993. "\r\n" .
  994. "\r\n" .
  995. "\r\n" .
  996. "--alt-{$boundary}--\r\n" .
  997. "\r\n" .
  998. "--$boundary\r\n" .
  999. "Content-Disposition: attachment; filename=\"VERSION.txt\"\r\n" .
  1000. "Content-Type: text/plain\r\n" .
  1001. "Content-Transfer-Encoding: base64\r\n" .
  1002. "\r\n";
  1003. $this->assertStringContainsString($expected, $result['message']);
  1004. }
  1005. /**
  1006. * Test setting inline attachments and messages.
  1007. */
  1008. public function testSendWithInlineAttachments(): void
  1009. {
  1010. $this->Email->setTransport('debug');
  1011. $this->Email->setFrom('cake@cakephp.org');
  1012. $this->Email->setTo('cake@cakephp.org');
  1013. $this->Email->setSubject('My title');
  1014. $this->Email->setEmailFormat('both');
  1015. $this->Email->setAttachments([
  1016. 'cake.png' => [
  1017. 'file' => CORE_PATH . 'VERSION.txt',
  1018. 'contentId' => 'abc123',
  1019. ],
  1020. ]);
  1021. $result = $this->Email->send('Hello');
  1022. $boundary = $this->Email->getBoundary();
  1023. $this->assertStringContainsString('Content-Type: multipart/mixed; boundary="' . $boundary . '"', $result['headers']);
  1024. $expected = "--$boundary\r\n" .
  1025. "Content-Type: multipart/related; boundary=\"rel-$boundary\"\r\n" .
  1026. "\r\n" .
  1027. "--rel-$boundary\r\n" .
  1028. "Content-Type: multipart/alternative; boundary=\"alt-$boundary\"\r\n" .
  1029. "\r\n" .
  1030. "--alt-$boundary\r\n" .
  1031. "Content-Type: text/plain; charset=UTF-8\r\n" .
  1032. "Content-Transfer-Encoding: 8bit\r\n" .
  1033. "\r\n" .
  1034. 'Hello' .
  1035. "\r\n" .
  1036. "\r\n" .
  1037. "\r\n" .
  1038. "--alt-$boundary\r\n" .
  1039. "Content-Type: text/html; charset=UTF-8\r\n" .
  1040. "Content-Transfer-Encoding: 8bit\r\n" .
  1041. "\r\n" .
  1042. 'Hello' .
  1043. "\r\n" .
  1044. "\r\n" .
  1045. "\r\n" .
  1046. "--alt-{$boundary}--\r\n" .
  1047. "\r\n" .
  1048. "--rel-$boundary\r\n" .
  1049. "Content-Disposition: inline; filename=\"cake.png\"\r\n" .
  1050. "Content-Type: text/plain\r\n" .
  1051. "Content-Transfer-Encoding: base64\r\n" .
  1052. "Content-ID: <abc123>\r\n" .
  1053. "\r\n";
  1054. $this->assertStringContainsString($expected, $result['message']);
  1055. $this->assertStringContainsString('--rel-' . $boundary . '--', $result['message']);
  1056. $this->assertStringContainsString('--' . $boundary . '--', $result['message']);
  1057. }
  1058. /**
  1059. * Test setting inline attachments and HTML only messages.
  1060. */
  1061. public function testSendWithInlineAttachmentsHtmlOnly(): void
  1062. {
  1063. $this->Email->setTransport('debug');
  1064. $this->Email->setFrom('cake@cakephp.org');
  1065. $this->Email->setTo('cake@cakephp.org');
  1066. $this->Email->setSubject('My title');
  1067. $this->Email->setEmailFormat('html');
  1068. $this->Email->setAttachments([
  1069. 'cake.png' => [
  1070. 'file' => CORE_PATH . 'VERSION.txt',
  1071. 'contentId' => 'abc123',
  1072. ],
  1073. ]);
  1074. $result = $this->Email->send('Hello');
  1075. $boundary = $this->Email->getBoundary();
  1076. $this->assertStringContainsString('Content-Type: multipart/mixed; boundary="' . $boundary . '"', $result['headers']);
  1077. $expected = "--$boundary\r\n" .
  1078. "Content-Type: multipart/related; boundary=\"rel-$boundary\"\r\n" .
  1079. "\r\n" .
  1080. "--rel-$boundary\r\n" .
  1081. "Content-Type: text/html; charset=UTF-8\r\n" .
  1082. "Content-Transfer-Encoding: 8bit\r\n" .
  1083. "\r\n" .
  1084. 'Hello' .
  1085. "\r\n" .
  1086. "\r\n" .
  1087. "\r\n" .
  1088. "--rel-$boundary\r\n" .
  1089. "Content-Disposition: inline; filename=\"cake.png\"\r\n" .
  1090. "Content-Type: text/plain\r\n" .
  1091. "Content-Transfer-Encoding: base64\r\n" .
  1092. "Content-ID: <abc123>\r\n" .
  1093. "\r\n";
  1094. $this->assertStringContainsString($expected, $result['message']);
  1095. $this->assertStringContainsString('--rel-' . $boundary . '--', $result['message']);
  1096. $this->assertStringContainsString('--' . $boundary . '--', $result['message']);
  1097. }
  1098. /**
  1099. * Test disabling content-disposition.
  1100. */
  1101. public function testSendWithNoContentDispositionAttachments(): void
  1102. {
  1103. $this->Email->setTransport('debug');
  1104. $this->Email->setFrom('cake@cakephp.org');
  1105. $this->Email->setTo('cake@cakephp.org');
  1106. $this->Email->setSubject('My title');
  1107. $this->Email->setEmailFormat('text');
  1108. $this->Email->setAttachments([
  1109. 'cake.png' => [
  1110. 'file' => CORE_PATH . 'VERSION.txt',
  1111. 'contentDisposition' => false,
  1112. ],
  1113. ]);
  1114. $result = $this->Email->send('Hello');
  1115. $boundary = $this->Email->getBoundary();
  1116. $this->assertStringContainsString('Content-Type: multipart/mixed; boundary="' . $boundary . '"', $result['headers']);
  1117. $expected = "--$boundary\r\n" .
  1118. "Content-Type: text/plain; charset=UTF-8\r\n" .
  1119. "Content-Transfer-Encoding: 8bit\r\n" .
  1120. "\r\n" .
  1121. 'Hello' .
  1122. "\r\n" .
  1123. "\r\n" .
  1124. "\r\n" .
  1125. "--{$boundary}\r\n" .
  1126. "Content-Type: text/plain\r\n" .
  1127. "Content-Transfer-Encoding: base64\r\n" .
  1128. "\r\n";
  1129. $this->assertStringContainsString($expected, $result['message']);
  1130. $this->assertStringContainsString('--' . $boundary . '--', $result['message']);
  1131. }
  1132. /**
  1133. * Test an attachment filename with non-ASCII characters.
  1134. */
  1135. public function testSendWithNonAsciiFilenameAttachments(): void
  1136. {
  1137. $this->Email->setTransport('debug');
  1138. $this->Email->setFrom('cake@cakephp.org');
  1139. $this->Email->setTo('cake@cakephp.org');
  1140. $this->Email->setSubject('My title');
  1141. $this->Email->setEmailFormat('both');
  1142. $this->Email->setAttachments([
  1143. 'gâteau.png' => [
  1144. 'file' => CORE_PATH . 'VERSION.txt',
  1145. 'contentId' => 'abc123',
  1146. ],
  1147. ]);
  1148. $result = $this->Email->send('Hello');
  1149. $boundary = $this->Email->getBoundary();
  1150. $this->assertStringContainsString(
  1151. 'Content-Type: multipart/mixed; boundary="' . $boundary . '"',
  1152. $result['headers']
  1153. );
  1154. $expected = "--$boundary\r\n" .
  1155. "Content-Type: multipart/related; boundary=\"rel-$boundary\"\r\n" .
  1156. "\r\n" .
  1157. "--rel-$boundary\r\n" .
  1158. "Content-Type: multipart/alternative; boundary=\"alt-$boundary\"\r\n" .
  1159. "\r\n" .
  1160. "--alt-$boundary\r\n" .
  1161. "Content-Type: text/plain; charset=UTF-8\r\n" .
  1162. "Content-Transfer-Encoding: 8bit\r\n" .
  1163. "\r\n" .
  1164. 'Hello' .
  1165. "\r\n" .
  1166. "\r\n" .
  1167. "\r\n" .
  1168. "--alt-$boundary\r\n" .
  1169. "Content-Type: text/html; charset=UTF-8\r\n" .
  1170. "Content-Transfer-Encoding: 8bit\r\n" .
  1171. "\r\n" .
  1172. 'Hello' .
  1173. "\r\n" .
  1174. "\r\n" .
  1175. "\r\n" .
  1176. "--alt-{$boundary}--\r\n" .
  1177. "\r\n" .
  1178. "--rel-$boundary\r\n" .
  1179. "Content-Disposition: inline; filename=\"gateau.png\"; filename*=utf-8''g%C3%A2teau.png\r\n" .
  1180. "Content-Type: text/plain\r\n" .
  1181. "Content-Transfer-Encoding: base64\r\n" .
  1182. "Content-ID: <abc123>\r\n" .
  1183. "\r\n";
  1184. $this->assertStringContainsString($expected, $result['message']);
  1185. $this->assertStringContainsString('--rel-' . $boundary . '--', $result['message']);
  1186. $this->assertStringContainsString('--' . $boundary . '--', $result['message']);
  1187. }
  1188. /**
  1189. * testSendWithLog method
  1190. */
  1191. public function testSendWithLog(): void
  1192. {
  1193. Log::setConfig('email', [
  1194. 'className' => 'Array',
  1195. ]);
  1196. $this->Email->setTransport('debug');
  1197. $this->Email->setTo('me@cakephp.org');
  1198. $this->Email->setFrom('cake@cakephp.org');
  1199. $this->Email->setSubject('My title');
  1200. $this->Email->setProfile(['log' => 'debug']);
  1201. $text = 'Logging This';
  1202. $result = $this->Email->send($text);
  1203. $this->assertNotEmpty($result);
  1204. $messages = Log::engine('email')->read();
  1205. $this->assertCount(1, $messages);
  1206. $this->assertStringContainsString($text, $messages[0]);
  1207. $this->assertStringContainsString('cake@cakephp.org', $messages[0]);
  1208. $this->assertStringContainsString('me@cakephp.org', $messages[0]);
  1209. }
  1210. /**
  1211. * testSendWithLogAndScope method
  1212. */
  1213. public function testSendWithLogAndScope(): void
  1214. {
  1215. Log::setConfig('email', [
  1216. 'className' => 'Array',
  1217. 'scopes' => ['email'],
  1218. ]);
  1219. $this->Email->setTransport('debug');
  1220. $this->Email->setTo('me@cakephp.org');
  1221. $this->Email->setFrom('cake@cakephp.org');
  1222. $this->Email->setSubject('My title');
  1223. $this->Email->setProfile(['log' => ['scope' => 'email']]);
  1224. $text = 'Logging This';
  1225. $this->Email->send($text);
  1226. $messages = Log::engine('email')->read();
  1227. $this->assertCount(1, $messages);
  1228. $this->assertStringContainsString($text, $messages[0]);
  1229. $this->assertStringContainsString('cake@cakephp.org', $messages[0]);
  1230. $this->assertStringContainsString('me@cakephp.org', $messages[0]);
  1231. }
  1232. /**
  1233. * testSendRender method
  1234. */
  1235. public function testSendRender(): void
  1236. {
  1237. $this->Email->reset();
  1238. $this->Email->setTransport('debug');
  1239. $this->Email->setFrom('cake@cakephp.org');
  1240. $this->Email->setTo(['you@cakephp.org' => 'You']);
  1241. $this->Email->setSubject('My title');
  1242. $this->Email->setProfile(['empty']);
  1243. $this->Email->viewBuilder()->setTemplate('default', 'default');
  1244. $result = $this->Email->send();
  1245. $this->assertStringContainsString('This email was sent using the CakePHP Framework', $result['message']);
  1246. $this->assertStringContainsString('Message-ID: ', $result['headers']);
  1247. $this->assertStringContainsString('To: ', $result['headers']);
  1248. }
  1249. /**
  1250. * test sending and rendering with no layout
  1251. */
  1252. public function testSendRenderNoLayout(): void
  1253. {
  1254. $this->Email->reset();
  1255. $this->Email->setTransport('debug');
  1256. $this->Email->setFrom('cake@cakephp.org');
  1257. $this->Email->setTo(['you@cakephp.org' => 'You']);
  1258. $this->Email->setSubject('My title');
  1259. $this->Email->setConfig(['empty']);
  1260. $this->Email->viewBuilder()
  1261. ->setTemplate('default')
  1262. ->disableAutoLayout();
  1263. $result = $this->Email->send('message body.');
  1264. $this->assertStringContainsString('message body.', $result['message']);
  1265. $this->assertStringNotContainsString('This email was sent using the CakePHP Framework', $result['message']);
  1266. }
  1267. /**
  1268. * testSendRender both method
  1269. */
  1270. public function testSendRenderBoth(): void
  1271. {
  1272. $this->Email->reset();
  1273. $this->Email->setTransport('debug');
  1274. $this->Email->setFrom('cake@cakephp.org');
  1275. $this->Email->setTo(['you@cakephp.org' => 'You']);
  1276. $this->Email->setSubject('My title');
  1277. $this->Email->setProfile(['empty']);
  1278. $this->Email->viewBuilder()->setTemplate('default', 'default');
  1279. $this->Email->setEmailFormat('both');
  1280. $result = $this->Email->send();
  1281. $this->assertStringContainsString('Message-ID: ', $result['headers']);
  1282. $this->assertStringContainsString('To: ', $result['headers']);
  1283. $boundary = $this->Email->getBoundary();
  1284. $this->assertStringContainsString('Content-Type: multipart/alternative; boundary="' . $boundary . '"', $result['headers']);
  1285. $expected = "--$boundary\r\n" .
  1286. "Content-Type: text/plain; charset=UTF-8\r\n" .
  1287. "Content-Transfer-Encoding: 8bit\r\n" .
  1288. "\r\n" .
  1289. "\r\n" .
  1290. "\r\n" .
  1291. 'This email was sent using the CakePHP Framework, https://cakephp.org.' .
  1292. "\r\n" .
  1293. "\r\n" .
  1294. "\r\n" .
  1295. "--$boundary\r\n" .
  1296. "Content-Type: text/html; charset=UTF-8\r\n" .
  1297. "Content-Transfer-Encoding: 8bit\r\n" .
  1298. "\r\n" .
  1299. '<!DOCTYPE html';
  1300. $this->assertStringStartsWith($expected, $result['message']);
  1301. $expected = "</html>\r\n" .
  1302. "\r\n" .
  1303. "\r\n" .
  1304. "\r\n" .
  1305. "--$boundary--\r\n";
  1306. $this->assertStringEndsWith($expected, $result['message']);
  1307. }
  1308. /**
  1309. * testSendRender method for ISO-2022-JP
  1310. */
  1311. public function testSendRenderJapanese(): void
  1312. {
  1313. $this->Email->reset();
  1314. $this->Email->setTransport('debug');
  1315. $this->Email->setFrom('cake@cakephp.org');
  1316. $this->Email->setTo(['you@cakephp.org' => 'You']);
  1317. $this->Email->setSubject('My title');
  1318. $this->Email->setProfile(['empty']);
  1319. $this->Email->viewBuilder()->setTemplate('default');
  1320. $this->Email->viewBuilder()->setLayout('japanese');
  1321. $this->Email->setCharset('ISO-2022-JP');
  1322. $result = $this->Email->send();
  1323. $expected = mb_convert_encoding('CakePHP Framework を使って送信したメールです。 https://cakephp.org.', 'ISO-2022-JP');
  1324. $this->assertStringContainsString($expected, $result['message']);
  1325. $this->assertStringContainsString('Message-ID: ', $result['headers']);
  1326. $this->assertStringContainsString('To: ', $result['headers']);
  1327. }
  1328. /**
  1329. * testSendRenderThemed method
  1330. */
  1331. public function testSendRenderThemed(): void
  1332. {
  1333. $this->loadPlugins(['TestTheme']);
  1334. $this->Email->reset();
  1335. $this->Email->setTransport('debug');
  1336. $this->Email->setFrom('cake@cakephp.org');
  1337. $this->Email->setTo(['you@cakephp.org' => 'You']);
  1338. $this->Email->setSubject('My title');
  1339. $this->Email->setProfile(['empty']);
  1340. $this->Email->viewBuilder()->setTheme('TestTheme');
  1341. $this->Email->viewBuilder()->setTemplate('themed', 'default');
  1342. $result = $this->Email->send();
  1343. $this->assertStringContainsString('In TestTheme', $result['message']);
  1344. $this->assertStringContainsString('/test_theme/img/test.jpg', $result['message']);
  1345. $this->assertStringContainsString('Message-ID: ', $result['headers']);
  1346. $this->assertStringContainsString('To: ', $result['headers']);
  1347. $this->assertStringContainsString('/test_theme/img/test.jpg', $result['message']);
  1348. $this->clearPlugins();
  1349. }
  1350. /**
  1351. * testSendRenderWithHTML method and assert line length is kept below the required limit
  1352. */
  1353. public function testSendRenderWithHTML(): void
  1354. {
  1355. $this->Email->reset();
  1356. $this->Email->setTransport('debug');
  1357. $this->Email->setFrom('cake@cakephp.org');
  1358. $this->Email->setTo(['you@cakephp.org' => 'You']);
  1359. $this->Email->setSubject('My title');
  1360. $this->Email->setProfile(['empty']);
  1361. $this->Email->setEmailFormat('html');
  1362. $this->Email->viewBuilder()->setTemplate('html', 'default');
  1363. $result = $this->Email->send();
  1364. $this->assertTextContains('<h1>HTML Ipsum Presents</h1>', $result['message']);
  1365. $this->assertLineLengths($result['message']);
  1366. }
  1367. /**
  1368. * testSendRenderWithVars method
  1369. */
  1370. public function testSendRenderWithVars(): void
  1371. {
  1372. $this->Email->reset();
  1373. $this->Email->setTransport('debug');
  1374. $this->Email->setFrom('cake@cakephp.org');
  1375. $this->Email->setTo(['you@cakephp.org' => 'You']);
  1376. $this->Email->setSubject('My title');
  1377. $this->Email->setProfile(['empty']);
  1378. $this->Email->viewBuilder()->setTemplate('custom', 'default');
  1379. $this->Email->setViewVars(['value' => 12345]);
  1380. $result = $this->Email->send();
  1381. $this->assertStringContainsString('Here is your value: 12345', $result['message']);
  1382. }
  1383. /**
  1384. * testSendRenderWithVars method for ISO-2022-JP
  1385. */
  1386. public function testSendRenderWithVarsJapanese(): void
  1387. {
  1388. $this->Email->reset();
  1389. $this->Email->setTransport('debug');
  1390. $this->Email->setFrom('cake@cakephp.org');
  1391. $this->Email->setTo(['you@cakephp.org' => 'You']);
  1392. $this->Email->setSubject('My title');
  1393. $this->Email->setProfile(['empty']);
  1394. $this->Email->viewBuilder()->setTemplate('japanese', 'default');
  1395. $this->Email->setViewVars(['value' => '日本語の差し込み123']);
  1396. $this->Email->setCharset('ISO-2022-JP');
  1397. $result = $this->Email->send();
  1398. $expected = mb_convert_encoding('ここにあなたの設定した値が入ります: 日本語の差し込み123', 'ISO-2022-JP');
  1399. $this->assertStringContainsString($expected, $result['message']);
  1400. }
  1401. /**
  1402. * testSendRenderWithHelpers method
  1403. */
  1404. public function testSendRenderWithHelpers(): void
  1405. {
  1406. $this->Email->reset();
  1407. $this->Email->setTransport('debug');
  1408. $timestamp = time();
  1409. $this->Email->setFrom('cake@cakephp.org');
  1410. $this->Email->setTo(['you@cakephp.org' => 'You']);
  1411. $this->Email->setSubject('My title');
  1412. $this->Email->setProfile(['empty']);
  1413. $this->Email->viewBuilder()
  1414. ->setTemplate('custom_helper')
  1415. ->setLayout('default')
  1416. ->setHelpers(['Time'], false);
  1417. $this->Email->setViewVars(['time' => $timestamp]);
  1418. $result = $this->Email->send();
  1419. $dateTime = new \DateTime();
  1420. $dateTime->setTimestamp($timestamp);
  1421. $this->assertStringContainsString('Right now: ' . $dateTime->format($dateTime::ATOM), $result['message']);
  1422. $result = $this->Email->viewBuilder()->getHelpers();
  1423. $this->assertEquals(['Time'], $result);
  1424. }
  1425. /**
  1426. * testSendRenderWithImage method
  1427. */
  1428. public function testSendRenderWithImage(): void
  1429. {
  1430. $this->Email->reset();
  1431. $this->Email->setTransport('debug');
  1432. $this->Email->setFrom('cake@cakephp.org');
  1433. $this->Email->setTo(['you@cakephp.org' => 'You']);
  1434. $this->Email->setSubject('My title');
  1435. $this->Email->setProfile(['empty']);
  1436. $this->Email->viewBuilder()->setTemplate('image');
  1437. $this->Email->setEmailFormat('html');
  1438. $server = env('SERVER_NAME') ? env('SERVER_NAME') : 'localhost';
  1439. if (env('SERVER_PORT') && env('SERVER_PORT') !== 80) {
  1440. $server .= ':' . env('SERVER_PORT');
  1441. }
  1442. $expected = '<img src="http://' . $server . '/img/image.gif" alt="cool image" width="100" height="100"';
  1443. $result = $this->Email->send();
  1444. $this->assertStringContainsString($expected, $result['message']);
  1445. }
  1446. /**
  1447. * testSendRenderPlugin method
  1448. */
  1449. public function testSendRenderPlugin(): void
  1450. {
  1451. $this->loadPlugins(['TestPlugin', 'TestPluginTwo', 'TestTheme']);
  1452. $this->Email->reset();
  1453. $this->Email->setTransport('debug');
  1454. $this->Email->setFrom('cake@cakephp.org');
  1455. $this->Email->setTo(['you@cakephp.org' => 'You']);
  1456. $this->Email->setSubject('My title');
  1457. $this->Email->setProfile(['empty']);
  1458. $this->Email->viewBuilder()
  1459. ->setTemplate('TestPlugin.test_plugin_tpl')
  1460. ->setLayout('default');
  1461. $result = $this->Email->send();
  1462. $this->assertStringContainsString('Into TestPlugin.', $result['message']);
  1463. $this->assertStringContainsString('This email was sent using the CakePHP Framework', $result['message']);
  1464. $this->Email->viewBuilder()
  1465. ->setTemplate('TestPlugin.test_plugin_tpl')
  1466. ->setLayout('TestPlugin.plug_default');
  1467. $result = $this->Email->send();
  1468. $this->assertStringContainsString('Into TestPlugin.', $result['message']);
  1469. $this->assertStringContainsString('This email was sent using the TestPlugin.', $result['message']);
  1470. $this->Email->viewBuilder()
  1471. ->setTemplate('TestPlugin.test_plugin_tpl')
  1472. ->setLayout('plug_default');
  1473. $result = $this->Email->send();
  1474. $this->assertStringContainsString('Into TestPlugin.', $result['message']);
  1475. $this->assertStringContainsString('This email was sent using the TestPlugin.', $result['message']);
  1476. $this->Email->viewBuilder()
  1477. ->setTemplate('TestPlugin.test_plugin_tpl')
  1478. ->setLayout('TestPluginTwo.default');
  1479. $result = $this->Email->send();
  1480. $this->assertStringContainsString('Into TestPlugin.', $result['message']);
  1481. $this->assertStringContainsString('This email was sent using TestPluginTwo.', $result['message']);
  1482. // test plugin template overridden by theme
  1483. $this->Email->viewBuilder()->setTheme('TestTheme');
  1484. $result = $this->Email->send();
  1485. $this->assertStringContainsString('Into TestPlugin. (themed)', $result['message']);
  1486. $this->Email->setViewVars(['value' => 12345]);
  1487. $this->Email->viewBuilder()
  1488. ->setTemplate('custom')
  1489. ->setLayout('TestPlugin.plug_default');
  1490. $result = $this->Email->send();
  1491. $this->assertStringContainsString('Here is your value: 12345', $result['message']);
  1492. $this->assertStringContainsString('This email was sent using the TestPlugin.', $result['message']);
  1493. $this->clearPlugins();
  1494. }
  1495. /**
  1496. * Test that a MissingTemplateException is thrown
  1497. */
  1498. public function testMissingTemplateException(): void
  1499. {
  1500. $this->expectException(MissingTemplateException::class);
  1501. $this->Email->reset();
  1502. $this->Email->setTransport('debug');
  1503. $this->Email->setFrom('cake@cakephp.org');
  1504. $this->Email->setTo(['you@cakephp.org' => 'You']);
  1505. $this->Email->setSubject('My title');
  1506. $this->Email->viewBuilder()->setTemplate('fooo');
  1507. $this->Email->send();
  1508. }
  1509. /**
  1510. * testSendMultipleMIME method
  1511. */
  1512. public function testSendMultipleMIME(): void
  1513. {
  1514. $this->Email->reset();
  1515. $this->Email->setTransport('debug');
  1516. $this->Email->setFrom('cake@cakephp.org');
  1517. $this->Email->setTo(['you@cakephp.org' => 'You']);
  1518. $this->Email->setSubject('My title');
  1519. $this->Email->viewBuilder()->setTemplate('custom', 'default');
  1520. $this->Email->setProfile([]);
  1521. $this->Email->setViewVars(['value' => 12345]);
  1522. $this->Email->setEmailFormat('both');
  1523. $this->Email->send();
  1524. $message = $this->Email->message();
  1525. $boundary = $this->Email->getBoundary();
  1526. $this->assertNotEmpty($boundary);
  1527. $this->assertContains('--' . $boundary, $message);
  1528. $this->assertContains('--' . $boundary . '--', $message);
  1529. $this->Email->setAttachments(['fake.php' => __FILE__]);
  1530. $this->Email->send();
  1531. $message = $this->Email->message();
  1532. $boundary = $this->Email->getBoundary();
  1533. $this->assertNotEmpty($boundary);
  1534. $this->assertContains('--' . $boundary, $message);
  1535. $this->assertContains('--' . $boundary . '--', $message);
  1536. $this->assertContains('--alt-' . $boundary, $message);
  1537. $this->assertContains('--alt-' . $boundary . '--', $message);
  1538. }
  1539. /**
  1540. * testSendAttachment method
  1541. */
  1542. public function testSendAttachment(): void
  1543. {
  1544. $this->Email->reset();
  1545. $this->Email->setTransport('debug');
  1546. $this->Email->setFrom('cake@cakephp.org');
  1547. $this->Email->setTo(['you@cakephp.org' => 'You']);
  1548. $this->Email->setSubject('My title');
  1549. $this->Email->setProfile([]);
  1550. $this->Email->setAttachments([CAKE . 'basics.php']);
  1551. $result = $this->Email->send('body');
  1552. $expected = "Content-Disposition: attachment; filename=\"basics.php\"\r\n" .
  1553. "Content-Type: text/x-php\r\n" .
  1554. "Content-Transfer-Encoding: base64\r\n";
  1555. $this->assertStringContainsString($expected, $result['message']);
  1556. $this->Email->setAttachments(['my.file.txt' => CAKE . 'basics.php']);
  1557. $result = $this->Email->send('body');
  1558. $expected = "Content-Disposition: attachment; filename=\"my.file.txt\"\r\n" .
  1559. "Content-Type: text/x-php\r\n" .
  1560. "Content-Transfer-Encoding: base64\r\n";
  1561. $this->assertStringContainsString($expected, $result['message']);
  1562. $this->Email->setAttachments(['file.txt' => ['file' => CAKE . 'basics.php', 'mimetype' => 'text/plain']]);
  1563. $result = $this->Email->send('body');
  1564. $expected = "Content-Disposition: attachment; filename=\"file.txt\"\r\n" .
  1565. "Content-Type: text/plain\r\n" .
  1566. "Content-Transfer-Encoding: base64\r\n";
  1567. $this->assertStringContainsString($expected, $result['message']);
  1568. $this->Email->setAttachments(['file2.txt' => ['file' => CAKE . 'basics.php', 'mimetype' => 'text/plain', 'contentId' => 'a1b1c1']]);
  1569. $result = $this->Email->send('body');
  1570. $expected = "Content-Disposition: inline; filename=\"file2.txt\"\r\n" .
  1571. "Content-Type: text/plain\r\n" .
  1572. "Content-Transfer-Encoding: base64\r\n" .
  1573. "Content-ID: <a1b1c1>\r\n";
  1574. $this->assertStringContainsString($expected, $result['message']);
  1575. }
  1576. /**
  1577. * testDeliver method
  1578. */
  1579. public function testDeliver(): void
  1580. {
  1581. TransportFactory::drop('default');
  1582. TransportFactory::setConfig('default', ['className' => 'Debug']);
  1583. $instance = Email::deliver('all@cakephp.org', 'About', 'Everything ok', ['from' => 'root@cakephp.org'], false);
  1584. $this->assertInstanceOf('Cake\Mailer\Email', $instance);
  1585. $this->assertSame($instance->getTo(), ['all@cakephp.org' => 'all@cakephp.org']);
  1586. $this->assertSame($instance->getSubject(), 'About');
  1587. $this->assertSame($instance->getFrom(), ['root@cakephp.org' => 'root@cakephp.org']);
  1588. $this->assertInstanceOf('Cake\Mailer\AbstractTransport', $instance->getTransport());
  1589. $config = [
  1590. 'from' => 'cake@cakephp.org',
  1591. 'to' => 'debug@cakephp.org',
  1592. 'subject' => 'Update ok',
  1593. 'template' => 'custom',
  1594. 'layout' => 'custom_layout',
  1595. 'viewVars' => ['value' => 123],
  1596. 'cc' => ['cake@cakephp.org' => 'Myself'],
  1597. ];
  1598. $instance = Email::deliver(null, null, ['name' => 'CakePHP'], $config, false);
  1599. $this->assertSame($instance->getFrom(), ['cake@cakephp.org' => 'cake@cakephp.org']);
  1600. $this->assertSame($instance->getTo(), ['debug@cakephp.org' => 'debug@cakephp.org']);
  1601. $this->assertSame($instance->getSubject(), 'Update ok');
  1602. $this->assertSame($instance->viewBuilder()->getTemplate(), 'custom');
  1603. $this->assertSame($instance->viewBuilder()->getLayout(), 'custom_layout');
  1604. $this->assertEquals($instance->getViewVars(), ['value' => 123, 'name' => 'CakePHP']);
  1605. $this->assertSame($instance->getCc(), ['cake@cakephp.org' => 'Myself']);
  1606. $configs = ['from' => 'root@cakephp.org', 'message' => 'Message from configs', 'transport' => 'debug'];
  1607. $instance = Email::deliver('all@cakephp.org', 'About', null, $configs, true);
  1608. $message = $instance->message();
  1609. $this->assertSame($configs['message'], $message[0]);
  1610. }
  1611. /**
  1612. * testMessage method
  1613. */
  1614. public function testMessage(): void
  1615. {
  1616. $this->Email->reset();
  1617. $this->Email->setTransport('debug');
  1618. $this->Email->setFrom('cake@cakephp.org');
  1619. $this->Email->setTo(['you@cakephp.org' => 'You']);
  1620. $this->Email->setSubject('My title');
  1621. $this->Email->setProfile(['empty']);
  1622. $this->Email->viewBuilder()->setTemplate('default', 'default');
  1623. $this->Email->setEmailFormat('both');
  1624. $this->Email->send();
  1625. $expected = '<p>This email was sent using the <a href="https://cakephp.org">CakePHP Framework</a></p>';
  1626. $this->assertStringContainsString($expected, $this->Email->message(Email::MESSAGE_HTML));
  1627. $expected = 'This email was sent using the CakePHP Framework, https://cakephp.org.';
  1628. $this->assertStringContainsString($expected, $this->Email->message(Email::MESSAGE_TEXT));
  1629. $message = $this->Email->message();
  1630. $this->assertContains('Content-Type: text/plain; charset=UTF-8', $message);
  1631. $this->assertContains('Content-Type: text/html; charset=UTF-8', $message);
  1632. // UTF-8 is 8bit
  1633. $this->assertTrue($this->_checkContentTransferEncoding($message, '8bit'));
  1634. $this->Email->setCharset('ISO-2022-JP');
  1635. $this->Email->send();
  1636. $message = $this->Email->message();
  1637. $this->assertContains('Content-Type: text/plain; charset=ISO-2022-JP', $message);
  1638. $this->assertContains('Content-Type: text/html; charset=ISO-2022-JP', $message);
  1639. // ISO-2022-JP is 7bit
  1640. $this->assertTrue($this->_checkContentTransferEncoding($message, '7bit'));
  1641. }
  1642. /**
  1643. * testReset method
  1644. */
  1645. public function testReset(): void
  1646. {
  1647. $this->Email->setTo('cake@cakephp.org');
  1648. $this->Email->viewBuilder()->setTheme('TestTheme');
  1649. $this->Email->setEmailPattern('/.+@.+\..+/i');
  1650. $this->assertSame(['cake@cakephp.org' => 'cake@cakephp.org'], $this->Email->getTo());
  1651. $this->Email->reset();
  1652. $this->assertSame([], $this->Email->getTo());
  1653. $this->assertNull($this->Email->viewBuilder()->getTheme());
  1654. $this->assertSame(Email::EMAIL_PATTERN, $this->Email->getEmailPattern());
  1655. }
  1656. /**
  1657. * testReset with charset
  1658. */
  1659. public function testResetWithCharset(): void
  1660. {
  1661. $this->Email->setCharset('ISO-2022-JP');
  1662. $this->Email->reset();
  1663. $this->assertSame('utf-8', $this->Email->getCharset());
  1664. $this->assertSame('utf-8', $this->Email->getHeaderCharset());
  1665. }
  1666. /**
  1667. * testRender method
  1668. */
  1669. public function testRenderWithLayoutAndAttachment(): void
  1670. {
  1671. $this->Email->setEmailFormat('html');
  1672. $this->Email->viewBuilder()->setTemplate('html', 'default');
  1673. $this->Email->setAttachments([CAKE . 'basics.php']);
  1674. $this->Email->render();
  1675. $result = $this->Email->message();
  1676. $this->assertNotEmpty($result);
  1677. $result = $this->Email->getBoundary();
  1678. $this->assertMatchesRegularExpression('/^[0-9a-f]{32}$/', $result);
  1679. }
  1680. /**
  1681. * testConstructWithConfigArray method
  1682. */
  1683. public function testConstructWithConfigArray(): void
  1684. {
  1685. $configs = [
  1686. 'from' => ['some@example.com' => 'My website'],
  1687. 'to' => 'test@example.com',
  1688. 'subject' => 'Test mail subject',
  1689. 'transport' => 'debug',
  1690. ];
  1691. $this->Email = new Email($configs);
  1692. $result = $this->Email->getTo();
  1693. $this->assertEquals([$configs['to'] => $configs['to']], $result);
  1694. $result = $this->Email->getFrom();
  1695. $this->assertEquals($configs['from'], $result);
  1696. $result = $this->Email->getSubject();
  1697. $this->assertSame($configs['subject'], $result);
  1698. $result = $this->Email->getTransport();
  1699. $this->assertInstanceOf('Cake\Mailer\Transport\DebugTransport', $result);
  1700. $result = $this->Email->send('This is the message');
  1701. $this->assertStringContainsString('Message-ID: ', $result['headers']);
  1702. $this->assertStringContainsString('To: ', $result['headers']);
  1703. }
  1704. /**
  1705. * testConfigArrayWithLayoutWithoutTemplate method
  1706. */
  1707. public function testConfigArrayWithLayoutWithoutTemplate(): void
  1708. {
  1709. $configs = [
  1710. 'from' => ['some@example.com' => 'My website'],
  1711. 'to' => 'test@example.com',
  1712. 'subject' => 'Test mail subject',
  1713. 'transport' => 'debug',
  1714. 'layout' => 'custom',
  1715. ];
  1716. $this->Email = new Email($configs);
  1717. $template = $this->Email->viewBuilder()->getTemplate();
  1718. $layout = $this->Email->viewBuilder()->getLayout();
  1719. $this->assertNull($template);
  1720. $this->assertSame($configs['layout'], $layout);
  1721. }
  1722. /**
  1723. * testConstructWithConfigString method
  1724. */
  1725. public function testConstructWithConfigString(): void
  1726. {
  1727. $configs = [
  1728. 'from' => ['some@example.com' => 'My website'],
  1729. 'to' => 'test@example.com',
  1730. 'subject' => 'Test mail subject',
  1731. 'transport' => 'debug',
  1732. ];
  1733. Email::setConfig('test', $configs);
  1734. $this->Email = new Email('test');
  1735. $result = $this->Email->getTo();
  1736. $this->assertEquals([$configs['to'] => $configs['to']], $result);
  1737. $result = $this->Email->getFrom();
  1738. $this->assertEquals($configs['from'], $result);
  1739. $result = $this->Email->getSubject();
  1740. $this->assertSame($configs['subject'], $result);
  1741. $result = $this->Email->getTransport();
  1742. $this->assertInstanceOf('Cake\Mailer\Transport\DebugTransport', $result);
  1743. $result = $this->Email->send('This is the message');
  1744. $this->assertStringContainsString('Message-ID: ', $result['headers']);
  1745. $this->assertStringContainsString('To: ', $result['headers']);
  1746. }
  1747. /**
  1748. * testViewRender method
  1749. */
  1750. public function testViewRender(): void
  1751. {
  1752. $result = $this->Email->getViewRenderer();
  1753. $this->assertSame('Cake\View\View', $result);
  1754. $result = $this->Email->setViewRenderer('Cake\View\ThemeView');
  1755. $this->assertInstanceOf('Cake\Mailer\Email', $result);
  1756. $result = $this->Email->getViewRenderer();
  1757. $this->assertSame('Cake\View\ThemeView', $result);
  1758. }
  1759. /**
  1760. * testEmailFormat method
  1761. */
  1762. public function testEmailFormat(): void
  1763. {
  1764. $result = $this->Email->getEmailFormat();
  1765. $this->assertSame('text', $result);
  1766. $result = $this->Email->setEmailFormat('html');
  1767. $this->assertInstanceOf('Cake\Mailer\Email', $result);
  1768. $result = $this->Email->getEmailFormat();
  1769. $this->assertSame('html', $result);
  1770. $this->expectException(\InvalidArgumentException::class);
  1771. $this->Email->setEmailFormat('invalid');
  1772. }
  1773. /**
  1774. * Tests that it is possible to add charset configuration to a CakeEmail object
  1775. */
  1776. public function testConfigCharset(): void
  1777. {
  1778. $email = new Email();
  1779. $this->assertEquals(Configure::read('App.encoding'), $email->getCharset());
  1780. $this->assertEquals(Configure::read('App.encoding'), $email->getHeaderCharset());
  1781. $email = new Email(['charset' => 'iso-2022-jp', 'headerCharset' => 'iso-2022-jp-ms']);
  1782. $this->assertSame('iso-2022-jp', $email->getCharset());
  1783. $this->assertSame('iso-2022-jp-ms', $email->getHeaderCharset());
  1784. $email = new Email(['charset' => 'iso-2022-jp']);
  1785. $this->assertSame('iso-2022-jp', $email->getCharset());
  1786. $this->assertSame('iso-2022-jp', $email->getHeaderCharset());
  1787. $email = new Email(['headerCharset' => 'iso-2022-jp-ms']);
  1788. $this->assertEquals(Configure::read('App.encoding'), $email->getCharset());
  1789. $this->assertSame('iso-2022-jp-ms', $email->getHeaderCharset());
  1790. }
  1791. /**
  1792. * Tests that the header is encoded using the configured headerCharset
  1793. */
  1794. public function testHeaderEncoding(): void
  1795. {
  1796. $email = new Email(['headerCharset' => 'iso-2022-jp-ms', 'transport' => 'debug']);
  1797. $email->setSubject('あれ?もしかしての前と');
  1798. $headers = $email->getHeaders(['subject']);
  1799. $expected = '?ISO-2022-JP?B?GyRCJCIkbCEpJGIkNyQrJDckRiROQTAkSBsoQg==?=';
  1800. $this->assertStringContainsString($expected, $headers['Subject']);
  1801. $email->setTo('someone@example.com')->setFrom('someone@example.com');
  1802. $result = $email->send('ってテーブルを作ってやってたらう');
  1803. $this->assertStringContainsString('ってテーブルを作ってやってたらう', $result['message']);
  1804. }
  1805. /**
  1806. * Tests that the body is encoded using the configured charset
  1807. */
  1808. public function testBodyEncoding(): void
  1809. {
  1810. $email = new Email([
  1811. 'charset' => 'iso-2022-jp',
  1812. 'headerCharset' => 'iso-2022-jp-ms',
  1813. 'transport' => 'debug',
  1814. ]);
  1815. $email->setSubject('あれ?もしかしての前と');
  1816. $headers = $email->getHeaders(['subject']);
  1817. $expected = '?ISO-2022-JP?B?GyRCJCIkbCEpJGIkNyQrJDckRiROQTAkSBsoQg==?=';
  1818. $this->assertStringContainsString($expected, $headers['Subject']);
  1819. $email->setTo('someone@example.com')->setFrom('someone@example.com');
  1820. $result = $email->send('ってテーブルを作ってやってたらう');
  1821. $this->assertStringContainsString('Content-Type: text/plain; charset=ISO-2022-JP', $result['headers']);
  1822. $this->assertStringContainsString(mb_convert_encoding('ってテーブルを作ってやってたらう', 'ISO-2022-JP'), $result['message']);
  1823. }
  1824. /**
  1825. * Tests that the body is encoded using the configured charset (Japanese standard encoding)
  1826. */
  1827. public function testBodyEncodingIso2022Jp(): void
  1828. {
  1829. $email = new Email([
  1830. 'charset' => 'iso-2022-jp',
  1831. 'headerCharset' => 'iso-2022-jp',
  1832. 'transport' => 'debug',
  1833. ]);
  1834. $email->setSubject('あれ?もしかしての前と');
  1835. $headers = $email->getHeaders(['subject']);
  1836. $expected = '?ISO-2022-JP?B?GyRCJCIkbCEpJGIkNyQrJDckRiROQTAkSBsoQg==?=';
  1837. $this->assertStringContainsString($expected, $headers['Subject']);
  1838. $email->setTo('someone@example.com')->setFrom('someone@example.com');
  1839. $result = $email->send('①㈱');
  1840. $this->assertTextContains('Content-Type: text/plain; charset=ISO-2022-JP', $result['headers']);
  1841. $this->assertTextNotContains('Content-Type: text/plain; charset=ISO-2022-JP-MS', $result['headers']); // not charset=iso-2022-jp-ms
  1842. $this->assertTextNotContains(mb_convert_encoding('①㈱', 'ISO-2022-JP-MS'), $result['message']);
  1843. }
  1844. /**
  1845. * Tests that the body is encoded using the configured charset (Japanese irregular encoding, but sometime use this)
  1846. */
  1847. public function testBodyEncodingIso2022JpMs(): void
  1848. {
  1849. $email = new Email([
  1850. 'charset' => 'iso-2022-jp-ms',
  1851. 'headerCharset' => 'iso-2022-jp-ms',
  1852. 'transport' => 'debug',
  1853. ]);
  1854. $email->setSubject('あれ?もしかしての前と');
  1855. $headers = $email->getHeaders(['subject']);
  1856. $expected = '?ISO-2022-JP?B?GyRCJCIkbCEpJGIkNyQrJDckRiROQTAkSBsoQg==?=';
  1857. $this->assertStringContainsString($expected, $headers['Subject']);
  1858. $email->setTo('someone@example.com')->setFrom('someone@example.com');
  1859. $result = $email->send('①㈱');
  1860. $this->assertTextContains('Content-Type: text/plain; charset=ISO-2022-JP', $result['headers']);
  1861. $this->assertTextNotContains('Content-Type: text/plain; charset=iso-2022-jp-ms', $result['headers']); // not charset=iso-2022-jp-ms
  1862. $this->assertStringContainsString(mb_convert_encoding('①㈱', 'ISO-2022-JP-MS'), $result['message']);
  1863. }
  1864. /**
  1865. * @param array|string $message
  1866. */
  1867. protected function _checkContentTransferEncoding($message, string $charset): bool
  1868. {
  1869. $boundary = '--' . $this->Email->getBoundary();
  1870. $result['text'] = false;
  1871. $result['html'] = false;
  1872. $length = count($message);
  1873. for ($i = 0; $i < $length; ++$i) {
  1874. if ($message[$i] === $boundary) {
  1875. $flag = false;
  1876. $type = '';
  1877. while (!preg_match('/^$/', $message[$i])) {
  1878. if (preg_match('/^Content-Type: text\/plain/', $message[$i])) {
  1879. $type = 'text';
  1880. }
  1881. if (preg_match('/^Content-Type: text\/html/', $message[$i])) {
  1882. $type = 'html';
  1883. }
  1884. if ($message[$i] === 'Content-Transfer-Encoding: ' . $charset) {
  1885. $flag = true;
  1886. }
  1887. ++$i;
  1888. }
  1889. $result[$type] = $flag;
  1890. }
  1891. }
  1892. return $result['text'] && $result['html'];
  1893. }
  1894. /**
  1895. * Test CakeEmail::_encode function
  1896. */
  1897. public function testEncode(): void
  1898. {
  1899. $this->Email->setHeaderCharset('ISO-2022-JP');
  1900. $result = $this->Email->getMessage()->encode('日本語');
  1901. $expected = '=?ISO-2022-JP?B?GyRCRnxLXDhsGyhC?=';
  1902. $this->assertSame($expected, $result);
  1903. $this->Email->setHeaderCharset('ISO-2022-JP');
  1904. $result = $this->Email->getMessage()->encode('長い長い長いSubjectの場合はfoldingするのが正しいんだけどいったいどうなるんだろう?');
  1905. $expected = "=?ISO-2022-JP?B?GyRCRDkkJEQ5JCREOSQkGyhCU3ViamVjdBskQiROPmw5ZyRPGyhCZm9s?=\r\n" .
  1906. " =?ISO-2022-JP?B?ZGluZxskQiQ5JGskTiQsQDUkNyQkJHMkQCQxJEkkJCRDJD8kJCRJGyhC?=\r\n" .
  1907. ' =?ISO-2022-JP?B?GyRCJCYkSiRrJHMkQCRtJCYhKRsoQg==?=';
  1908. $this->assertSame($expected, $result);
  1909. }
  1910. /**
  1911. * Test CakeEmail::_decode function
  1912. */
  1913. public function testDecode(): void
  1914. {
  1915. $this->Email->setHeaderCharset('ISO-2022-JP');
  1916. $result = $this->Email->getMessage()->decode('=?ISO-2022-JP?B?GyRCRnxLXDhsGyhC?=');
  1917. $expected = '日本語';
  1918. $this->assertSame($expected, $result);
  1919. $this->Email->setHeaderCharset('ISO-2022-JP');
  1920. $result = $this->Email->getMessage()->decode("=?ISO-2022-JP?B?GyRCRDkkJEQ5JCREOSQkGyhCU3ViamVjdBskQiROPmw5ZyRPGyhCZm9s?=\r\n" .
  1921. " =?ISO-2022-JP?B?ZGluZxskQiQ5JGskTiQsQDUkNyQkJHMkQCQxJEkkJCRDJD8kJCRJGyhC?=\r\n" .
  1922. ' =?ISO-2022-JP?B?GyRCJCYkSiRrJHMkQCRtJCYhKRsoQg==?=');
  1923. $expected = '長い長い長いSubjectの場合はfoldingするのが正しいんだけどいったいどうなるんだろう?';
  1924. $this->assertSame($expected, $result);
  1925. }
  1926. /**
  1927. * Tests charset setter/getter
  1928. */
  1929. public function testCharset(): void
  1930. {
  1931. $this->Email->setCharset('UTF-8');
  1932. $this->assertSame($this->Email->getCharset(), 'UTF-8');
  1933. $this->Email->setCharset('ISO-2022-JP');
  1934. $this->assertSame($this->Email->getCharset(), 'ISO-2022-JP');
  1935. $charset = $this->Email->setCharset('Shift_JIS');
  1936. $this->assertSame('Shift_JIS', $charset->getCharset());
  1937. }
  1938. /**
  1939. * Tests headerCharset setter/getter
  1940. */
  1941. public function testHeaderCharset(): void
  1942. {
  1943. $this->Email->setHeaderCharset('UTF-8');
  1944. $this->assertSame($this->Email->getHeaderCharset(), 'UTF-8');
  1945. $this->Email->setHeaderCharset('ISO-2022-JP');
  1946. $this->assertSame($this->Email->getHeaderCharset(), 'ISO-2022-JP');
  1947. $charset = $this->Email->setHeaderCharset('Shift_JIS');
  1948. $this->assertSame('Shift_JIS', $charset->getHeaderCharset());
  1949. }
  1950. /**
  1951. * Tests headerCharset on reset
  1952. */
  1953. public function testHeaderCharsetReset(): void
  1954. {
  1955. $email = new Email(['headerCharset' => 'ISO-2022-JP']);
  1956. $email->reset();
  1957. $this->assertSame('utf-8', $email->getCharset());
  1958. $this->assertSame('utf-8', $email->getHeaderCharset());
  1959. }
  1960. /**
  1961. * Test transferEncoding
  1962. */
  1963. public function testTransferEncoding(): void
  1964. {
  1965. // Test new transfer encoding
  1966. $expected = 'quoted-printable';
  1967. $this->Email->setTransferEncoding($expected);
  1968. $this->assertSame($expected, $this->Email->getTransferEncoding());
  1969. $this->assertSame($expected, $this->Email->getContentTransferEncoding());
  1970. // Test default charset/encoding : utf8/8bit
  1971. $expected = '8bit';
  1972. $this->Email->reset();
  1973. $this->assertNull($this->Email->getTransferEncoding());
  1974. $this->assertSame($expected, $this->Email->getContentTransferEncoding());
  1975. //Test wrong encoding
  1976. $this->expectException(\InvalidArgumentException::class);
  1977. $this->Email->setTransferEncoding('invalid');
  1978. }
  1979. /**
  1980. * Tests for compatible check.
  1981. * charset property and charset() method.
  1982. * headerCharset property and headerCharset() method.
  1983. */
  1984. public function testCharsetsCompatible(): void
  1985. {
  1986. $checkHeaders = [
  1987. 'from' => true,
  1988. 'to' => true,
  1989. 'cc' => true,
  1990. 'subject' => true,
  1991. ];
  1992. // Header Charset : null (used by default UTF-8)
  1993. // Body Charset : ISO-2022-JP
  1994. $oldStyleEmail = $this->_getEmailByOldStyleCharset('iso-2022-jp', null);
  1995. $oldStyleHeaders = $oldStyleEmail->getHeaders($checkHeaders);
  1996. $newStyleEmail = $this->_getEmailByNewStyleCharset('iso-2022-jp', null);
  1997. $newStyleHeaders = $newStyleEmail->getHeaders($checkHeaders);
  1998. $this->assertSame($oldStyleHeaders['From'], $newStyleHeaders['From']);
  1999. $this->assertSame($oldStyleHeaders['To'], $newStyleHeaders['To']);
  2000. $this->assertSame($oldStyleHeaders['Cc'], $newStyleHeaders['Cc']);
  2001. $this->assertSame($oldStyleHeaders['Subject'], $newStyleHeaders['Subject']);
  2002. // Header Charset : UTF-8
  2003. // Boby Charset : ISO-2022-JP
  2004. $oldStyleEmail = $this->_getEmailByOldStyleCharset('iso-2022-jp', 'utf-8');
  2005. $oldStyleHeaders = $oldStyleEmail->getHeaders($checkHeaders);
  2006. $newStyleEmail = $this->_getEmailByNewStyleCharset('iso-2022-jp', 'utf-8');
  2007. $newStyleHeaders = $newStyleEmail->getHeaders($checkHeaders);
  2008. $this->assertSame($oldStyleHeaders['From'], $newStyleHeaders['From']);
  2009. $this->assertSame($oldStyleHeaders['To'], $newStyleHeaders['To']);
  2010. $this->assertSame($oldStyleHeaders['Cc'], $newStyleHeaders['Cc']);
  2011. $this->assertSame($oldStyleHeaders['Subject'], $newStyleHeaders['Subject']);
  2012. // Header Charset : ISO-2022-JP
  2013. // Boby Charset : UTF-8
  2014. $oldStyleEmail = $this->_getEmailByOldStyleCharset('utf-8', 'iso-2022-jp');
  2015. $oldStyleHeaders = $oldStyleEmail->getHeaders($checkHeaders);
  2016. $newStyleEmail = $this->_getEmailByNewStyleCharset('utf-8', 'iso-2022-jp');
  2017. $newStyleHeaders = $newStyleEmail->getHeaders($checkHeaders);
  2018. $this->assertSame($oldStyleHeaders['From'], $newStyleHeaders['From']);
  2019. $this->assertSame($oldStyleHeaders['To'], $newStyleHeaders['To']);
  2020. $this->assertSame($oldStyleHeaders['Cc'], $newStyleHeaders['Cc']);
  2021. $this->assertSame($oldStyleHeaders['Subject'], $newStyleHeaders['Subject']);
  2022. }
  2023. /**
  2024. * @param mixed $charset
  2025. * @param mixed $headerCharset
  2026. */
  2027. protected function _getEmailByOldStyleCharset($charset, $headerCharset): Email
  2028. {
  2029. $email = new Email(['transport' => 'debug']);
  2030. if (!empty($charset)) {
  2031. $email->setCharset($charset);
  2032. }
  2033. if (!empty($headerCharset)) {
  2034. $email->setHeaderCharset($headerCharset);
  2035. }
  2036. $email->setFrom('someone@example.com', 'どこかの誰か');
  2037. $email->setTo('someperson@example.jp', 'どこかのどなたか');
  2038. $email->setCc('miku@example.net', 'ミク');
  2039. $email->setSubject('テストメール');
  2040. $email->send('テストメールの本文');
  2041. return $email;
  2042. }
  2043. /**
  2044. * @param mixed $charset
  2045. * @param mixed $headerCharset
  2046. */
  2047. protected function _getEmailByNewStyleCharset($charset, $headerCharset): Email
  2048. {
  2049. $email = new Email(['transport' => 'debug']);
  2050. if (! empty($charset)) {
  2051. $email->setCharset($charset);
  2052. }
  2053. if (! empty($headerCharset)) {
  2054. $email->setHeaderCharset($headerCharset);
  2055. }
  2056. $email->setFrom('someone@example.com', 'どこかの誰か');
  2057. $email->setTo('someperson@example.jp', 'どこかのどなたか');
  2058. $email->setCc('miku@example.net', 'ミク');
  2059. $email->setSubject('テストメール');
  2060. $email->send('テストメールの本文');
  2061. return $email;
  2062. }
  2063. /**
  2064. * testWrapLongLine()
  2065. */
  2066. public function testWrapLongLine(): void
  2067. {
  2068. $message = '<a href="http://cakephp.org">' . str_repeat('x', Message::LINE_LENGTH_MUST) . '</a>';
  2069. $this->Email->reset();
  2070. $this->Email->setTransport('debug');
  2071. $this->Email->setFrom('cake@cakephp.org');
  2072. $this->Email->setTo('cake@cakephp.org');
  2073. $this->Email->setSubject('Wordwrap Test');
  2074. $this->Email->setProfile(['empty']);
  2075. $result = $this->Email->send($message);
  2076. $expected = "<a\r\n" . 'href="http://cakephp.org">' . str_repeat('x', Message::LINE_LENGTH_MUST - 26) . "\r\n" .
  2077. str_repeat('x', 26) . "\r\n</a>\r\n\r\n";
  2078. $this->assertSame($expected, $result['message']);
  2079. $this->assertLineLengths($result['message']);
  2080. $str1 = 'a ';
  2081. $str2 = ' b';
  2082. $length = strlen($str1) + strlen($str2);
  2083. $message = $str1 . str_repeat('x', Message::LINE_LENGTH_MUST - $length - 1) . $str2;
  2084. $result = $this->Email->send($message);
  2085. $expected = "{$message}\r\n\r\n";
  2086. $this->assertSame($expected, $result['message']);
  2087. $this->assertLineLengths($result['message']);
  2088. $message = $str1 . str_repeat('x', Message::LINE_LENGTH_MUST - $length) . $str2;
  2089. $result = $this->Email->send($message);
  2090. $expected = "{$message}\r\n\r\n";
  2091. $this->assertSame($expected, $result['message']);
  2092. $this->assertLineLengths($result['message']);
  2093. $message = $str1 . str_repeat('x', Message::LINE_LENGTH_MUST - $length + 1) . $str2;
  2094. $result = $this->Email->send($message);
  2095. $expected = $str1 . str_repeat('x', Message::LINE_LENGTH_MUST - $length + 1) . sprintf("\r\n%s\r\n\r\n", trim($str2));
  2096. $this->assertSame($expected, $result['message']);
  2097. $this->assertLineLengths($result['message']);
  2098. }
  2099. /**
  2100. * testWrapWithTagsAcrossLines()
  2101. */
  2102. public function testWrapWithTagsAcrossLines(): void
  2103. {
  2104. $str = <<<HTML
  2105. <table>
  2106. <th align="right" valign="top"
  2107. style="font-weight: bold">The tag is across multiple lines</th>
  2108. </table>
  2109. HTML;
  2110. $message = $str . str_repeat('x', Message::LINE_LENGTH_MUST + 1);
  2111. $this->Email->reset();
  2112. $this->Email->setTransport('debug');
  2113. $this->Email->setFrom('cake@cakephp.org');
  2114. $this->Email->setTo('cake@cakephp.org');
  2115. $this->Email->setSubject('Wordwrap Test');
  2116. $this->Email->setProfile(['empty']);
  2117. $result = $this->Email->send($message);
  2118. $message = str_replace("\r\n", "\n", substr($message, 0, -9));
  2119. $message = str_replace("\n", "\r\n", $message);
  2120. $expected = "{$message}\r\nxxxxxxxxx\r\n\r\n";
  2121. $this->assertSame($expected, $result['message']);
  2122. $this->assertLineLengths($result['message']);
  2123. }
  2124. /**
  2125. * CakeEmailTest::testWrapIncludeLessThanSign()
  2126. */
  2127. public function testWrapIncludeLessThanSign(): void
  2128. {
  2129. $str = 'foo<bar';
  2130. $length = strlen($str);
  2131. $message = $str . str_repeat('x', Message::LINE_LENGTH_MUST - $length + 1);
  2132. $this->Email->reset();
  2133. $this->Email->setTransport('debug');
  2134. $this->Email->setFrom('cake@cakephp.org');
  2135. $this->Email->setTo('cake@cakephp.org');
  2136. $this->Email->setSubject('Wordwrap Test');
  2137. $this->Email->setProfile(['empty']);
  2138. $result = $this->Email->send($message);
  2139. $message = substr($message, 0, -1);
  2140. $expected = "{$message}\r\nx\r\n\r\n";
  2141. $this->assertSame($expected, $result['message']);
  2142. $this->assertLineLengths($result['message']);
  2143. }
  2144. /**
  2145. * CakeEmailTest::testWrapForJapaneseEncoding()
  2146. */
  2147. public function testWrapForJapaneseEncoding(): void
  2148. {
  2149. $this->skipIf(!function_exists('mb_convert_encoding'));
  2150. $message = mb_convert_encoding('受け付けました', 'iso-2022-jp', 'UTF-8');
  2151. $this->Email->reset();
  2152. $this->Email->setTransport('debug');
  2153. $this->Email->setFrom('cake@cakephp.org');
  2154. $this->Email->setTo('cake@cakephp.org');
  2155. $this->Email->setSubject('Wordwrap Test');
  2156. $this->Email->setProfile(['empty']);
  2157. $this->Email->setCharset('iso-2022-jp');
  2158. $this->Email->setHeaderCharset('iso-2022-jp');
  2159. $result = $this->Email->send($message);
  2160. $expected = "{$message}\r\n\r\n";
  2161. $this->assertSame($expected, $result['message']);
  2162. }
  2163. /**
  2164. * CakeEmailTest::testMockTransport()
  2165. */
  2166. public function testMockTransport(): void
  2167. {
  2168. TransportFactory::drop('default');
  2169. $mock = $this->getMockBuilder('Cake\Mailer\AbstractTransport')->getMock();
  2170. $config = ['from' => 'tester@example.org', 'transport' => 'default'];
  2171. Email::setConfig('default', $config);
  2172. TransportFactory::setConfig('default', $mock);
  2173. $em = new Email('default');
  2174. $this->assertSame($mock, $em->getTransport());
  2175. }
  2176. /**
  2177. * testZeroOnlyLinesNotBeingEmptied()
  2178. */
  2179. public function testZeroOnlyLinesNotBeingEmptied(): void
  2180. {
  2181. $message = "Lorem\r\n0\r\n0\r\nipsum";
  2182. $this->Email->reset();
  2183. $this->Email->setTransport('debug');
  2184. $this->Email->setFrom('cake@cakephp.org');
  2185. $this->Email->setTo('cake@cakephp.org');
  2186. $this->Email->setSubject('Wordwrap Test');
  2187. $result = $this->Email->send($message);
  2188. $expected = "{$message}\r\n\r\n";
  2189. $this->assertSame($expected, $result['message']);
  2190. }
  2191. /**
  2192. * testJsonSerialize()
  2193. */
  2194. public function testJsonSerialize(): void
  2195. {
  2196. $xmlstr = <<<XML
  2197. <?xml version='1.0' standalone='yes'?>
  2198. <framework>
  2199. <name>CakePHP</name>
  2200. <url>http://cakephp.org</url>
  2201. </framework>
  2202. XML;
  2203. $this->Email->reset()
  2204. ->setTo(['cakephp@cakephp.org' => 'CakePHP'])
  2205. ->setFrom('noreply@cakephp.org')
  2206. ->setReplyTo('cakephp@cakephp.org')
  2207. ->setCc(['mark@cakephp.org', 'juan@cakephp.org' => 'Juan Basso'])
  2208. ->setBcc('phpnut@cakephp.org')
  2209. ->setSubject('Test Serialize')
  2210. ->setMessageId('<uuid@server.com>')
  2211. ->setDomain('foo.bar')
  2212. ->setViewVars([
  2213. 'users' => $this->getTableLocator()->get('Users')->get(1, ['fields' => ['id', 'username']]),
  2214. 'xml' => new SimpleXmlElement($xmlstr),
  2215. 'exception' => new Exception('test'),
  2216. ])
  2217. ->setAttachments([
  2218. 'test.txt' => TEST_APP . 'config' . DS . 'empty.ini',
  2219. 'image' => [
  2220. 'data' => file_get_contents(TEST_APP . 'webroot' . DS . 'img' . DS . 'cake.icon.png'),
  2221. 'mimetype' => 'image/png',
  2222. ],
  2223. ]);
  2224. $this->Email->viewBuilder()
  2225. ->setTemplate('default')
  2226. ->setLayout('test');
  2227. $result = json_decode(json_encode($this->Email), true);
  2228. $this->assertStringContainsString('test', $result['viewConfig']['_vars']['exception']);
  2229. unset($result['viewConfig']['_vars']['exception']);
  2230. $encode = function ($path) {
  2231. return chunk_split(base64_encode(file_get_contents($path)), 76, "\r\n");
  2232. };
  2233. $expected = [
  2234. 'to' => ['cakephp@cakephp.org' => 'CakePHP'],
  2235. 'from' => ['noreply@cakephp.org' => 'noreply@cakephp.org'],
  2236. 'replyTo' => ['cakephp@cakephp.org' => 'cakephp@cakephp.org'],
  2237. 'cc' => ['mark@cakephp.org' => 'mark@cakephp.org', 'juan@cakephp.org' => 'Juan Basso'],
  2238. 'bcc' => ['phpnut@cakephp.org' => 'phpnut@cakephp.org'],
  2239. 'subject' => 'Test Serialize',
  2240. 'emailFormat' => 'text',
  2241. 'messageId' => '<uuid@server.com>',
  2242. 'domain' => 'foo.bar',
  2243. 'appCharset' => 'UTF-8',
  2244. 'charset' => 'utf-8',
  2245. 'viewConfig' => [
  2246. '_template' => 'default',
  2247. '_layout' => 'test',
  2248. '_helpers' => ['Html'],
  2249. '_className' => 'Cake\View\View',
  2250. '_autoLayout' => true,
  2251. '_vars' => [
  2252. 'users' => [
  2253. 'id' => 1,
  2254. 'username' => 'mariano',
  2255. ],
  2256. 'xml' => [
  2257. 'name' => 'CakePHP',
  2258. 'url' => 'http://cakephp.org',
  2259. ],
  2260. ],
  2261. ],
  2262. 'attachments' => [
  2263. 'test.txt' => [
  2264. 'data' => $encode(TEST_APP . 'config' . DS . 'empty.ini'),
  2265. 'mimetype' => 'text/plain',
  2266. ],
  2267. 'image' => [
  2268. 'data' => $encode(TEST_APP . 'webroot' . DS . 'img' . DS . 'cake.icon.png'),
  2269. 'mimetype' => 'image/png',
  2270. ],
  2271. ],
  2272. 'emailPattern' => '/^((?:[\p{L}0-9.!#$%&\'*+\/=?^_`{|}~-]+)*@[\p{L}0-9-._]+)$/ui',
  2273. ];
  2274. $this->assertEquals($expected, $result);
  2275. $result = json_decode(json_encode(unserialize(serialize($this->Email))), true);
  2276. $this->assertStringContainsString('test', $result['viewConfig']['_vars']['exception']);
  2277. unset($result['viewConfig']['_vars']['exception']);
  2278. $this->assertEquals($expected, $result);
  2279. }
  2280. /**
  2281. * testStaticMethodProxy
  2282. */
  2283. public function testStaticMethodProxy(): void
  2284. {
  2285. Email::setConfig('proxy_test', ['yay']);
  2286. $this->assertEquals(['yay'], Mailer::getConfig('proxy_test'));
  2287. Email::drop('proxy_test');
  2288. $this->assertSame([], Mailer::configured());
  2289. }
  2290. /**
  2291. * CakeEmailTest::assertLineLengths()
  2292. *
  2293. * @param string $message
  2294. */
  2295. public function assertLineLengths($message): void
  2296. {
  2297. $lines = explode("\r\n", $message);
  2298. foreach ($lines as $line) {
  2299. $this->assertTrue(
  2300. strlen($line) <= Message::LINE_LENGTH_MUST,
  2301. 'Line length exceeds the max. limit of Message::LINE_LENGTH_MUST'
  2302. );
  2303. }
  2304. }
  2305. }