Email.php 16 KB

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