Email.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  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. const PRIORITY_HIGHEST = 1;
  24. const PRIORITY_HIGH = 2;
  25. const PRIORITY_NORMAL = 3;
  26. const PRIORITY_LOW = 4;
  27. 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. list($priority) = sscanf($this->getHeaders()->getHeaderBody('X-Priority'), '%[1-5]');
  238. return $priority ?? 3;
  239. }
  240. /**
  241. * @param resource|string $body
  242. *
  243. * @return $this
  244. */
  245. public function text($body, string $charset = 'utf-8')
  246. {
  247. $this->text = $body;
  248. $this->textCharset = $charset;
  249. return $this;
  250. }
  251. /**
  252. * @return resource|string|null
  253. */
  254. public function getTextBody()
  255. {
  256. return $this->text;
  257. }
  258. public function getTextCharset(): ?string
  259. {
  260. return $this->textCharset;
  261. }
  262. /**
  263. * @param resource|string|null $body
  264. *
  265. * @return $this
  266. */
  267. public function html($body, string $charset = 'utf-8')
  268. {
  269. $this->html = $body;
  270. $this->htmlCharset = $charset;
  271. return $this;
  272. }
  273. /**
  274. * @return resource|string|null
  275. */
  276. public function getHtmlBody()
  277. {
  278. return $this->html;
  279. }
  280. public function getHtmlCharset(): ?string
  281. {
  282. return $this->htmlCharset;
  283. }
  284. /**
  285. * @param resource|string $body
  286. *
  287. * @return $this
  288. */
  289. public function attach($body, string $name = null, string $contentType = null)
  290. {
  291. $this->attachments[] = ['body' => $body, 'name' => $name, 'content-type' => $contentType, 'inline' => false];
  292. return $this;
  293. }
  294. /**
  295. * @return $this
  296. */
  297. public function attachFromPath(string $path, string $name = null, string $contentType = null)
  298. {
  299. $this->attachments[] = ['path' => $path, 'name' => $name, 'content-type' => $contentType, 'inline' => false];
  300. return $this;
  301. }
  302. /**
  303. * @param resource|string $body
  304. *
  305. * @return $this
  306. */
  307. public function embed($body, string $name = null, string $contentType = null)
  308. {
  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)
  316. {
  317. $this->attachments[] = ['path' => $path, 'name' => $name, 'content-type' => $contentType, 'inline' => true];
  318. return $this;
  319. }
  320. /**
  321. * @return $this
  322. */
  323. public function attachPart(DataPart $part)
  324. {
  325. $this->attachments[] = ['part' => $part];
  326. return $this;
  327. }
  328. /**
  329. * @return DataPart[]
  330. */
  331. public function getAttachments(): array
  332. {
  333. $parts = [];
  334. foreach ($this->attachments as $attachment) {
  335. $parts[] = $this->createDataPart($attachment);
  336. }
  337. return $parts;
  338. }
  339. public function getBody(): AbstractPart
  340. {
  341. if (null !== $body = parent::getBody()) {
  342. return $body;
  343. }
  344. return $this->generateBody();
  345. }
  346. public function ensureValidity()
  347. {
  348. if (null === $this->text && null === $this->html && !$this->attachments) {
  349. throw new LogicException('A message must have a text or an HTML part or attachments.');
  350. }
  351. parent::ensureValidity();
  352. }
  353. /**
  354. * Generates an AbstractPart based on the raw body of a message.
  355. *
  356. * The most "complex" part generated by this method is when there is text and HTML bodies
  357. * with related images for the HTML part and some attachments:
  358. *
  359. * multipart/mixed
  360. * |
  361. * |------------> multipart/related
  362. * | |
  363. * | |------------> multipart/alternative
  364. * | | |
  365. * | | ------------> text/plain (with content)
  366. * | | |
  367. * | | ------------> text/html (with content)
  368. * | |
  369. * | ------------> image/png (with content)
  370. * |
  371. * ------------> application/pdf (with content)
  372. */
  373. private function generateBody(): AbstractPart
  374. {
  375. $this->ensureValidity();
  376. [$htmlPart, $attachmentParts, $inlineParts] = $this->prepareParts();
  377. $part = null === $this->text ? null : new TextPart($this->text, $this->textCharset);
  378. if (null !== $htmlPart) {
  379. if (null !== $part) {
  380. $part = new AlternativePart($part, $htmlPart);
  381. } else {
  382. $part = $htmlPart;
  383. }
  384. }
  385. if ($inlineParts) {
  386. $part = new RelatedPart($part, ...$inlineParts);
  387. }
  388. if ($attachmentParts) {
  389. if ($part) {
  390. $part = new MixedPart($part, ...$attachmentParts);
  391. } else {
  392. $part = new MixedPart(...$attachmentParts);
  393. }
  394. }
  395. return $part;
  396. }
  397. private function prepareParts(): ?array
  398. {
  399. $names = [];
  400. $htmlPart = null;
  401. $html = $this->html;
  402. if (null !== $this->html) {
  403. if (\is_resource($html)) {
  404. if (stream_get_meta_data($html)['seekable'] ?? false) {
  405. rewind($html);
  406. }
  407. $html = stream_get_contents($html);
  408. }
  409. $htmlPart = new TextPart($html, $this->htmlCharset, 'html');
  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. $attachmentParts = $inlineParts = [];
  414. foreach ($this->attachments as $attachment) {
  415. foreach ($names as $name) {
  416. if (isset($attachment['part'])) {
  417. continue;
  418. }
  419. if ($name !== $attachment['name']) {
  420. continue;
  421. }
  422. if (isset($inlineParts[$name])) {
  423. continue 2;
  424. }
  425. $attachment['inline'] = true;
  426. $inlineParts[$name] = $part = $this->createDataPart($attachment);
  427. $html = str_replace('cid:'.$name, 'cid:'.$part->getContentId(), $html);
  428. continue 2;
  429. }
  430. $attachmentParts[] = $this->createDataPart($attachment);
  431. }
  432. if (null !== $htmlPart) {
  433. $htmlPart = new TextPart($html, $this->htmlCharset, 'html');
  434. }
  435. return [$htmlPart, $attachmentParts, array_values($inlineParts)];
  436. }
  437. private function createDataPart(array $attachment): DataPart
  438. {
  439. if (isset($attachment['part'])) {
  440. return $attachment['part'];
  441. }
  442. if (isset($attachment['body'])) {
  443. $part = new DataPart($attachment['body'], $attachment['name'] ?? null, $attachment['content-type'] ?? null);
  444. } else {
  445. $part = DataPart::fromPath($attachment['path'] ?? '', $attachment['name'] ?? null, $attachment['content-type'] ?? null);
  446. }
  447. if ($attachment['inline']) {
  448. $part->asInline();
  449. }
  450. return $part;
  451. }
  452. /**
  453. * @return $this
  454. */
  455. private function setHeaderBody(string $type, string $name, $body): object
  456. {
  457. $this->getHeaders()->setHeaderBody($type, $name, $body);
  458. return $this;
  459. }
  460. private function addListAddressHeaderBody(string $name, array $addresses)
  461. {
  462. if (!$header = $this->getHeaders()->get($name)) {
  463. return $this->setListAddressHeaderBody($name, $addresses);
  464. }
  465. $header->addAddresses(Address::createArray($addresses));
  466. return $this;
  467. }
  468. private function setListAddressHeaderBody(string $name, array $addresses)
  469. {
  470. $addresses = Address::createArray($addresses);
  471. $headers = $this->getHeaders();
  472. if ($header = $headers->get($name)) {
  473. $header->setAddresses($addresses);
  474. } else {
  475. $headers->addMailboxListHeader($name, $addresses);
  476. }
  477. return $this;
  478. }
  479. /**
  480. * @internal
  481. */
  482. public function __serialize(): array
  483. {
  484. if (\is_resource($this->text)) {
  485. if (stream_get_meta_data($this->text)['seekable'] ?? false) {
  486. rewind($this->text);
  487. }
  488. $this->text = stream_get_contents($this->text);
  489. }
  490. if (\is_resource($this->html)) {
  491. if (stream_get_meta_data($this->html)['seekable'] ?? false) {
  492. rewind($this->html);
  493. }
  494. $this->html = stream_get_contents($this->html);
  495. }
  496. foreach ($this->attachments as $i => $attachment) {
  497. if (isset($attachment['body']) && \is_resource($attachment['body'])) {
  498. if (stream_get_meta_data($attachment['body'])['seekable'] ?? false) {
  499. rewind($attachment['body']);
  500. }
  501. $this->attachments[$i]['body'] = stream_get_contents($attachment['body']);
  502. }
  503. }
  504. return [$this->text, $this->textCharset, $this->html, $this->htmlCharset, $this->attachments, parent::__serialize()];
  505. }
  506. /**
  507. * @internal
  508. */
  509. public function __unserialize(array $data): void
  510. {
  511. [$this->text, $this->textCharset, $this->html, $this->htmlCharset, $this->attachments, $parentData] = $data;
  512. parent::__unserialize($parentData);
  513. }
  514. }