BaseMailer.php 11.7 KB
Newer Older
1 2 3 4 5 6 7
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

Paul Klimov committed
8
namespace yii\mail;
9

10
use Yii;
11 12
use yii\base\Component;
use yii\base\InvalidConfigException;
13
use yii\base\ViewContextInterface;
Qiang Xue committed
14
use yii\web\View;
15
use yii\base\MailEvent;
16 17

/**
Qiang Xue committed
18 19
 * BaseMailer serves as a base class that implements the basic functions required by [[MailerInterface]].
 *
20
 * Concrete child classes should may focus on implementing the [[sendMessage()]] method.
21 22 23
 *
 * @see BaseMessage
 *
24 25
 * @property View $view View instance. Note that the type of this property differs in getter and setter. See
 * [[getView()]] and [[setView()]] for details.
26 27 28 29
 *
 * @author Paul Klimov <klimov.paul@gmail.com>
 * @since 2.0
 */
30
abstract class BaseMailer extends Component implements MailerInterface, ViewContextInterface
31
{
32
	/**
Mark committed
33 34
	 * @event \yii\base\MailEvent an event raised right before send.
	 * You may set [[\yii\base\MailEvent::isValid]] to be false to cancel the send.
35 36 37
	 */
	const EVENT_BEFORE_SEND = 'beforeSend';
	/**
Mark committed
38
	 * @event \yii\base\MailEvent an event raised right after send.
39 40
	 */
	const EVENT_AFTER_SEND = 'afterSend';
41
	/**
42
	 * @var string directory containing view files for this email messages.
Qiang Xue committed
43
	 * This can be specified as an absolute path or path alias.
44
	 */
45
	public $viewPath = '@app/mail';
46
	/**
Qiang Xue committed
47 48 49 50
	 * @var string|boolean HTML layout view name. This is the layout used to render HTML mail body.
	 * The property can take the following values:
	 *
	 * - a relative view name: a view file relative to [[viewPath]], e.g., 'layouts/html'.
51
	 * - a path alias: an absolute view file path specified as a path alias, e.g., '@app/mail/html'.
Qiang Xue committed
52
	 * - a boolean false: the layout is disabled.
53 54 55
	 */
	public $htmlLayout = 'layouts/html';
	/**
Qiang Xue committed
56 57
	 * @var string|boolean text layout view name. This is the layout used to render TEXT mail body.
	 * Please refer to [[htmlLayout]] for possible values that this property can take.
58 59
	 */
	public $textLayout = 'layouts/text';
60
	/**
Qiang Xue committed
61 62 63
	 * @var array the configuration that should be applied to any newly created
	 * email message instance by [[createMessage()]] or [[compose()]]. Any valid property defined
	 * by [[MessageInterface]] can be configured, such as `from`, `to`, `subject`, `textBody`, `htmlBody`, etc.
64
	 *
65
	 * For example:
66
	 *
67
	 * ~~~
Qiang Xue committed
68
	 * [
69
	 *     'charset' => 'UTF-8',
70
	 *     'from' => 'noreply@mydomain.com',
71
	 *     'bcc' => 'developer@mydomain.com',
Qiang Xue committed
72
	 * ]
73 74
	 * ~~~
	 */
75
	public $messageConfig = [];
76
	/**
Qiang Xue committed
77
	 * @var string the default class name of the new message instances created by [[createMessage()]]
78 79
	 */
	public $messageClass = 'yii\mail\BaseMessage';
80 81 82 83 84 85 86 87 88 89 90 91 92 93
	/**
	 * @var boolean whether to save email messages as files under [[fileTransportPath]] instead of sending them
	 * to the actual recipients. This is usually used during development for debugging purpose.
	 * @see fileTransportPath
	 */
	public $useFileTransport = false;
	/**
	 * @var string the directory where the email messages are saved when [[useFileTransport]] is true.
	 */
	public $fileTransportPath = '@runtime/mail';
	/**
	 * @var callback a PHP callback that will be called by [[send()]] when [[useFileTransport]] is true.
	 * The callback should return a file name which will be used to save the email message.
	 * If not set, the file name will be generated based on the current timestamp.
94 95 96 97 98 99
	 *
	 * The signature of the callback is:
	 *
	 * ~~~
	 * function ($mailer, $message)
	 * ~~~
100 101 102 103 104 105 106
	 */
	public $fileTransportCallback;

	/**
	 * @var \yii\base\View|array view instance or its array configuration.
	 */
	private $_view = [];
107 108

	/**
Qiang Xue committed
109 110 111
	 * @param array|View $view view instance or its array configuration that will be used to
	 * render message bodies.
	 * @throws InvalidConfigException on invalid argument.
112 113 114 115
	 */
	public function setView($view)
	{
		if (!is_array($view) && !is_object($view)) {
Qiang Xue committed
116
			throw new InvalidConfigException('"' . get_class($this) . '::view" should be either object or configuration array, "' . gettype($view) . '" given.');
117 118 119 120 121
		}
		$this->_view = $view;
	}

	/**
Qiang Xue committed
122
	 * @return View view instance.
123 124 125 126 127 128 129 130 131 132 133 134
	 */
	public function getView()
	{
		if (!is_object($this->_view)) {
			$this->_view = $this->createView($this->_view);
		}
		return $this->_view;
	}

	/**
	 * Creates view instance from given configuration.
	 * @param array $config view configuration.
Qiang Xue committed
135
	 * @return View view instance.
136 137 138 139
	 */
	protected function createView(array $config)
	{
		if (!array_key_exists('class', $config)) {
Qiang Xue committed
140
			$config['class'] = View::className();
141
		}
142 143 144
		return Yii::createObject($config);
	}

145
	/**
Qiang Xue committed
146 147 148 149 150 151 152 153 154 155 156 157 158
	 * Creates a new message instance and optionally composes its body content via view rendering.
	 *
	 * @param string|array $view the view to be used for rendering the message body. This can be:
	 *
	 * - a string, which represents the view name or path alias for rendering the HTML body of the email.
	 *   In this case, the text body will be generated by applying `strip_tags()` to the HTML body.
	 * - an array with 'html' and/or 'text' elements. The 'html' element refers to the view name or path alias
	 *   for rendering the HTML body, while 'text' element is for rendering the text body. For example,
	 *   `['html' => 'contact-html', 'text' => 'contact-text']`.
	 * - null, meaning the message instance will be returned without body content.
	 *
	 * The view to be rendered can be specified in one of the following formats:
	 *
159
	 * - path alias (e.g. "@app/mail/contact");
Qiang Xue committed
160 161 162 163
	 * - a relative view name (e.g. "contact"): the actual view file will be resolved by [[findViewFile()]]
	 *
	 * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file.
	 * @return MessageInterface message instance.
164 165 166 167 168 169 170
	 */
	public function compose($view = null, array $params = [])
	{
		$message = $this->createMessage();
		if ($view !== null) {
			$params['message'] = $message;
			if (is_array($view)) {
Qiang Xue committed
171 172
				if (isset($view['html'])) {
					$html = $this->render($view['html'], $params, $this->htmlLayout);
173
				}
Qiang Xue committed
174 175
				if (isset($view['text'])) {
					$text = $this->render($view['text'], $params, $this->textLayout);
176 177 178
				}
			} else {
				$html = $this->render($view, $params, $this->htmlLayout);
Qiang Xue committed
179 180 181 182 183 184 185 186
			}
			if (isset($html)) {
				$message->setHtmlBody($html);
			}
			if (isset($text)) {
				$message->setTextBody($text);
			} elseif (isset($html)) {
				$message->setTextBody(strip_tags($html));
187 188 189 190 191 192
			}
		}
		return $message;
	}

	/**
Qiang Xue committed
193 194 195 196
	 * Creates a new message instance.
	 * The newly created instance will be initialized with the configuration specified by [[messageConfig]].
	 * If the configuration does not specify a 'class', the [[messageClass]] will be used as the class
	 * of the new message instance.
197
	 * @return MessageInterface message instance.
198
	 */
199
	protected function createMessage()
200
	{
201
		$config = $this->messageConfig;
202 203 204
		if (!array_key_exists('class', $config)) {
			$config['class'] = $this->messageClass;
		}
Qiang Xue committed
205
		return Yii::createObject($config);
206
	}
207

208 209 210 211 212 213 214 215 216 217 218
	/**
	 * Sends the given email message.
	 * This method will log a message about the email being sent.
	 * If [[useFileTransport]] is true, it will save the email as a file under [[fileTransportPath]].
	 * Otherwise, it will call [[sendMessage()]] to send the email to its recipient(s).
	 * Child classes should implement [[sendMessage()]] with the actual email sending logic.
	 * @param MessageInterface $message email message instance to be sent
	 * @return boolean whether the message has been sent successfully
	 */
	public function send($message)
	{
219 220 221 222
		if (!$this->beforeSend($message)) {
			return false;
		}

223 224 225 226
		$address = $message->getTo();
		if (is_array($address)) {
			$address = implode(', ', array_keys($address));
		}
227
		Yii::info('Sending email "' . $message->getSubject() . '" to "' . $address . '"', __METHOD__);
228 229

		if ($this->useFileTransport) {
230
			$isSuccessful = $this->saveMessage($message);
231
		} else {
232
			$isSuccessful = $this->sendMessage($message);
233
		}
234 235
		$this->afterSend($message, $isSuccessful);
		return $isSuccessful;
236 237
	}

238
	/**
Qiang Xue committed
239 240 241 242 243 244
	 * Sends multiple messages at once.
	 *
	 * The default implementation simply calls [[send()]] multiple times.
	 * Child classes may override this method to implement more efficient way of
	 * sending multiple messages.
	 *
245
	 * @param array $messages list of email messages, which should be sent.
Qiang Xue committed
246
	 * @return integer number of messages that are successfully sent.
247
	 */
248 249
	public function sendMultiple(array $messages)
	{
250 251 252 253 254 255 256 257
		$successCount = 0;
		foreach ($messages as $message) {
			if ($this->send($message)) {
				$successCount++;
			}
		}
		return $successCount;
	}
258 259

	/**
Qiang Xue committed
260 261
	 * Renders the specified view with optional parameters and layout.
	 * The view will be rendered using the [[view]] component.
262 263
	 * @param string $view the view name or the path alias of the view file.
	 * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file.
Qiang Xue committed
264
	 * @param string|boolean $layout layout view name or path alias. If false, no layout will be applied.
265
	 * @return string the rendering result.
266
	 */
267
	public function render($view, $params = [], $layout = false)
268
	{
269 270 271 272 273 274
		$output = $this->getView()->render($view, $params, $this);
		if ($layout !== false) {
			return $this->getView()->render($layout, ['content' => $output], $this);
		} else {
			return $output;
		}
275 276
	}

277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
	/**
	 * Sends the specified message.
	 * This method should be implemented by child classes with the actual email sending logic.
	 * @param MessageInterface $message the message to be sent
	 * @return boolean whether the message is sent successfully
	 */
	abstract protected function sendMessage($message);

	/**
	 * Saves the message as a file under [[fileTransportPath]].
	 * @param MessageInterface $message
	 * @return boolean whether the message is saved successfully
	 */
	protected function saveMessage($message)
	{
		$path = Yii::getAlias($this->fileTransportPath);
		if (!is_dir(($path))) {
			mkdir($path, 0777, true);
		}
		if ($this->fileTransportCallback !== null) {
297
			$file = $path . '/' . call_user_func($this->fileTransportCallback, $this, $message);
298
		} else {
Alexander Makarov committed
299
			$file = $path . '/' . $this->generateMessageFileName();
300 301 302 303 304
		}
		file_put_contents($file, $message->toString());
		return true;
	}

305 306 307 308 309 310 311 312 313
	/**
	 * @return string the file name for saving the message when [[useFileTransport]] is true.
	 */
	public function generateMessageFileName()
	{
		$time = microtime(true);
		return date('Ymd-His-', $time) . sprintf('%04d', (int)(($time - (int)$time) * 10000)) . '-' . sprintf('%04d', mt_rand(0, 10000)) . '.eml';
	}

314 315
	/**
	 * Finds the view file corresponding to the specified relative view name.
Qiang Xue committed
316
	 * This method will return the view file by prefixing the view name with [[viewPath]].
317 318 319 320 321 322
	 * @param string $view a relative view name. The name does NOT start with a slash.
	 * @return string the view file path. Note that the file may not exist.
	 */
	public function findViewFile($view)
	{
		return Yii::getAlias($this->viewPath) . DIRECTORY_SEPARATOR . $view;
323
	}
324 325 326 327 328 329

	/**
	 * This method is invoked right before mail send.
	 * You may override this method to do last-minute preparation for the message.
	 * If you override this method, please make sure you call the parent implementation first.
	 * @param MessageInterface $message
330
	 * @return boolean whether to continue sending an email.
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
	 */
	public function beforeSend($message)
	{
		$event = new MailEvent(['message' => $message]);
		$this->trigger(self::EVENT_BEFORE_SEND, $event);
		return $event->isValid;
	}

	/**
	 * This method is invoked right after mail was send.
	 * You may override this method to do some postprocessing or logging based on mail send status.
	 * If you override this method, please make sure you call the parent implementation first.
	 * @param MessageInterface $message
	 * @param boolean $isSuccessful
	 */
	public function afterSend($message, $isSuccessful)
	{
		$event = new MailEvent(['message' => $message, 'isSuccessful' => $isSuccessful]);
		$this->trigger(self::EVENT_AFTER_SEND, $event);
	}

352
}