Email.php 16 KB

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