Email.php 15 KB

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