Email.php 15 KB

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