EmailTarget.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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\log;
  8. use Yii;
  9. use yii\base\InvalidConfigException;
  10. use yii\mail\MailerInterface;
  11. /**
  12. * EmailTarget sends selected log messages to the specified email addresses.
  13. *
  14. * You may configure the email to be sent by setting the [[message]] property, through which
  15. * you can set the target email addresses, subject, etc.
  16. *
  17. * @author Qiang Xue <[email protected]>
  18. * @since 2.0
  19. */
  20. class EmailTarget extends Target
  21. {
  22. /**
  23. * @var array the configuration array for creating a [[\yii\mail\MessageInterface|message]] object.
  24. * Note that the "to" option must be set, which specifies the destination email address(es).
  25. */
  26. public $message = [];
  27. /**
  28. * @var MailerInterface|string the mailer object or the application component ID of the mailer object.
  29. * After the EmailTarget object is created, if you want to change this property, you should only assign it
  30. * with a mailer object.
  31. */
  32. public $mail = 'mail';
  33. /**
  34. * @inheritdoc
  35. */
  36. public function init()
  37. {
  38. parent::init();
  39. if (empty($this->message['to'])) {
  40. throw new InvalidConfigException('The "to" option must be set for EmailTarget::message.');
  41. }
  42. if (is_string($this->mail)) {
  43. $this->mail = Yii::$app->getComponent($this->mail);
  44. }
  45. if (!$this->mail instanceof MailerInterface) {
  46. throw new InvalidConfigException("EmailTarget::mailer must be either a mailer object or the application component ID of a mailer object.");
  47. }
  48. }
  49. /**
  50. * Sends log messages to specified email addresses.
  51. */
  52. public function export()
  53. {
  54. // moved initialization of subject here because of the following issue
  55. // https://github.com/yiisoft/yii2/issues/1446
  56. if (empty($this->message['subject'])) {
  57. $this->message['subject'] = 'Application Log';
  58. }
  59. $messages = array_map([$this, 'formatMessage'], $this->messages);
  60. $body = wordwrap(implode("\n", $messages), 70);
  61. $this->composeMessage($body)->send($this->mail);
  62. }
  63. /**
  64. * Composes a mail message with the given body content.
  65. * @param string $body the body content
  66. * @return \yii\mail\MessageInterface $message
  67. */
  68. protected function composeMessage($body)
  69. {
  70. $message = $this->mail->compose();
  71. Yii::configure($message, $this->message);
  72. $message->setTextBody($body);
  73. return $message;
  74. }
  75. }