BaseMailer.php 14 KB

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