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

Qiang Xue committed
8
namespace yii\log;
w  
Qiang Xue committed
9

w  
Qiang Xue committed
10
/**
w  
Qiang Xue committed
11
 * EmailTarget sends selected log messages to the specified email addresses.
w  
Qiang Xue committed
12
 *
w  
Qiang Xue committed
13 14 15
 * The target email addresses may be specified via [[emails]] property.
 * Optionally, you may set the email [[subject]], [[sentFrom]] address and
 * additional [[headers]].
w  
Qiang Xue committed
16 17
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
w  
Qiang Xue committed
18
 * @since 2.0
w  
Qiang Xue committed
19
 */
w  
Qiang Xue committed
20
class EmailTarget extends Target
w  
Qiang Xue committed
21 22 23 24
{
	/**
	 * @var array list of destination email addresses.
	 */
Alexander Makarov committed
25
	public $emails = [];
w  
Qiang Xue committed
26 27 28
	/**
	 * @var string email subject
	 */
w  
Qiang Xue committed
29
	public $subject;
w  
Qiang Xue committed
30
	/**
w  
Qiang Xue committed
31
	 * @var string email sent-from address
w  
Qiang Xue committed
32
	 */
w  
Qiang Xue committed
33
	public $sentFrom;
w  
Qiang Xue committed
34 35 36
	/**
	 * @var array list of additional headers to use when sending an email.
	 */
Alexander Makarov committed
37
	public $headers = [];
w  
Qiang Xue committed
38 39

	/**
Qiang Xue committed
40
	 * Sends log messages to specified email addresses.
w  
Qiang Xue committed
41
	 */
Qiang Xue committed
42
	public function export()
w  
Qiang Xue committed
43
	{
w  
Qiang Xue committed
44
		$body = '';
Qiang Xue committed
45
		foreach ($this->messages as $message) {
w  
Qiang Xue committed
46 47 48
			$body .= $this->formatMessage($message);
		}
		$body = wordwrap($body, 70);
49
		$subject = $this->subject === null ? \Yii::t('yii', 'Application Log') : $this->subject;
w  
Qiang Xue committed
50 51 52
		foreach ($this->emails as $email) {
			$this->sendEmail($subject, $body, $email, $this->sentFrom, $this->headers);
		}
w  
Qiang Xue committed
53 54 55 56 57
	}

	/**
	 * Sends an email.
	 * @param string $subject email subject
w  
Qiang Xue committed
58 59 60 61
	 * @param string $body email body
	 * @param string $sentTo sent-to email address
	 * @param string $sentFrom sent-from email address
	 * @param array $headers additional headers to be used when sending the email
w  
Qiang Xue committed
62
	 */
w  
Qiang Xue committed
63
	protected function sendEmail($subject, $body, $sentTo, $sentFrom, $headers)
w  
Qiang Xue committed
64
	{
w  
Qiang Xue committed
65 66 67
		if ($sentFrom !== null) {
			$headers[] = "From:  {$sentFrom}";
		}
Qiang Xue committed
68
		mail($sentTo, $subject, $body, implode("\r\n", $headers));
w  
Qiang Xue committed
69
	}
Zander Baldwin committed
70
}