Message.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\swiftmailer;
  8. use Yii;
  9. use yii\base\InvalidConfigException;
  10. use yii\helpers\ArrayHelper;
  11. use yii\mail\BaseMessage;
  12. /**
  13. * Message implements a message class based on SwiftMailer.
  14. *
  15. * @see http://swiftmailer.org/docs/messages.html
  16. * @see Mailer
  17. *
  18. * @method Mailer getMailer() returns mailer instance.
  19. *
  20. * @property array $headers Headers in format: `[name => value]`. This property is write-only.
  21. * @property int $priority Priority value as integer in range: `1..5`, where 1 is the highest priority and 5
  22. * is the lowest.
  23. * @property string $readReceiptTo Receipt receive email addresses. Note that the type of this property
  24. * differs in getter and setter. See [[getReadReceiptTo()]] and [[setReadReceiptTo()]] for details.
  25. * @property string $returnPath The bounce email address.
  26. * @property array|callable|\Swift_Signer $signature Signature specification. See [[addSignature()]] for
  27. * details on how it should be specified. This property is write-only.
  28. * @property \Swift_Message $swiftMessage Swift message instance. This property is read-only.
  29. *
  30. * @author Paul Klimov <klimov.paul@gmail.com>
  31. * @since 2.0
  32. */
  33. class Message extends BaseMessage
  34. {
  35. /**
  36. * @var \Swift_Message Swift message instance.
  37. */
  38. private $_swiftMessage;
  39. /**
  40. * @var \Swift_Signer[] attached signers
  41. */
  42. private $signers = [];
  43. /**
  44. * This method is called after the object is created by cloning an existing one.
  45. * It ensures [[swiftMessage]] is also cloned.
  46. * @since 2.0.7
  47. */
  48. public function __clone()
  49. {
  50. if (is_object($this->_swiftMessage)) {
  51. $this->_swiftMessage = clone $this->_swiftMessage;
  52. }
  53. }
  54. /**
  55. * @return \Swift_Message Swift message instance.
  56. */
  57. public function getSwiftMessage()
  58. {
  59. if (!is_object($this->_swiftMessage)) {
  60. $this->_swiftMessage = $this->createSwiftMessage();
  61. }
  62. return $this->_swiftMessage;
  63. }
  64. /**
  65. * @inheritdoc
  66. */
  67. public function getCharset()
  68. {
  69. return $this->getSwiftMessage()->getCharset();
  70. }
  71. /**
  72. * @inheritdoc
  73. */
  74. public function setCharset($charset)
  75. {
  76. $this->getSwiftMessage()->setCharset($charset);
  77. return $this;
  78. }
  79. /**
  80. * @inheritdoc
  81. */
  82. public function getFrom()
  83. {
  84. return $this->getSwiftMessage()->getFrom();
  85. }
  86. /**
  87. * @inheritdoc
  88. */
  89. public function setFrom($from)
  90. {
  91. $this->getSwiftMessage()->setFrom($from);
  92. return $this;
  93. }
  94. /**
  95. * @inheritdoc
  96. */
  97. public function getReplyTo()
  98. {
  99. return $this->getSwiftMessage()->getReplyTo();
  100. }
  101. /**
  102. * @inheritdoc
  103. */
  104. public function setReplyTo($replyTo)
  105. {
  106. $this->getSwiftMessage()->setReplyTo($replyTo);
  107. return $this;
  108. }
  109. /**
  110. * @inheritdoc
  111. */
  112. public function getTo()
  113. {
  114. return $this->getSwiftMessage()->getTo();
  115. }
  116. /**
  117. * @inheritdoc
  118. */
  119. public function setTo($to)
  120. {
  121. $this->getSwiftMessage()->setTo($to);
  122. return $this;
  123. }
  124. /**
  125. * @inheritdoc
  126. */
  127. public function getCc()
  128. {
  129. return $this->getSwiftMessage()->getCc();
  130. }
  131. /**
  132. * @inheritdoc
  133. */
  134. public function setCc($cc)
  135. {
  136. $this->getSwiftMessage()->setCc($cc);
  137. return $this;
  138. }
  139. /**
  140. * @inheritdoc
  141. */
  142. public function getBcc()
  143. {
  144. return $this->getSwiftMessage()->getBcc();
  145. }
  146. /**
  147. * @inheritdoc
  148. */
  149. public function setBcc($bcc)
  150. {
  151. $this->getSwiftMessage()->setBcc($bcc);
  152. return $this;
  153. }
  154. /**
  155. * @inheritdoc
  156. */
  157. public function getSubject()
  158. {
  159. return $this->getSwiftMessage()->getSubject();
  160. }
  161. /**
  162. * @inheritdoc
  163. */
  164. public function setSubject($subject)
  165. {
  166. $this->getSwiftMessage()->setSubject($subject);
  167. return $this;
  168. }
  169. /**
  170. * @inheritdoc
  171. */
  172. public function setTextBody($text)
  173. {
  174. $this->setBody($text, 'text/plain');
  175. return $this;
  176. }
  177. /**
  178. * @inheritdoc
  179. */
  180. public function setHtmlBody($html)
  181. {
  182. $this->setBody($html, 'text/html');
  183. return $this;
  184. }
  185. /**
  186. * Sets the message body.
  187. * If body is already set and its content type matches given one, it will
  188. * be overridden, if content type miss match the multipart message will be composed.
  189. * @param string $body body content.
  190. * @param string $contentType body content type.
  191. */
  192. protected function setBody($body, $contentType)
  193. {
  194. $message = $this->getSwiftMessage();
  195. $oldBody = $message->getBody();
  196. $charset = $message->getCharset();
  197. if (empty($oldBody)) {
  198. $parts = $message->getChildren();
  199. $partFound = false;
  200. foreach ($parts as $key => $part) {
  201. if (!($part instanceof \Swift_Mime_Attachment)) {
  202. /* @var $part \Swift_Mime_MimePart */
  203. if ($part->getContentType() == $contentType) {
  204. $charset = $part->getCharset();
  205. unset($parts[$key]);
  206. $partFound = true;
  207. break;
  208. }
  209. }
  210. }
  211. if ($partFound) {
  212. reset($parts);
  213. $message->setChildren($parts);
  214. $message->addPart($body, $contentType, $charset);
  215. } else {
  216. $message->setBody($body, $contentType);
  217. }
  218. } else {
  219. $oldContentType = $message->getContentType();
  220. if ($oldContentType == $contentType) {
  221. $message->setBody($body, $contentType);
  222. } else {
  223. $message->setBody(null);
  224. $message->setContentType(null);
  225. $message->addPart($oldBody, $oldContentType, $charset);
  226. $message->addPart($body, $contentType, $charset);
  227. }
  228. }
  229. }
  230. /**
  231. * @inheritdoc
  232. */
  233. public function attach($fileName, array $options = [])
  234. {
  235. $attachment = \Swift_Attachment::fromPath($fileName);
  236. if (!empty($options['fileName'])) {
  237. $attachment->setFilename($options['fileName']);
  238. }
  239. if (!empty($options['contentType'])) {
  240. $attachment->setContentType($options['contentType']);
  241. }
  242. $this->getSwiftMessage()->attach($attachment);
  243. return $this;
  244. }
  245. /**
  246. * @inheritdoc
  247. */
  248. public function attachContent($content, array $options = [])
  249. {
  250. $attachment = new \Swift_Attachment($content);
  251. if (!empty($options['fileName'])) {
  252. $attachment->setFilename($options['fileName']);
  253. }
  254. if (!empty($options['contentType'])) {
  255. $attachment->setContentType($options['contentType']);
  256. }
  257. if (!empty($options['setDisposition'])) {
  258. $attachment->setDisposition($options['setDisposition']);
  259. }
  260. $this->getSwiftMessage()->attach($attachment);
  261. return $this;
  262. }
  263. /**
  264. * @inheritdoc
  265. */
  266. public function embed($fileName, array $options = [])
  267. {
  268. $embedFile = \Swift_EmbeddedFile::fromPath($fileName);
  269. if (!empty($options['fileName'])) {
  270. $embedFile->setFilename($options['fileName']);
  271. }
  272. if (!empty($options['contentType'])) {
  273. $embedFile->setContentType($options['contentType']);
  274. }
  275. return $this->getSwiftMessage()->embed($embedFile);
  276. }
  277. /**
  278. * @inheritdoc
  279. */
  280. public function embedContent($content, array $options = [])
  281. {
  282. $embedFile = new \Swift_EmbeddedFile($content);
  283. if (!empty($options['fileName'])) {
  284. $embedFile->setFilename($options['fileName']);
  285. }
  286. if (!empty($options['contentType'])) {
  287. $embedFile->setContentType($options['contentType']);
  288. }
  289. return $this->getSwiftMessage()->embed($embedFile);
  290. }
  291. /**
  292. * Sets message signature
  293. * @param array|callable|\Swift_Signer $signature signature specification.
  294. * See [[addSignature()]] for details on how it should be specified.
  295. * @return $this self reference.
  296. * @since 2.0.6
  297. */
  298. public function setSignature($signature)
  299. {
  300. if (!empty($this->signers)) {
  301. // clear previously set signers
  302. $swiftMessage = $this->getSwiftMessage();
  303. foreach ($this->signers as $signer) {
  304. $swiftMessage->detachSigner($signer);
  305. }
  306. $this->signers = [];
  307. }
  308. return $this->addSignature($signature);
  309. }
  310. /**
  311. * Adds message signature.
  312. * @param array|callable|\Swift_Signer $signature signature specification, this can be:
  313. *
  314. * - [[\Swift_Signer]] instance
  315. * - callable, which returns [[\Swift_Signer]] instance
  316. * - configuration array for the signer creation
  317. *
  318. * @return $this self reference
  319. * @throws InvalidConfigException on invalid signature configuration
  320. * @since 2.0.6
  321. */
  322. public function addSignature($signature)
  323. {
  324. if ($signature instanceof \Swift_Signer) {
  325. $signer = $signature;
  326. } elseif (is_callable($signature)) {
  327. $signer = call_user_func($signature);
  328. } elseif (is_array($signature)) {
  329. $signer = $this->createSwiftSigner($signature);
  330. } else {
  331. throw new InvalidConfigException('Signature should be instance of "Swift_Signer", callable or array configuration');
  332. }
  333. $this->getSwiftMessage()->attachSigner($signer);
  334. $this->signers[] = $signer;
  335. return $this;
  336. }
  337. /**
  338. * Creates signer from its configuration
  339. * @param array $signature signature configuration
  340. * @return \Swift_Signer signer instance
  341. * @throws InvalidConfigException on invalid configuration provided
  342. * @since 2.0.6
  343. */
  344. protected function createSwiftSigner($signature)
  345. {
  346. if (!isset($signature['type'])) {
  347. throw new InvalidConfigException('Signature configuration should contain "type" key');
  348. }
  349. switch (strtolower($signature['type'])) {
  350. case 'dkim' :
  351. $domain = ArrayHelper::getValue($signature, 'domain', null);
  352. $selector = ArrayHelper::getValue($signature, 'selector', null);
  353. if (isset($signature['key'])) {
  354. $privateKey = $signature['key'];
  355. } elseif (isset($signature['file'])) {
  356. $privateKey = file_get_contents(Yii::getAlias($signature['file']));
  357. } else {
  358. throw new InvalidConfigException("Either 'key' or 'file' signature option should be specified");
  359. }
  360. return new \Swift_Signers_DKIMSigner($privateKey, $domain, $selector);
  361. case 'opendkim' :
  362. $domain = ArrayHelper::getValue($signature, 'domain', null);
  363. $selector = ArrayHelper::getValue($signature, 'selector', null);
  364. if (isset($signature['key'])) {
  365. $privateKey = $signature['key'];
  366. } elseif (isset($signature['file'])) {
  367. $privateKey = file_get_contents(Yii::getAlias($signature['file']));
  368. } else {
  369. throw new InvalidConfigException("Either 'key' or 'file' signature option should be specified");
  370. }
  371. return new \Swift_Signers_OpenDKIMSigner($privateKey, $domain, $selector);
  372. default:
  373. throw new InvalidConfigException("Unrecognized signature type '{$signature['type']}'");
  374. }
  375. }
  376. /**
  377. * @inheritdoc
  378. */
  379. public function toString()
  380. {
  381. return $this->getSwiftMessage()->toString();
  382. }
  383. /**
  384. * Creates the Swift email message instance.
  385. * @return \Swift_Message email message instance.
  386. */
  387. protected function createSwiftMessage()
  388. {
  389. return new \Swift_Message();
  390. }
  391. // Headers setup :
  392. /**
  393. * Adds custom header value to the message.
  394. * Several invocations of this method with the same name will add multiple header values.
  395. * @param string $name header name.
  396. * @param string $value header value.
  397. * @return $this self reference.
  398. * @since 2.0.6
  399. */
  400. public function addHeader($name, $value)
  401. {
  402. $this->getSwiftMessage()->getHeaders()->addTextHeader($name, $value);
  403. return $this;
  404. }
  405. /**
  406. * Sets custom header value to the message.
  407. * @param string $name header name.
  408. * @param string|array $value header value or values.
  409. * @return $this self reference.
  410. * @since 2.0.6
  411. */
  412. public function setHeader($name, $value)
  413. {
  414. $headerSet = $this->getSwiftMessage()->getHeaders();
  415. if ($headerSet->has($name)) {
  416. $headerSet->remove($name);
  417. }
  418. foreach ((array)$value as $v) {
  419. $headerSet->addTextHeader($name, $v);
  420. }
  421. return $this;
  422. }
  423. /**
  424. * Returns all values for the specified header.
  425. * @param string $name header name.
  426. * @return array header values list.
  427. * @since 2.0.6
  428. */
  429. public function getHeader($name)
  430. {
  431. $headerSet = $this->getSwiftMessage()->getHeaders();
  432. if (!$headerSet->has($name)) {
  433. return [];
  434. }
  435. $headers = [];
  436. foreach ($headerSet->getAll($name) as $header) {
  437. $headers[] = $header->getValue();
  438. }
  439. return $headers;
  440. }
  441. /**
  442. * Sets custom header values to the message.
  443. * @param array $headers headers in format: `[name => value]`.
  444. * @return $this self reference.
  445. * @since 2.0.7
  446. */
  447. public function setHeaders($headers)
  448. {
  449. foreach ($headers as $name => $value) {
  450. $this->setHeader($name, $value);
  451. }
  452. return $this;
  453. }
  454. // SwiftMessage shortcuts :
  455. /**
  456. * Set the return-path (the bounce address) of this message.
  457. * @param string $address the bounce email address.
  458. * @return $this self reference.
  459. * @since 2.0.6
  460. */
  461. public function setReturnPath($address)
  462. {
  463. $this->getSwiftMessage()->setReturnPath($address);
  464. return $this;
  465. }
  466. /**
  467. * Returns the return-path (the bounce address) of this message.
  468. * @return string the bounce email address.
  469. * @since 2.0.6
  470. */
  471. public function getReturnPath()
  472. {
  473. return $this->getSwiftMessage()->getReturnPath();
  474. }
  475. /**
  476. * Set the priority of this message.
  477. * @param int $priority priority value, should be an integer in range: `1..5`,
  478. * where 1 is the highest priority and 5 is the lowest.
  479. * @return $this self reference.
  480. * @since 2.0.6
  481. */
  482. public function setPriority($priority)
  483. {
  484. $this->getSwiftMessage()->setPriority($priority);
  485. return $this;
  486. }
  487. /**
  488. * Returns the priority of this message.
  489. * @return int priority value as integer in range: `1..5`,
  490. * where 1 is the highest priority and 5 is the lowest.
  491. * @since 2.0.6
  492. */
  493. public function getPriority()
  494. {
  495. return $this->getSwiftMessage()->getPriority();
  496. }
  497. /**
  498. * Sets the ask for a delivery receipt from the recipient to be sent to $addresses.
  499. * @param string|array $addresses receipt receive email address(es).
  500. * @return $this self reference.
  501. * @since 2.0.6
  502. */
  503. public function setReadReceiptTo($addresses)
  504. {
  505. $this->getSwiftMessage()->setReadReceiptTo($addresses);
  506. return $this;
  507. }
  508. /**
  509. * Get the addresses to which a read-receipt will be sent.
  510. * @return string receipt receive email addresses.
  511. * @since 2.0.6
  512. */
  513. public function getReadReceiptTo()
  514. {
  515. return $this->getSwiftMessage()->getReadReceiptTo();
  516. }
  517. }