Message.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  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 = \Swift_Attachment::newInstance($content);
  251. if (!empty($options['fileName'])) {
  252. $attachment->setFilename($options['fileName']);
  253. }
  254. if (!empty($options['contentType'])) {
  255. $attachment->setContentType($options['contentType']);
  256. }
  257. $this->getSwiftMessage()->attach($attachment);
  258. return $this;
  259. }
  260. /**
  261. * @inheritdoc
  262. */
  263. public function embed($fileName, array $options = [])
  264. {
  265. $embedFile = \Swift_EmbeddedFile::fromPath($fileName);
  266. if (!empty($options['fileName'])) {
  267. $embedFile->setFilename($options['fileName']);
  268. }
  269. if (!empty($options['contentType'])) {
  270. $embedFile->setContentType($options['contentType']);
  271. }
  272. return $this->getSwiftMessage()->embed($embedFile);
  273. }
  274. /**
  275. * @inheritdoc
  276. */
  277. public function embedContent($content, array $options = [])
  278. {
  279. $embedFile = \Swift_EmbeddedFile::newInstance($content);
  280. if (!empty($options['fileName'])) {
  281. $embedFile->setFilename($options['fileName']);
  282. }
  283. if (!empty($options['contentType'])) {
  284. $embedFile->setContentType($options['contentType']);
  285. }
  286. return $this->getSwiftMessage()->embed($embedFile);
  287. }
  288. /**
  289. * Sets message signature
  290. * @param array|callable|\Swift_Signer $signature signature specification.
  291. * See [[addSignature()]] for details on how it should be specified.
  292. * @return $this self reference.
  293. * @since 2.0.6
  294. */
  295. public function setSignature($signature)
  296. {
  297. if (!empty($this->signers)) {
  298. // clear previously set signers
  299. $swiftMessage = $this->getSwiftMessage();
  300. foreach ($this->signers as $signer) {
  301. $swiftMessage->detachSigner($signer);
  302. }
  303. $this->signers = [];
  304. }
  305. return $this->addSignature($signature);
  306. }
  307. /**
  308. * Adds message signature.
  309. * @param array|callable|\Swift_Signer $signature signature specification, this can be:
  310. *
  311. * - [[\Swift_Signer]] instance
  312. * - callable, which returns [[\Swift_Signer]] instance
  313. * - configuration array for the signer creation
  314. *
  315. * @return $this self reference
  316. * @throws InvalidConfigException on invalid signature configuration
  317. * @since 2.0.6
  318. */
  319. public function addSignature($signature)
  320. {
  321. if ($signature instanceof \Swift_Signer) {
  322. $signer = $signature;
  323. } elseif (is_callable($signature)) {
  324. $signer = call_user_func($signature);
  325. } elseif (is_array($signature)) {
  326. $signer = $this->createSwiftSigner($signature);
  327. } else {
  328. throw new InvalidConfigException('Signature should be instance of "Swift_Signer", callable or array configuration');
  329. }
  330. $this->getSwiftMessage()->attachSigner($signer);
  331. $this->signers[] = $signer;
  332. return $this;
  333. }
  334. /**
  335. * Creates signer from its configuration
  336. * @param array $signature signature configuration
  337. * @return \Swift_Signer signer instance
  338. * @throws InvalidConfigException on invalid configuration provided
  339. * @since 2.0.6
  340. */
  341. protected function createSwiftSigner($signature)
  342. {
  343. if (!isset($signature['type'])) {
  344. throw new InvalidConfigException('Signature configuration should contain "type" key');
  345. }
  346. switch (strtolower($signature['type'])) {
  347. case 'dkim' :
  348. $domain = ArrayHelper::getValue($signature, 'domain', null);
  349. $selector = ArrayHelper::getValue($signature, 'selector', null);
  350. if (isset($signature['key'])) {
  351. $privateKey = $signature['key'];
  352. } elseif (isset($signature['file'])) {
  353. $privateKey = file_get_contents(Yii::getAlias($signature['file']));
  354. } else {
  355. throw new InvalidConfigException("Either 'key' or 'file' signature option should be specified");
  356. }
  357. return new \Swift_Signers_DKIMSigner($privateKey, $domain, $selector);
  358. case 'opendkim' :
  359. $domain = ArrayHelper::getValue($signature, 'domain', null);
  360. $selector = ArrayHelper::getValue($signature, 'selector', null);
  361. if (isset($signature['key'])) {
  362. $privateKey = $signature['key'];
  363. } elseif (isset($signature['file'])) {
  364. $privateKey = file_get_contents(Yii::getAlias($signature['file']));
  365. } else {
  366. throw new InvalidConfigException("Either 'key' or 'file' signature option should be specified");
  367. }
  368. return new \Swift_Signers_OpenDKIMSigner($privateKey, $domain, $selector);
  369. default:
  370. throw new InvalidConfigException("Unrecognized signature type '{$signature['type']}'");
  371. }
  372. }
  373. /**
  374. * @inheritdoc
  375. */
  376. public function toString()
  377. {
  378. return $this->getSwiftMessage()->toString();
  379. }
  380. /**
  381. * Creates the Swift email message instance.
  382. * @return \Swift_Message email message instance.
  383. */
  384. protected function createSwiftMessage()
  385. {
  386. return new \Swift_Message();
  387. }
  388. // Headers setup :
  389. /**
  390. * Adds custom header value to the message.
  391. * Several invocations of this method with the same name will add multiple header values.
  392. * @param string $name header name.
  393. * @param string $value header value.
  394. * @return $this self reference.
  395. * @since 2.0.6
  396. */
  397. public function addHeader($name, $value)
  398. {
  399. $this->getSwiftMessage()->getHeaders()->addTextHeader($name, $value);
  400. return $this;
  401. }
  402. /**
  403. * Sets custom header value to the message.
  404. * @param string $name header name.
  405. * @param string|array $value header value or values.
  406. * @return $this self reference.
  407. * @since 2.0.6
  408. */
  409. public function setHeader($name, $value)
  410. {
  411. $headerSet = $this->getSwiftMessage()->getHeaders();
  412. if ($headerSet->has($name)) {
  413. $headerSet->remove($name);
  414. }
  415. foreach ((array)$value as $v) {
  416. $headerSet->addTextHeader($name, $v);
  417. }
  418. return $this;
  419. }
  420. /**
  421. * Returns all values for the specified header.
  422. * @param string $name header name.
  423. * @return array header values list.
  424. * @since 2.0.6
  425. */
  426. public function getHeader($name)
  427. {
  428. $headerSet = $this->getSwiftMessage()->getHeaders();
  429. if (!$headerSet->has($name)) {
  430. return [];
  431. }
  432. $headers = [];
  433. foreach ($headerSet->getAll($name) as $header) {
  434. $headers[] = $header->getValue();
  435. }
  436. return $headers;
  437. }
  438. /**
  439. * Sets custom header values to the message.
  440. * @param array $headers headers in format: `[name => value]`.
  441. * @return $this self reference.
  442. * @since 2.0.7
  443. */
  444. public function setHeaders($headers)
  445. {
  446. foreach ($headers as $name => $value) {
  447. $this->setHeader($name, $value);
  448. }
  449. return $this;
  450. }
  451. // SwiftMessage shortcuts :
  452. /**
  453. * Set the return-path (the bounce address) of this message.
  454. * @param string $address the bounce email address.
  455. * @return $this self reference.
  456. * @since 2.0.6
  457. */
  458. public function setReturnPath($address)
  459. {
  460. $this->getSwiftMessage()->setReturnPath($address);
  461. return $this;
  462. }
  463. /**
  464. * Returns the return-path (the bounce address) of this message.
  465. * @return string the bounce email address.
  466. * @since 2.0.6
  467. */
  468. public function getReturnPath()
  469. {
  470. return $this->getSwiftMessage()->getReturnPath();
  471. }
  472. /**
  473. * Set the priority of this message.
  474. * @param int $priority priority value, should be an integer in range: `1..5`,
  475. * where 1 is the highest priority and 5 is the lowest.
  476. * @return $this self reference.
  477. * @since 2.0.6
  478. */
  479. public function setPriority($priority)
  480. {
  481. $this->getSwiftMessage()->setPriority($priority);
  482. return $this;
  483. }
  484. /**
  485. * Returns the priority of this message.
  486. * @return int priority value as integer in range: `1..5`,
  487. * where 1 is the highest priority and 5 is the lowest.
  488. * @since 2.0.6
  489. */
  490. public function getPriority()
  491. {
  492. return $this->getSwiftMessage()->getPriority();
  493. }
  494. /**
  495. * Sets the ask for a delivery receipt from the recipient to be sent to $addresses.
  496. * @param string|array $addresses receipt receive email address(es).
  497. * @return $this self reference.
  498. * @since 2.0.6
  499. */
  500. public function setReadReceiptTo($addresses)
  501. {
  502. $this->getSwiftMessage()->setReadReceiptTo($addresses);
  503. return $this;
  504. }
  505. /**
  506. * Get the addresses to which a read-receipt will be sent.
  507. * @return string receipt receive email addresses.
  508. * @since 2.0.6
  509. */
  510. public function getReadReceiptTo()
  511. {
  512. return $this->getSwiftMessage()->getReadReceiptTo();
  513. }
  514. }