Email.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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. public function addPart(DataPart $part): static
  315. {
  316. $this->cachedBody = null;
  317. $this->attachments[] = $part;
  318. return $this;
  319. }
  320. /**
  321. * @return DataPart[]
  322. */
  323. public function getAttachments(): array
  324. {
  325. return $this->attachments;
  326. }
  327. public function getBody(): AbstractPart
  328. {
  329. if (null !== $body = parent::getBody()) {
  330. return $body;
  331. }
  332. return $this->generateBody();
  333. }
  334. public function ensureValidity(): void
  335. {
  336. $this->ensureBodyValid();
  337. if ('1' === $this->getHeaders()->getHeaderBody('X-Unsent')) {
  338. throw new LogicException('Cannot send messages marked as "draft".');
  339. }
  340. parent::ensureValidity();
  341. }
  342. private function ensureBodyValid(): void
  343. {
  344. if (null === $this->text && null === $this->html && !$this->attachments) {
  345. throw new LogicException('A message must have a text or an HTML part or attachments.');
  346. }
  347. }
  348. /**
  349. * Generates an AbstractPart based on the raw body of a message.
  350. *
  351. * The most "complex" part generated by this method is when there is text and HTML bodies
  352. * with related images for the HTML part and some attachments:
  353. *
  354. * multipart/mixed
  355. * |
  356. * |------------> multipart/related
  357. * | |
  358. * | |------------> multipart/alternative
  359. * | | |
  360. * | | ------------> text/plain (with content)
  361. * | | |
  362. * | | ------------> text/html (with content)
  363. * | |
  364. * | ------------> image/png (with content)
  365. * |
  366. * ------------> application/pdf (with content)
  367. */
  368. private function generateBody(): AbstractPart
  369. {
  370. if (null !== $this->cachedBody) {
  371. return $this->cachedBody;
  372. }
  373. $this->ensureBodyValid();
  374. [$htmlPart, $otherParts, $relatedParts] = $this->prepareParts();
  375. $part = null === $this->text ? null : new TextPart($this->text, $this->textCharset);
  376. if (null !== $htmlPart) {
  377. if (null !== $part) {
  378. $part = new AlternativePart($part, $htmlPart);
  379. } else {
  380. $part = $htmlPart;
  381. }
  382. }
  383. if ($relatedParts) {
  384. $part = new RelatedPart($part, ...$relatedParts);
  385. }
  386. if ($otherParts) {
  387. if ($part) {
  388. $part = new MixedPart($part, ...$otherParts);
  389. } else {
  390. $part = new MixedPart(...$otherParts);
  391. }
  392. }
  393. return $this->cachedBody = $part;
  394. }
  395. private function prepareParts(): ?array
  396. {
  397. $names = [];
  398. $htmlPart = null;
  399. $html = $this->html;
  400. if (null !== $html) {
  401. $htmlPart = new TextPart($html, $this->htmlCharset, 'html');
  402. $html = $htmlPart->getBody();
  403. $regexes = [
  404. '<img\s+[^>]*src\s*=\s*(?:([\'"])cid:(.+?)\\1|cid:([^>\s]+))',
  405. '<\w+\s+[^>]*background\s*=\s*(?:([\'"])cid:(.+?)\\1|cid:([^>\s]+))',
  406. ];
  407. $tmpMatches = [];
  408. foreach ($regexes as $regex) {
  409. preg_match_all('/'.$regex.'/i', $html, $tmpMatches);
  410. $names = array_merge($names, $tmpMatches[2], $tmpMatches[3]);
  411. }
  412. $names = array_filter(array_unique($names));
  413. }
  414. $otherParts = $relatedParts = [];
  415. foreach ($this->attachments as $part) {
  416. foreach ($names as $name) {
  417. if ($name !== $part->getName() && (!$part->hasContentId() || $name !== $part->getContentId())) {
  418. continue;
  419. }
  420. if (isset($relatedParts[$name])) {
  421. continue 2;
  422. }
  423. if ($name !== $part->getContentId()) {
  424. $html = str_replace('cid:'.$name, 'cid:'.$part->getContentId(), $html, $count);
  425. }
  426. $relatedParts[$name] = $part;
  427. $part->setName($part->getContentId())->asInline();
  428. continue 2;
  429. }
  430. $otherParts[] = $part;
  431. }
  432. if (null !== $htmlPart) {
  433. $htmlPart = new TextPart($html, $this->htmlCharset, 'html');
  434. }
  435. return [$htmlPart, $otherParts, array_values($relatedParts)];
  436. }
  437. /**
  438. * @return $this
  439. */
  440. private function setHeaderBody(string $type, string $name, $body): static
  441. {
  442. $this->getHeaders()->setHeaderBody($type, $name, $body);
  443. return $this;
  444. }
  445. /**
  446. * @return $this
  447. */
  448. private function addListAddressHeaderBody(string $name, array $addresses): static
  449. {
  450. if (!$header = $this->getHeaders()->get($name)) {
  451. return $this->setListAddressHeaderBody($name, $addresses);
  452. }
  453. $header->addAddresses(Address::createArray($addresses));
  454. return $this;
  455. }
  456. /**
  457. * @return $this
  458. */
  459. private function setListAddressHeaderBody(string $name, array $addresses): static
  460. {
  461. $addresses = Address::createArray($addresses);
  462. $headers = $this->getHeaders();
  463. if ($header = $headers->get($name)) {
  464. $header->setAddresses($addresses);
  465. } else {
  466. $headers->addMailboxListHeader($name, $addresses);
  467. }
  468. return $this;
  469. }
  470. /**
  471. * @internal
  472. */
  473. public function __serialize(): array
  474. {
  475. if (\is_resource($this->text)) {
  476. $this->text = (new TextPart($this->text))->getBody();
  477. }
  478. if (\is_resource($this->html)) {
  479. $this->html = (new TextPart($this->html))->getBody();
  480. }
  481. return [$this->text, $this->textCharset, $this->html, $this->htmlCharset, $this->attachments, parent::__serialize()];
  482. }
  483. /**
  484. * @internal
  485. */
  486. public function __unserialize(array $data): void
  487. {
  488. [$this->text, $this->textCharset, $this->html, $this->htmlCharset, $this->attachments, $parentData] = $data;
  489. parent::__unserialize($parentData);
  490. }
  491. }