forked from vernes/YiiMailer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathYiiMailer.php
567 lines (499 loc) · 13 KB
/
YiiMailer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
<?
/**
* YiiMailer class - wrapper for PHPMailer
* Yii extension for sending emails using views and layouts
* https://github.com/vernes/YiiMailer
* Copyright (c) 2013 YiiMailer
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*
* @package YiiMailer
* @author Vernes Šiljegović
* @copyright Copyright (c) 2013 YiiMailer
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version 1.5, 2013-06-03
*/
class YiiMailer extends PHPMailer {
/**
* Sets the CharSet of the message.
* @var string
*/
public $CharSet='UTF-8';
/**
* Sets the text-only body of the message.
* @var string
*/
public $AltBody='';
/**
* Default paths and private properties
*/
private $viewPath='application.views.mail';
private $layoutPath='application.views.mail.layouts';
private $baseDirPath='webroot.images.mail';
private $testMode=false;
private $savePath='webroot.assets.mail';
private $layout;
private $view;
private $data;
/**
* Constants
*/
const CONFIG_FILE='mail.php'; //Define the name of the config file
const CONFIG_PARAMS='YiiMailer'; //Define the key of the Yii params for the config array
/**
* Set and configure initial parameters
* @param string $view View name
* @param array $data Data array
* @param string $layout Layout name
*/
public function __construct($view='', $data= [], $layout='')
{
//initialize config
if(isset(EO::app()->params[self::CONFIG_PARAMS]))
$config=EO::app()->params[self::CONFIG_PARAMS];
else
$config=require(EO::getPathOfAlias('application.config').DIRECTORY_SEPARATOR.self::CONFIG_FILE);
//set config
$this->setConfig($config);
//set view
$this->setView($view);
//set data
$this->setData($data);
//set layout
$this->setLayout($layout);
}
/**
* Configure parameters
* @param array $config Config parameters
* @throws CException
*/
private function setConfig($config)
{
if(!is_array($config))
throw new CException("Configuration options must be an array!");
foreach($config as $key=>$val)
{
$this->$key=$val;
}
}
/**
* Set the view to be used
* @param string $view View file
* @throws CException
*/
public function setView($view)
{
if($view!='')
{
if(!is_file($this->getViewFile($this->viewPath.'.'.$view)))
throw new CException('View "'.$view.'" not found');
$this->view=$view;
}
}
/**
* Get currently used view
* @return string View filename
*/
public function getView()
{
return $this->viewPath.'.'.$this->view;
}
/**
* Clear currently used view
*/
public function clearView()
{
$this->view=null;
}
/**
* Send data to be used in mail body
* @param array $data Data array
*/
public function setData($data)
{
$this->data=$data;
}
/**
* Get current data array
* @return array Data array
*/
public function getData()
{
return $this->data;
}
/**
* Clear current data array
*/
public function clearData()
{
$this->data= [];
}
/**
* Set layout file to be used
* @param string $layout Layout filename
* @throws CException
*/
public function setLayout($layout)
{
if($layout!='')
{
if(!is_file($this->getViewFile($this->layoutPath.'.'.$layout)))
throw new CException('Layout "'.$layout.'" not found!');
$this->layout=$layout;
}
}
/**
* Get current layout
* @return string Layout filename
*/
public function getLayout()
{
return $this->layout;
}
/**
* Clear current layout
*/
public function clearLayout()
{
$this->layout=null;
}
/**
* Set path for email views
* @param string $path Yii path
* @throws CException
*/
public function setViewPath($path)
{
if (!is_string($path) && !preg_match("/[a-z0-9\.]/i",$path))
throw new CException('Path "'.$path.'" not valid!');
$this->viewPath=$path;
}
/**
* Get path for email views
* @return string Yii path
*/
public function getViewPath()
{
return $this->viewPath;
}
/**
* Set path for email layouts
* @param string $path Yii path
* @throws CException
*/
public function setLayoutPath($path)
{
if (!is_string($path) && !preg_match("/[a-z0-9\.]/i",$path))
throw new CException('Path "'.$path.'" not valid!');
$this->layoutPath=$path;
}
/**
* Get path for email layouts
* @return string Yii path
*/
public function getLayoutPath()
{
return $this->layoutPath;
}
/**
* Set path for images to embed in email messages
* @param string $path Yii path
* @throws CException
*/
public function setBaseDirPath($path)
{
if (!is_string($path) && !preg_match("/[a-z0-9\.]/i",$path))
throw new CException('Path "'.$path.'" not valid!');
$this->baseDirPath=$path;
}
/**
* Get path for email images
* @return string Yii path
*/
public function getBaseDirPath()
{
return $this->baseDirPath;
}
/**
* Set From address and name
* @param string $address Email address of the sender
* @param string $name Name of the sender
* @param boolean $auto Also set the Reply-To
* @return boolean True on success, false if address not valid
*/
public function setFrom($address, $name = '', $auto = true)
{
return parent::SetFrom($address, $name, (int)$auto);
}
/**
* Set one or more email addresses to send to
* Valid arguments:
* $mail->setTo('[email protected]');
* $mail->setTo(array('[email protected]','[email protected]'));
* $mail->setTo(array('[email protected]'=>'John Doe','[email protected]'));
* @param mixed $addresses Email address or array of email addresses
* @return boolean True on success, false if addresses not valid
*/
public function setTo($addresses)
{
$this->ClearAddresses();
return $this->setAddresses('to',$addresses);
}
/**
* Set one or more CC email addresses
* @param mixed $addresses Email address or array of email addresses
* @return boolean True on success, false if addresses not valid
*/
public function setCc($addresses)
{
$this->ClearCCs();
return $this->setAddresses('cc',$addresses);
}
/**
* Set one or more BCC email addresses
* @param mixed $addresses Email address or array of email addresses
* @return boolean True on success, false if addresses not valid
*/
public function setBcc($addresses)
{
$this->ClearBCCs();
return $this->setAddresses('bcc',$addresses);
}
/**
* Set one or more Reply-To email addresses
* @param mixed $addresses Email address or array of email addresses
* @return boolean True on success, false if addresses not valid
*/
public function setReplyTo($addresses)
{
$this->ClearReplyTos();
return $this->setAddresses('Reply-To',$addresses);
}
/**
* Set one or more email addresses of different kinds
* @param string $type Type of the recipient (to, cc, bcc or Reply-To)
* @param mixed $addresses Email address or array of email addresses
* @return boolean True on success, false if addresses not valid
*/
private function setAddresses($type,$addresses)
{
if(!is_array($addresses))
{
$addresses=(array)$addresses;
}
$result=true;
foreach ($addresses as $key => $value) {
if(is_int($key))
$r=$this->AddAnAddress($type,$value);
else
$r=$this->AddAnAddress($type,$key,$value);
if($result && !$r)
$result=false;
}
return $result;
}
/**
* Set subject of the email
* @param string $subject Subject of the email
*/
public function setSubject($subject)
{
$this->Subject=$subject;
}
/**
* Set text body of the email
* @param string $body Textual body of the email
*/
public function setBody($body)
{
$this->Body=$body;
}
/**
* Set one or more email attachments
* Valid arguments:
* $mail->setAttachment('something.pdf');
* $mail->setAttachment(array('something.pdf','something_else.pdf','another.doc'));
* $mail->setAttachment(array('something.pdf'=>'Some file','something_else.pdf'=>'Another file'));
* @param mixed $attachments Path to the file or array of files to attach
* @return boolean True on success, false if addresses not valid
*/
public function setAttachment($attachments)
{
if(!is_array($attachments))
$attachments=(array)$attachments;
$result=true;
foreach ($attachments as $key => $value) {
if(is_int($key))
$r=$this->AddAttachment($value);
else
$r=$this->AddAttachment($key,$value);
if($result && !$r)
$result=false;
}
return $result;
}
/**
* Clear all recipients and attachments
*/
public function clear()
{
$this->ClearAllRecipients();
$this->ClearReplyTos();
$this->ClearAttachments();
}
/**
* Get current error message
* @return string Error message
*/
public function getError()
{
return $this->ErrorInfo;
}
/**
* Find the view file for the given view name
* @param string $viewName Name of the view
* @return string The file path or false if the file does not exist
*/
public function getViewFile($viewName)
{
//In web application, use existing method
if(isset(EO::app()->controller)) {
$viewFile = EO::app()->controller->getViewFile($viewName);
if (!empty($viewFile)) {
return $viewFile;
}
}
//resolve the view file
//TODO: support for themes in console applications
if(empty($viewName))
return false;
$viewFile=EO::getPathOfAlias($viewName);
if(($theme=EO::app()->getTheme())!==null) {
$themeView = str_replace(EO::getPathOfAlias('vendor.digizijn'), '', $viewFile);
$themeView = str_replace('/views/', '/', $themeView); // FIXME Quick&dirty :)
if(is_file($theme->getViewPath().$themeView.'.php')) {
return EO::app()->findLocalizedFile($theme->getViewPath().$themeView.'.php');
}
}
if(is_file($viewFile.'.php'))
return EO::app()->findLocalizedFile($viewFile.'.php');
else
return false;
}
/**
* Render the view file
* @param string $viewName Name of the view
* @param array $viewData Data for extraction
* @return string The rendered result
* @throws CException
*/
public function renderView($viewName,$viewData=null)
{
//resolve the file name
if(($viewFile=$this->getViewFile($viewName))!==false)
{
//use controller instance if available or create dummy controller for console applications
if(isset(EO::app()->controller))
$controller=EO::app()->controller;
else
$controller=new CController(__CLASS__);
//render and return the result
return $controller->renderInternal($viewFile,$viewData,true);
}
else
{
//file name does not exist
throw new CException('View "'.$viewName.'" does not exist!');
}
}
/**
* Generates HTML email, with or without layout
*/
public function render()
{
//render view as body if specified
if(isset($this->view))
$this->setBody($this->renderView($this->viewPath.'.'.$this->view, $this->data));
//render with layout if given
if($this->layout)
{
//has layout
$this->MsgHTMLWithLayout($this->Body, EO::getPathOfAlias($this->baseDirPath));
}
else
{
//no layout
$this->MsgHTML($this->Body, EO::getPathOfAlias($this->baseDirPath));
}
}
/**
* Render HTML email message with layout
* @param string $message Email message
* @param string $basedir Path for images to embed in message
*/
protected function MsgHTMLWithLayout($message, $basedir = '')
{
$this->MsgHTML($this->renderView($this->layoutPath.'.'.$this->layout, ['content'=>$message,'data'=>$this->data]), $basedir);
}
/**
* Render message and send emails
* @return boolean True if sent successfully, false otherwise
*/
public function send()
{
//render message
$this->render();
//send the message
try{
//prepare the message
if(!$this->PreSend())
return false;
//in test mode, save message as a file
if($this->testMode)
return $this->save();
else
return $this->PostSend();
} catch (phpmailerException $e) {
$this->mailHeader = '';
$this->SetError($e->getMessage());
if ($this->exceptions) {
throw $e;
}
return false;
}
}
/**
* Save message as eml file
* @return boolean True if saved successfully, false otherwise
*/
public function save()
{
$filename = date('YmdHis') . '_' . uniqid() . '.eml';
$dir = EO::getPathOfAlias($this->savePath);
//check if dir exists and is writable
if(!is_writable($dir))
throw new CException('Directory "'.$dir.'" does not exist or is not writable!');
try {
$file = fopen($dir . DIRECTORY_SEPARATOR . $filename,'w+');
fwrite($file, $this->GetSentMIMEMessage());
fclose($file);
return true;
} catch(Exception $e) {
$this->SetError($e->getMessage());
return false;
}
}
}