You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

582 lines
15 KiB

3 years ago
  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 $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 array|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. $htmlPart = new TextPart($html, $this->htmlCharset, 'html');
  404. $html = $htmlPart->getBody();
  405. preg_match_all('(<img\s+[^>]*src\s*=\s*(?:([\'"])cid:([^"]+)\\1|cid:([^>\s]+)))i', $html, $names);
  406. $names = array_filter(array_unique(array_merge($names[2], $names[3])));
  407. }
  408. $attachmentParts = $inlineParts = [];
  409. foreach ($this->attachments as $attachment) {
  410. foreach ($names as $name) {
  411. if (isset($attachment['part'])) {
  412. continue;
  413. }
  414. if ($name !== $attachment['name']) {
  415. continue;
  416. }
  417. if (isset($inlineParts[$name])) {
  418. continue 2;
  419. }
  420. $attachment['inline'] = true;
  421. $inlineParts[$name] = $part = $this->createDataPart($attachment);
  422. $html = str_replace('cid:'.$name, 'cid:'.$part->getContentId(), $html);
  423. $part->setName($part->getContentId());
  424. continue 2;
  425. }
  426. $attachmentParts[] = $this->createDataPart($attachment);
  427. }
  428. if (null !== $htmlPart) {
  429. $htmlPart = new TextPart($html, $this->htmlCharset, 'html');
  430. }
  431. return [$htmlPart, $attachmentParts, array_values($inlineParts)];
  432. }
  433. private function createDataPart(array $attachment): DataPart
  434. {
  435. if (isset($attachment['part'])) {
  436. return $attachment['part'];
  437. }
  438. if (isset($attachment['body'])) {
  439. $part = new DataPart($attachment['body'], $attachment['name'] ?? null, $attachment['content-type'] ?? null);
  440. } else {
  441. $part = DataPart::fromPath($attachment['path'] ?? '', $attachment['name'] ?? null, $attachment['content-type'] ?? null);
  442. }
  443. if ($attachment['inline']) {
  444. $part->asInline();
  445. }
  446. return $part;
  447. }
  448. /**
  449. * @return $this
  450. */
  451. private function setHeaderBody(string $type, string $name, $body): object
  452. {
  453. $this->getHeaders()->setHeaderBody($type, $name, $body);
  454. return $this;
  455. }
  456. private function addListAddressHeaderBody(string $name, array $addresses)
  457. {
  458. if (!$header = $this->getHeaders()->get($name)) {
  459. return $this->setListAddressHeaderBody($name, $addresses);
  460. }
  461. $header->addAddresses(Address::createArray($addresses));
  462. return $this;
  463. }
  464. private function setListAddressHeaderBody(string $name, array $addresses)
  465. {
  466. $addresses = Address::createArray($addresses);
  467. $headers = $this->getHeaders();
  468. if ($header = $headers->get($name)) {
  469. $header->setAddresses($addresses);
  470. } else {
  471. $headers->addMailboxListHeader($name, $addresses);
  472. }
  473. return $this;
  474. }
  475. /**
  476. * @internal
  477. */
  478. public function __serialize(): array
  479. {
  480. if (\is_resource($this->text)) {
  481. $this->text = (new TextPart($this->text))->getBody();
  482. }
  483. if (\is_resource($this->html)) {
  484. $this->html = (new TextPart($this->html))->getBody();
  485. }
  486. foreach ($this->attachments as $i => $attachment) {
  487. if (isset($attachment['body']) && \is_resource($attachment['body'])) {
  488. $this->attachments[$i]['body'] = (new TextPart($attachment['body']))->getBody();
  489. }
  490. }
  491. return [$this->text, $this->textCharset, $this->html, $this->htmlCharset, $this->attachments, parent::__serialize()];
  492. }
  493. /**
  494. * @internal
  495. */
  496. public function __unserialize(array $data): void
  497. {
  498. [$this->text, $this->textCharset, $this->html, $this->htmlCharset, $this->attachments, $parentData] = $data;
  499. parent::__unserialize($parentData);
  500. }
  501. }