-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSendinblueMailer.php
407 lines (327 loc) · 10.9 KB
/
SendinblueMailer.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
<?php
Yii::setPathOfAlias( 'TijsVerkoyen', Yii::getPathOfAlias('ext') . DIRECTORY_SEPARATOR . basename(__DIR__) );
Yii::import( 'TijsVerkoyen.CssToInlineStyles.CssToInlineStyles' );
class SendinblueMailer extends CApplicationComponent {
public $to = array();
public $attributes = array();
public $subject = '';
public $view = null;
public $replyTo = null;
public $from;
public $layout;
public $cc = array();
public $bcc = array();
public $htmlContent = '';
public $tags = array();
public $apiKey = '';
public $inlineCss = true;
public $cssFileName = 'mail.css';
public $cssFilePath;
public $attachment = array();
/**
* 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';
/**
* Sets the CharSet of the message.
* @var string
*/
public $CharSet='UTF-8';
/**
* Sets the text-only body of the message.
* @var string
*/
public $AltBody='';
public $ErrorInfo = '';
const API_ENDPOINT = 'https://api.sendinblue.com/v3/';
/**
* Constants
*/
const CONFIG_FILE='mail.php'; //Define the name of the config file
const CONFIG_PARAMS='SendinblueMailer'; //Define the key of the Yii params for the config array
/**
* 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 $property => $value ) {
if ( ! property_exists( $this, $property ) ) {
continue;
}
$this->$property = $value;
}
}
public function init()
{
if(!$this->cssFilePath){
$this->cssFilePath = Yii::app()->theme->getBasePath() . DIRECTORY_SEPARATOR . 'css' . DIRECTORY_SEPARATOR;
}
//initialize config
if(isset(Yii::app()->params[self::CONFIG_PARAMS]))
$config=Yii::app()->params[self::CONFIG_PARAMS];
else
$config=require( Yii::getPathOfAlias('application.config') . DIRECTORY_SEPARATOR . self::CONFIG_FILE );
//set config
$this->setConfig($config);
parent::init();
}
public function setFrom( $from, $name = '' ){
$this->from = self::castAddress( $from, $name );
}
public function setTo( $tos, $clear = false ){
if ( $clear ) {
$this->to = array();
}
foreach( (array)$tos as $to ) {
$this->to[] = self::castAddress( $to );
}
}
public static function castAddress( $address, $name = '' ){
if( $name ) {
return [ 'email' => $address, 'name' => $name ];
} else {
return [ 'email' => $address ];
}
}
public function addReplyTo( $replyTo ){
$this->replyTo = self::castAddress( $replyTo );
}
/**
* 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( $ccs, $clear = false )
{
if ( $clear ) {
$this->cc = array();
}
foreach( (array)$ccs as $cc ) {
$this->cc[] = self::castAddress( $cc );
}
}
/**
* 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($bccs, $clear = false )
{
if ( $clear ) {
$this->bcc = array();
}
foreach( (array)$bccs as $bcc ) {
$this->bcc[] = self::castAddress( $bcc );
}
}
public function setSubject( $subject ){
$this->subject = $subject;
}
public function setView( $view ){
if($view == '')
{
return;
}
$this->view = $view;
}
public function setLayout( $layout ){
if($layout!='')
{
if(!is_file($this->getViewFile($this->layoutPath.'.'.$layout)))
throw new CException('Layout "'.$layout.'" not found!');
$this->layout=$layout;
}
}
public function setBody( $content ){
$this->htmlContent = $content;
}
public function setData( $attributes ){
$this->attributes = $attributes;
}
public function render( $inlineCss = true ){
if ( $this->view && ! is_numeric( $this->view ) ) {
if( ! is_file( $this->getViewFile( $this->viewPath . '.' . $this->view ) ) ) {
throw new CException('View "'.$view.'" not found');
}
$htmlContent = $this->renderView( $this->viewPath.'.'.$this->view, $this->attributes );
}
if( $this->layout ) {
$htmlContent = $this->renderView( $this->layoutPath . '.' . $this->layout, array( 'content' => $htmlContent, 'data' => $this->attributes ), Yii::getPathOfAlias($this->baseDirPath) );
}
if( $this->inlineCss && $inlineCss ) {
$this->htmlContent = $this->inlineCss( $htmlContent );
} else {
$this->htmlContent = $htmlContent;
}
$this->onRender( new CEvent($this, array( 'htmlContent' => $htmlContent ) ) );
}
public function inlineCss( $html ){
try{
$inliner = new \TijsVerkoyen\CssToInlineStyles\CssToInlineStyles($html, file_get_contents($this->cssFilePath.$this->cssFileName));
$html = $inliner->convert();
} catch (Exception $e){
Yii::trace('Cannot convert CSS to inline. Error:'.$e);
}
return $html;
}
/**
* 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(Yii::app()->controller))
$controller=Yii::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!');
}
}
/**
* 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(Yii::app()->controller))
return Yii::app()->controller->getViewFile($viewName);
//resolve the view file
//TODO: support for themes in console applications
if(empty($viewName))
return false;
$viewFile=Yii::getPathOfAlias($viewName);
if(is_file($viewFile.'.php'))
return Yii::app()->findLocalizedFile($viewFile.'.php');
else
return false;
}
public static function flatten($array, $prefix = '') {
$output = array();
foreach ($array as $key => $value) {
if (is_array($value)){
$output = array_merge( $output, self::flatten($value, $key . '_' ));
} elseif( $value instanceof CModel ) {
$output = array_merge( $output, self::flatten( $value->attributes, $key . '_' ) );
} else {
$output[$prefix . $key] = $value;
}
}
return $output;
}
public function onRender($event){
$this->raiseEvent('onRender', $event);
}
public function onSend($event){
$this->raiseEvent('onSend', $event);
}
public function send(){
$params = array(
'to' => $this->to,
'params' => self::flatten( $this->attributes ),
'subject' => $this->subject,
'replyTo' => $this->replyTo,
);
if ( $this->view && is_numeric( $this->view ) ) {
$params['templateId'] = $this->view;
$params['params'] = $this->attributes;
} else {
$this->render();
$params['htmlContent'] = $this->htmlContent;
$params['sender'] = $this->from;
}
if( !empty( $this->attachment ) ) {
$params['attachment'] = $this->attachment;
}
$this->onSend( new CEvent($this, $params) );
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => self::API_ENDPOINT . '/smtp/email',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'api-key: ' . $this->apiKey,
),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode( array_filter( $params ) ),
));
$response = curl_exec($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
$this->SetError( $err );
return false;
} else if( substr($httpCode, 0, 1) !== '2' ) {
$respObject = json_decode( $response );
if( isset( $respObject->message ) ) {
$this->SetError( 'Sendinblue: ' . $respObject->message );
}
return false;
} else {
return true;
}
}
/**
* Add an attachment from a path on the filesystem.
* Never use a user-supplied path to a file!
* Returns false if the file could not be found or read.
*
* @param string $path Path to the attachment
* @param string $name Overrides the attachment name
*
* @throws Exception
*
* @return bool
*/
public function addAttachment($url, $name = '' )
{
$this->attachment[] = array(
'url' => $url,
'name' => $name,
);
}
/**
* Get current error message
* @return string Error message
*/
public function getError()
{
return $this->ErrorInfo;
}
/**
* Set current error message
* @return string Error message
*/
public function setError( $message )
{
Yii::log( $message, 'error', 'ext.yii-mailer-sendinblue.SendinblueMailer' );
$this->ErrorInfo = $message;
}
}