BaseMailer.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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\mail;
  8. use Yii;
  9. use yii\base\Component;
  10. use yii\base\InvalidConfigException;
  11. use yii\base\ViewContextInterface;
  12. use yii\web\View;
  13. use yii\base\MailEvent;
  14. /**
  15. * BaseMailer serves as a base class that implements the basic functions required by [[MailerInterface]].
  16. *
  17. * Concrete child classes should may focus on implementing the [[sendMessage()]] method.
  18. *
  19. * @see BaseMessage
  20. *
  21. * @property View $view View instance. Note that the type of this property differs in getter and setter. See
  22. * [[getView()]] and [[setView()]] for details.
  23. *
  24. * @author Paul Klimov <[email protected]>
  25. * @since 2.0
  26. */
  27. abstract class BaseMailer extends Component implements MailerInterface, ViewContextInterface
  28. {
  29. /**
  30. * @event \yii\base\MailEvent an event raised right before send.
  31. * You may set [[\yii\base\MailEvent::isValid]] to be false to cancel the send.
  32. */
  33. const EVENT_BEFORE_SEND = 'beforeSend';
  34. /**
  35. * @event \yii\base\MailEvent an event raised right after send.
  36. */
  37. const EVENT_AFTER_SEND = 'afterSend';
  38. /**
  39. * @var string directory containing view files for this email messages.
  40. * This can be specified as an absolute path or path alias.
  41. */
  42. public $viewPath = '@app/mails';
  43. /**
  44. * @var string|boolean HTML layout view name. This is the layout used to render HTML mail body.
  45. * The property can take the following values:
  46. *
  47. * - a relative view name: a view file relative to [[viewPath]], e.g., 'layouts/html'.
  48. * - a path alias: an absolute view file path specified as a path alias, e.g., '@app/mails/html'.
  49. * - a boolean false: the layout is disabled.
  50. */
  51. public $htmlLayout = 'layouts/html';
  52. /**
  53. * @var string|boolean text layout view name. This is the layout used to render TEXT mail body.
  54. * Please refer to [[htmlLayout]] for possible values that this property can take.
  55. */
  56. public $textLayout = 'layouts/text';
  57. /**
  58. * @var array the configuration that should be applied to any newly created
  59. * email message instance by [[createMessage()]] or [[compose()]]. Any valid property defined
  60. * by [[MessageInterface]] can be configured, such as `from`, `to`, `subject`, `textBody`, `htmlBody`, etc.
  61. *
  62. * For example:
  63. *
  64. * ~~~
  65. * [
  66. * 'charset' => 'UTF-8',
  67. * 'from' => '[email protected]',
  68. * 'bcc' => '[email protected]',
  69. * ]
  70. * ~~~
  71. */
  72. public $messageConfig = [];
  73. /**
  74. * @var string the default class name of the new message instances created by [[createMessage()]]
  75. */
  76. public $messageClass = 'yii\mail\BaseMessage';
  77. /**
  78. * @var boolean whether to save email messages as files under [[fileTransportPath]] instead of sending them
  79. * to the actual recipients. This is usually used during development for debugging purpose.
  80. * @see fileTransportPath
  81. */
  82. public $useFileTransport = false;
  83. /**
  84. * @var string the directory where the email messages are saved when [[useFileTransport]] is true.
  85. */
  86. public $fileTransportPath = '@runtime/mail';
  87. /**
  88. * @var callback a PHP callback that will be called by [[send()]] when [[useFileTransport]] is true.
  89. * The callback should return a file name which will be used to save the email message.
  90. * If not set, the file name will be generated based on the current timestamp.
  91. *
  92. * The signature of the callback is:
  93. *
  94. * ~~~
  95. * function ($mailer, $message)
  96. * ~~~
  97. */
  98. public $fileTransportCallback;
  99. /**
  100. * @var \yii\base\View|array view instance or its array configuration.
  101. */
  102. private $_view = [];
  103. /**
  104. * @param array|View $view view instance or its array configuration that will be used to
  105. * render message bodies.
  106. * @throws InvalidConfigException on invalid argument.
  107. */
  108. public function setView($view)
  109. {
  110. if (!is_array($view) && !is_object($view)) {
  111. throw new InvalidConfigException('"' . get_class($this) . '::view" should be either object or configuration array, "' . gettype($view) . '" given.');
  112. }
  113. $this->_view = $view;
  114. }
  115. /**
  116. * @return View view instance.
  117. */
  118. public function getView()
  119. {
  120. if (!is_object($this->_view)) {
  121. $this->_view = $this->createView($this->_view);
  122. }
  123. return $this->_view;
  124. }
  125. /**
  126. * Creates view instance from given configuration.
  127. * @param array $config view configuration.
  128. * @return View view instance.
  129. */
  130. protected function createView(array $config)
  131. {
  132. if (!array_key_exists('class', $config)) {
  133. $config['class'] = View::className();
  134. }
  135. return Yii::createObject($config);
  136. }
  137. /**
  138. * Creates a new message instance and optionally composes its body content via view rendering.
  139. *
  140. * @param string|array $view the view to be used for rendering the message body. This can be:
  141. *
  142. * - a string, which represents the view name or path alias for rendering the HTML body of the email.
  143. * In this case, the text body will be generated by applying `strip_tags()` to the HTML body.
  144. * - an array with 'html' and/or 'text' elements. The 'html' element refers to the view name or path alias
  145. * for rendering the HTML body, while 'text' element is for rendering the text body. For example,
  146. * `['html' => 'contact-html', 'text' => 'contact-text']`.
  147. * - null, meaning the message instance will be returned without body content.
  148. *
  149. * The view to be rendered can be specified in one of the following formats:
  150. *
  151. * - path alias (e.g. "@app/mails/contact");
  152. * - a relative view name (e.g. "contact"): the actual view file will be resolved by [[findViewFile()]]
  153. *
  154. * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file.
  155. * @return MessageInterface message instance.
  156. */
  157. public function compose($view = null, array $params = [])
  158. {
  159. $message = $this->createMessage();
  160. if ($view !== null) {
  161. $params['message'] = $message;
  162. if (is_array($view)) {
  163. if (isset($view['html'])) {
  164. $html = $this->render($view['html'], $params, $this->htmlLayout);
  165. }
  166. if (isset($view['text'])) {
  167. $text = $this->render($view['text'], $params, $this->textLayout);
  168. }
  169. } else {
  170. $html = $this->render($view, $params, $this->htmlLayout);
  171. }
  172. if (isset($html)) {
  173. $message->setHtmlBody($html);
  174. }
  175. if (isset($text)) {
  176. $message->setTextBody($text);
  177. } elseif (isset($html)) {
  178. $message->setTextBody(strip_tags($html));
  179. }
  180. }
  181. return $message;
  182. }
  183. /**
  184. * Creates a new message instance.
  185. * The newly created instance will be initialized with the configuration specified by [[messageConfig]].
  186. * If the configuration does not specify a 'class', the [[messageClass]] will be used as the class
  187. * of the new message instance.
  188. * @return MessageInterface message instance.
  189. */
  190. protected function createMessage()
  191. {
  192. $config = $this->messageConfig;
  193. if (!array_key_exists('class', $config)) {
  194. $config['class'] = $this->messageClass;
  195. }
  196. return Yii::createObject($config);
  197. }
  198. /**
  199. * Sends the given email message.
  200. * This method will log a message about the email being sent.
  201. * If [[useFileTransport]] is true, it will save the email as a file under [[fileTransportPath]].
  202. * Otherwise, it will call [[sendMessage()]] to send the email to its recipient(s).
  203. * Child classes should implement [[sendMessage()]] with the actual email sending logic.
  204. * @param MessageInterface $message email message instance to be sent
  205. * @return boolean whether the message has been sent successfully
  206. */
  207. public function send($message)
  208. {
  209. if (!$this->beforeSend($message)) {
  210. return false;
  211. }
  212. $address = $message->getTo();
  213. if (is_array($address)) {
  214. $address = implode(', ', array_keys($address));
  215. }
  216. Yii::info('Sending email "' . $message->getSubject() . '" to "' . $address . '"', __METHOD__);
  217. if ($this->useFileTransport) {
  218. $isSuccessful = $this->saveMessage($message);
  219. } else {
  220. $isSuccessful = $this->sendMessage($message);
  221. }
  222. $this->afterSend($message, $isSuccessful);
  223. return $isSuccessful;
  224. }
  225. /**
  226. * Sends multiple messages at once.
  227. *
  228. * The default implementation simply calls [[send()]] multiple times.
  229. * Child classes may override this method to implement more efficient way of
  230. * sending multiple messages.
  231. *
  232. * @param array $messages list of email messages, which should be sent.
  233. * @return integer number of messages that are successfully sent.
  234. */
  235. public function sendMultiple(array $messages)
  236. {
  237. $successCount = 0;
  238. foreach ($messages as $message) {
  239. if ($this->send($message)) {
  240. $successCount++;
  241. }
  242. }
  243. return $successCount;
  244. }
  245. /**
  246. * Renders the specified view with optional parameters and layout.
  247. * The view will be rendered using the [[view]] component.
  248. * @param string $view the view name or the path alias of the view file.
  249. * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file.
  250. * @param string|boolean $layout layout view name or path alias. If false, no layout will be applied.
  251. * @return string the rendering result.
  252. */
  253. public function render($view, $params = [], $layout = false)
  254. {
  255. $output = $this->getView()->render($view, $params, $this);
  256. if ($layout !== false) {
  257. return $this->getView()->render($layout, ['content' => $output], $this);
  258. } else {
  259. return $output;
  260. }
  261. }
  262. /**
  263. * Sends the specified message.
  264. * This method should be implemented by child classes with the actual email sending logic.
  265. * @param MessageInterface $message the message to be sent
  266. * @return boolean whether the message is sent successfully
  267. */
  268. abstract protected function sendMessage($message);
  269. /**
  270. * Saves the message as a file under [[fileTransportPath]].
  271. * @param MessageInterface $message
  272. * @return boolean whether the message is saved successfully
  273. */
  274. protected function saveMessage($message)
  275. {
  276. $path = Yii::getAlias($this->fileTransportPath);
  277. if (!is_dir(($path))) {
  278. mkdir($path, 0777, true);
  279. }
  280. if ($this->fileTransportCallback !== null) {
  281. $file = $path . '/' . call_user_func($this->fileTransportCallback, $this, $message);
  282. } else {
  283. $time = microtime(true);
  284. $file = $path . '/' . date('Ymd-His-', $time) . sprintf('%04d', (int)(($time - (int)$time) * 10000)) . '-' . sprintf('%04d', mt_rand(0, 10000)) . '.eml';
  285. }
  286. file_put_contents($file, $message->toString());
  287. return true;
  288. }
  289. /**
  290. * Finds the view file corresponding to the specified relative view name.
  291. * This method will return the view file by prefixing the view name with [[viewPath]].
  292. * @param string $view a relative view name. The name does NOT start with a slash.
  293. * @return string the view file path. Note that the file may not exist.
  294. */
  295. public function findViewFile($view)
  296. {
  297. return Yii::getAlias($this->viewPath) . DIRECTORY_SEPARATOR . $view;
  298. }
  299. /**
  300. * This method is invoked right before mail send.
  301. * You may override this method to do last-minute preparation for the message.
  302. * If you override this method, please make sure you call the parent implementation first.
  303. * @param MessageInterface $message
  304. * @return boolean whether to continue sending an email.
  305. */
  306. public function beforeSend($message)
  307. {
  308. $event = new MailEvent(['message' => $message]);
  309. $this->trigger(self::EVENT_BEFORE_SEND, $event);
  310. return $event->isValid;
  311. }
  312. /**
  313. * This method is invoked right after mail was send.
  314. * You may override this method to do some postprocessing or logging based on mail send status.
  315. * If you override this method, please make sure you call the parent implementation first.
  316. * @param MessageInterface $message
  317. * @param boolean $isSuccessful
  318. */
  319. public function afterSend($message, $isSuccessful)
  320. {
  321. $event = new MailEvent(['message' => $message, 'isSuccessful' => $isSuccessful]);
  322. $this->trigger(self::EVENT_AFTER_SEND, $event);
  323. }
  324. }