Email.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Mime;
  11. use Symfony\Component\Mime\Exception\LogicException;
  12. use Symfony\Component\Mime\Part\AbstractPart;
  13. use Symfony\Component\Mime\Part\DataPart;
  14. use Symfony\Component\Mime\Part\Multipart\AlternativePart;
  15. use Symfony\Component\Mime\Part\Multipart\MixedPart;
  16. use Symfony\Component\Mime\Part\Multipart\RelatedPart;
  17. use Symfony\Component\Mime\Part\TextPart;
  18. /**
  19. * @author Fabien Potencier <fabien@symfony.com>
  20. */
  21. class Email extends Message
  22. {
  23. public const PRIORITY_HIGHEST = 1;
  24. public const PRIORITY_HIGH = 2;
  25. public const PRIORITY_NORMAL = 3;
  26. public const PRIORITY_LOW = 4;
  27. public const PRIORITY_LOWEST = 5;
  28. private const PRIORITY_MAP = [
  29. self::PRIORITY_HIGHEST => 'Highest',
  30. self::PRIORITY_HIGH => 'High',
  31. self::PRIORITY_NORMAL => 'Normal',
  32. self::PRIORITY_LOW => 'Low',
  33. self::PRIORITY_LOWEST => 'Lowest',
  34. ];
  35. private $text;
  36. private $textCharset;
  37. private $html;
  38. private $htmlCharset;
  39. private $attachments = [];
  40. /**
  41. * @var AbstractPart|null
  42. */
  43. private $cachedBody; // Used to avoid wrong body hash in DKIM signatures with multiple parts (e.g. HTML + TEXT) due to multiple boundaries.
  44. /**
  45. * @return $this
  46. */
  47. public function subject(string $subject)
  48. {
  49. return $this->setHeaderBody('Text', 'Subject', $subject);
  50. }
  51. public function getSubject(): ?string
  52. {
  53. return $this->getHeaders()->getHeaderBody('Subject');
  54. }
  55. /**
  56. * @return $this
  57. */
  58. public function date(\DateTimeInterface $dateTime)
  59. {
  60. return $this->setHeaderBody('Date', 'Date', $dateTime);
  61. }
  62. public function getDate(): ?\DateTimeImmutable
  63. {
  64. return $this->getHeaders()->getHeaderBody('Date');
  65. }
  66. /**
  67. * @param Address|string $address
  68. *
  69. * @return $this
  70. */
  71. public function returnPath($address)
  72. {
  73. return $this->setHeaderBody('Path', 'Return-Path', Address::create($address));
  74. }
  75. public function getReturnPath(): ?Address
  76. {
  77. return $this->getHeaders()->getHeaderBody('Return-Path');
  78. }
  79. /**
  80. * @param Address|string $address
  81. *
  82. * @return $this
  83. */
  84. public function sender($address)
  85. {
  86. return $this->setHeaderBody('Mailbox', 'Sender', Address::create($address));
  87. }
  88. public function getSender(): ?Address
  89. {
  90. return $this->getHeaders()->getHeaderBody('Sender');
  91. }
  92. /**
  93. * @param Address|string ...$addresses
  94. *
  95. * @return $this
  96. */
  97. public function addFrom(...$addresses)
  98. {
  99. return $this->addListAddressHeaderBody('From', $addresses);
  100. }
  101. /**
  102. * @param Address|string ...$addresses
  103. *
  104. * @return $this
  105. */
  106. public function from(...$addresses)
  107. {
  108. return $this->setListAddressHeaderBody('From', $addresses);
  109. }
  110. /**
  111. * @return Address[]
  112. */
  113. public function getFrom(): array
  114. {
  115. return $this->getHeaders()->getHeaderBody('From') ?: [];
  116. }
  117. /**
  118. * @param Address|string ...$addresses
  119. *
  120. * @return $this
  121. */
  122. public function addReplyTo(...$addresses)
  123. {
  124. return $this->addListAddressHeaderBody('Reply-To', $addresses);
  125. }
  126. /**
  127. * @param Address|string ...$addresses
  128. *
  129. * @return $this
  130. */
  131. public function replyTo(...$addresses)
  132. {
  133. return $this->setListAddressHeaderBody('Reply-To', $addresses);
  134. }
  135. /**
  136. * @return Address[]
  137. */
  138. public function getReplyTo(): array
  139. {
  140. return $this->getHeaders()->getHeaderBody('Reply-To') ?: [];
  141. }
  142. /**
  143. * @param Address|string ...$addresses
  144. *
  145. * @return $this
  146. */
  147. public function addTo(...$addresses)
  148. {
  149. return $this->addListAddressHeaderBody('To', $addresses);
  150. }
  151. /**
  152. * @param Address|string ...$addresses
  153. *
  154. * @return $this
  155. */
  156. public function to(...$addresses)
  157. {
  158. return $this->setListAddressHeaderBody('To', $addresses);
  159. }
  160. /**
  161. * @return Address[]
  162. */
  163. public function getTo(): array
  164. {
  165. return $this->getHeaders()->getHeaderBody('To') ?: [];
  166. }
  167. /**
  168. * @param Address|string ...$addresses
  169. *
  170. * @return $this
  171. */
  172. public function addCc(...$addresses)
  173. {
  174. return $this->addListAddressHeaderBody('Cc', $addresses);
  175. }
  176. /**
  177. * @param Address|string ...$addresses
  178. *
  179. * @return $this
  180. */
  181. public function cc(...$addresses)
  182. {
  183. return $this->setListAddressHeaderBody('Cc', $addresses);
  184. }
  185. /**
  186. * @return Address[]
  187. */
  188. public function getCc(): array
  189. {
  190. return $this->getHeaders()->getHeaderBody('Cc') ?: [];
  191. }
  192. /**
  193. * @param Address|string ...$addresses
  194. *
  195. * @return $this
  196. */
  197. public function addBcc(...$addresses)
  198. {
  199. return $this->addListAddressHeaderBody('Bcc', $addresses);
  200. }
  201. /**
  202. * @param Address|string ...$addresses
  203. *
  204. * @return $this
  205. */
  206. public function bcc(...$addresses)
  207. {
  208. return $this->setListAddressHeaderBody('Bcc', $addresses);
  209. }
  210. /**
  211. * @return Address[]
  212. */
  213. public function getBcc(): array
  214. {
  215. return $this->getHeaders()->getHeaderBody('Bcc') ?: [];
  216. }
  217. /**
  218. * Sets the priority of this message.
  219. *
  220. * The value is an integer where 1 is the highest priority and 5 is the lowest.
  221. *
  222. * @return $this
  223. */
  224. public function priority(int $priority)
  225. {
  226. if ($priority > 5) {
  227. $priority = 5;
  228. } elseif ($priority < 1) {
  229. $priority = 1;
  230. }
  231. return $this->setHeaderBody('Text', 'X-Priority', sprintf('%d (%s)', $priority, self::PRIORITY_MAP[$priority]));
  232. }
  233. /**
  234. * Get the priority of this message.
  235. *
  236. * The returned value is an integer where 1 is the highest priority and 5
  237. * is the lowest.
  238. */
  239. public function getPriority(): int
  240. {
  241. [$priority] = sscanf($this->getHeaders()->getHeaderBody('X-Priority') ?? '', '%[1-5]');
  242. return $priority ?? 3;
  243. }
  244. /**
  245. * @param resource|string|null $body
  246. *
  247. * @return $this
  248. */
  249. public function text($body, string $charset = 'utf-8')
  250. {
  251. if (null !== $body && !\is_string($body) && !\is_resource($body)) {
  252. throw new \TypeError(sprintf('The body must be a string, a resource or null (got "%s").', get_debug_type($body)));
  253. }
  254. $this->cachedBody = null;
  255. $this->text = $body;
  256. $this->textCharset = $charset;
  257. return $this;
  258. }
  259. /**
  260. * @return resource|string|null
  261. */
  262. public function getTextBody()
  263. {
  264. return $this->text;
  265. }
  266. public function getTextCharset(): ?string
  267. {
  268. return $this->textCharset;
  269. }
  270. /**
  271. * @param resource|string|null $body
  272. *
  273. * @return $this
  274. */
  275. public function html($body, string $charset = 'utf-8')
  276. {
  277. if (null !== $body && !\is_string($body) && !\is_resource($body)) {
  278. throw new \TypeError(sprintf('The body must be a string, a resource or null (got "%s").', get_debug_type($body)));
  279. }
  280. $this->cachedBody = null;
  281. $this->html = $body;
  282. $this->htmlCharset = $charset;
  283. return $this;
  284. }
  285. /**
  286. * @return resource|string|null
  287. */
  288. public function getHtmlBody()
  289. {
  290. return $this->html;
  291. }
  292. public function getHtmlCharset(): ?string
  293. {
  294. return $this->htmlCharset;
  295. }
  296. /**
  297. * @param resource|string $body
  298. *
  299. * @return $this
  300. */
  301. public function attach($body, string $name = null, string $contentType = null)
  302. {
  303. if (!\is_string($body) && !\is_resource($body)) {
  304. throw new \TypeError(sprintf('The body must be a string or a resource (got "%s").', get_debug_type($body)));
  305. }
  306. $this->cachedBody = null;
  307. $this->attachments[] = ['body' => $body, 'name' => $name, 'content-type' => $contentType, 'inline' => false];
  308. return $this;
  309. }
  310. /**
  311. * @return $this
  312. */
  313. public function attachFromPath(string $path, string $name = null, string $contentType = null)
  314. {
  315. $this->cachedBody = null;
  316. $this->attachments[] = ['path' => $path, 'name' => $name, 'content-type' => $contentType, 'inline' => false];
  317. return $this;
  318. }
  319. /**
  320. * @param resource|string $body
  321. *
  322. * @return $this
  323. */
  324. public function embed($body, string $name = null, string $contentType = null)
  325. {
  326. if (!\is_string($body) && !\is_resource($body)) {
  327. throw new \TypeError(sprintf('The body must be a string or a resource (got "%s").', get_debug_type($body)));
  328. }
  329. $this->cachedBody = null;
  330. $this->attachments[] = ['body' => $body, 'name' => $name, 'content-type' => $contentType, 'inline' => true];
  331. return $this;
  332. }
  333. /**
  334. * @return $this
  335. */
  336. public function embedFromPath(string $path, string $name = null, string $contentType = null)
  337. {
  338. $this->cachedBody = null;
  339. $this->attachments[] = ['path' => $path, 'name' => $name, 'content-type' => $contentType, 'inline' => true];
  340. return $this;
  341. }
  342. /**
  343. * @return $this
  344. */
  345. public function attachPart(DataPart $part)
  346. {
  347. $this->cachedBody = null;
  348. $this->attachments[] = ['part' => $part];
  349. return $this;
  350. }
  351. /**
  352. * @return array|DataPart[]
  353. */
  354. public function getAttachments(): array
  355. {
  356. $parts = [];
  357. foreach ($this->attachments as $attachment) {
  358. $parts[] = $this->createDataPart($attachment);
  359. }
  360. return $parts;
  361. }
  362. public function getBody(): AbstractPart
  363. {
  364. if (null !== $body = parent::getBody()) {
  365. return $body;
  366. }
  367. return $this->generateBody();
  368. }
  369. public function ensureValidity()
  370. {
  371. if (null === $this->text && null === $this->html && !$this->attachments) {
  372. throw new LogicException('A message must have a text or an HTML part or attachments.');
  373. }
  374. parent::ensureValidity();
  375. }
  376. /**
  377. * Generates an AbstractPart based on the raw body of a message.
  378. *
  379. * The most "complex" part generated by this method is when there is text and HTML bodies
  380. * with related images for the HTML part and some attachments:
  381. *
  382. * multipart/mixed
  383. * |
  384. * |------------> multipart/related
  385. * | |
  386. * | |------------> multipart/alternative
  387. * | | |
  388. * | | ------------> text/plain (with content)
  389. * | | |
  390. * | | ------------> text/html (with content)
  391. * | |
  392. * | ------------> image/png (with content)
  393. * |
  394. * ------------> application/pdf (with content)
  395. */
  396. private function generateBody(): AbstractPart
  397. {
  398. if (null !== $this->cachedBody) {
  399. return $this->cachedBody;
  400. }
  401. $this->ensureValidity();
  402. [$htmlPart, $otherParts, $relatedParts] = $this->prepareParts();
  403. $part = null === $this->text ? null : new TextPart($this->text, $this->textCharset);
  404. if (null !== $htmlPart) {
  405. if (null !== $part) {
  406. $part = new AlternativePart($part, $htmlPart);
  407. } else {
  408. $part = $htmlPart;
  409. }
  410. }
  411. if ($relatedParts) {
  412. $part = new RelatedPart($part, ...$relatedParts);
  413. }
  414. if ($otherParts) {
  415. if ($part) {
  416. $part = new MixedPart($part, ...$otherParts);
  417. } else {
  418. $part = new MixedPart(...$otherParts);
  419. }
  420. }
  421. return $this->cachedBody = $part;
  422. }
  423. private function prepareParts(): ?array
  424. {
  425. $names = [];
  426. $htmlPart = null;
  427. $html = $this->html;
  428. if (null !== $html) {
  429. $htmlPart = new TextPart($html, $this->htmlCharset, 'html');
  430. $html = $htmlPart->getBody();
  431. preg_match_all('(<img\s+[^>]*src\s*=\s*(?:([\'"])cid:(.+?)\\1|cid:([^>\s]+)))i', $html, $names);
  432. $names = array_filter(array_unique(array_merge($names[2], $names[3])));
  433. }
  434. // usage of reflection is a temporary workaround for missing getters that will be added in 6.2
  435. $nameRef = new \ReflectionProperty(TextPart::class, 'name');
  436. $nameRef->setAccessible(true);
  437. $otherParts = $relatedParts = [];
  438. foreach ($this->attachments as $attachment) {
  439. $part = $this->createDataPart($attachment);
  440. if (isset($attachment['part'])) {
  441. $attachment['name'] = $nameRef->getValue($part);
  442. }
  443. $related = false;
  444. foreach ($names as $name) {
  445. if ($name !== $attachment['name']) {
  446. continue;
  447. }
  448. if (isset($relatedParts[$name])) {
  449. continue 2;
  450. }
  451. $part->setDisposition('inline');
  452. $html = str_replace('cid:'.$name, 'cid:'.$part->getContentId(), $html, $count);
  453. if ($count) {
  454. $related = true;
  455. }
  456. $part->setName($part->getContentId());
  457. break;
  458. }
  459. if ($related) {
  460. $relatedParts[$attachment['name']] = $part;
  461. } else {
  462. $otherParts[] = $part;
  463. }
  464. }
  465. if (null !== $htmlPart) {
  466. $htmlPart = new TextPart($html, $this->htmlCharset, 'html');
  467. }
  468. return [$htmlPart, $otherParts, array_values($relatedParts)];
  469. }
  470. private function createDataPart(array $attachment): DataPart
  471. {
  472. if (isset($attachment['part'])) {
  473. return $attachment['part'];
  474. }
  475. if (isset($attachment['body'])) {
  476. $part = new DataPart($attachment['body'], $attachment['name'] ?? null, $attachment['content-type'] ?? null);
  477. } else {
  478. $part = DataPart::fromPath($attachment['path'] ?? '', $attachment['name'] ?? null, $attachment['content-type'] ?? null);
  479. }
  480. if ($attachment['inline']) {
  481. $part->asInline();
  482. }
  483. return $part;
  484. }
  485. /**
  486. * @return $this
  487. */
  488. private function setHeaderBody(string $type, string $name, $body): object
  489. {
  490. $this->getHeaders()->setHeaderBody($type, $name, $body);
  491. return $this;
  492. }
  493. private function addListAddressHeaderBody(string $name, array $addresses)
  494. {
  495. if (!$header = $this->getHeaders()->get($name)) {
  496. return $this->setListAddressHeaderBody($name, $addresses);
  497. }
  498. $header->addAddresses(Address::createArray($addresses));
  499. return $this;
  500. }
  501. /**
  502. * @return $this
  503. */
  504. private function setListAddressHeaderBody(string $name, array $addresses)
  505. {
  506. $addresses = Address::createArray($addresses);
  507. $headers = $this->getHeaders();
  508. if ($header = $headers->get($name)) {
  509. $header->setAddresses($addresses);
  510. } else {
  511. $headers->addMailboxListHeader($name, $addresses);
  512. }
  513. return $this;
  514. }
  515. /**
  516. * @internal
  517. */
  518. public function __serialize(): array
  519. {
  520. if (\is_resource($this->text)) {
  521. $this->text = (new TextPart($this->text))->getBody();
  522. }
  523. if (\is_resource($this->html)) {
  524. $this->html = (new TextPart($this->html))->getBody();
  525. }
  526. foreach ($this->attachments as $i => $attachment) {
  527. if (isset($attachment['body']) && \is_resource($attachment['body'])) {
  528. $this->attachments[$i]['body'] = (new TextPart($attachment['body']))->getBody();
  529. }
  530. }
  531. return [$this->text, $this->textCharset, $this->html, $this->htmlCharset, $this->attachments, parent::__serialize()];
  532. }
  533. /**
  534. * @internal
  535. */
  536. public function __unserialize(array $data): void
  537. {
  538. [$this->text, $this->textCharset, $this->html, $this->htmlCharset, $this->attachments, $parentData] = $data;
  539. parent::__unserialize($parentData);
  540. }
  541. }