forked from ikkez/f3-mailer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mailer.php
398 lines (364 loc) · 9.67 KB
/
mailer.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
<?php
/**
* Sugar Mailer
*
* The contents of this file are subject to the terms of the GNU General
* Public License Version 3.0. You may not use this file except in
* compliance with the license. Any of the license terms and conditions
* can be waived if you get permission from the copyright holder.
*
* Copyright (c) 2020 ~ ikkez
* Christian Knuth <[email protected]>
* https://github.com/ikkez/F3-Sugar/
*
* @version 1.2.2
* @date: 14.01.2020
*/
class Mailer {
/** @var SMTP */
protected $smtp;
protected
$recipients =[],
$charset;
static
$EOL="\r\n",
$queue = [];
public
$message = [],
$subject = "";
/**
* create mailer instance working with a specific charset
* usually one of these:
* ISO-8859-1
* ISO-8859-15
* UTF-8
* @param string $enforceCharset
*/
public function __construct($enforceCharset='UTF-8') {
$this->charset = $enforceCharset;
$this->reset();
}
/**
* initialize SMTP plugin
*/
public function initSMTP() {
/** @var \Base $f3 */
$f3 = \Base::instance();
$this->smtp = new \SMTP(
$f3->get('mailer.smtp.host'),
$f3->get('mailer.smtp.port'),
$f3->get('mailer.smtp.scheme'),
$f3->get('mailer.smtp.user'),
$f3->get('mailer.smtp.pw'));
if (!$f3->devoid('mailer.errors_to',$errors_to))
$this->setErrors($errors_to);
if (!$f3->devoid('mailer.reply_to',$reply_to))
$this->setReply($reply_to);
if (!$f3->devoid('mailer.from_mail',$from_mail)) {
if ($f3->devoid('mailer.from_name',$from_name))
$from_name = NULL;
$this->setFrom($from_mail, $from_name);
}
}
/**
* encode special chars if possible
* @param $str
* @return mixed
*/
protected function encode($str) {
if (empty($str) || $this->charset == 'UTF-8')
return $str;
if (extension_loaded('iconv'))
$out = @iconv("UTF-8", $this->charset."//IGNORE", $str);
if (!isset($out) || !$out)
$out = extension_loaded('mbstring')
? mb_convert_encoding($str,$this->charset,"UTF-8")
: utf8_decode($str);
return $out ?: $str;
}
/**
* encode and split header strings
* @param $str
* @return string
*/
protected function encodeHeader($str) {
if (extension_loaded('iconv')) {
$out = iconv_mime_encode('Subject', $str,
['input-charset' => 'UTF-8', 'output-charset' => $this->charset]);
$out = substr($out, strlen('Subject: '));
} elseif(extension_loaded('mbstring')) {
mb_internal_encoding('UTF-8');
$out = mb_encode_mimeheader($str, $this->charset, 'B', static::$EOL, strlen('Subject: '));
} else
$out = wordwrap($str,65,static::$EOL);
return $out;
}
/**
* build email with title string
* @param $email
* @param null $title
* @return string
*/
protected function buildMail($email, $title=null) {
return ($title?'"'.$this->encodeHeader($title).'" ':'').'<'.$email.'>';
}
/**
* set encoded header value
* @param $key
* @param $val
*/
public function set($key, $val) {
$this->smtp->set($key, $this->encode($val));
}
/**
* set message sender
* @param $email
* @param null $title
*/
public function setFrom($email, $title=null) {
$this->set('From', $this->buildMail($email,$title));
}
/**
* add a direct recipient
* @param $email
* @param null $title
*/
public function addTo($email, $title=null) {
$this->recipients['To'][$email] = $title;
}
/**
* add a carbon copy recipient
* @param $email
* @param null $title
*/
public function addCc($email, $title=null) {
$this->recipients['Cc'][$email] = $title;
}
/**
* add a blind carbon copy recipient
* @param $email
* @param null $title
*/
public function addBcc($email, $title=null) {
$this->recipients['Bcc'][$email] = $title;
}
/**
* set reply-to field respected by most email clients
* @param $email
* @param null $title
*/
public function setReply($email, $title=null) {
$this->set('Reply-To', $this->buildMail($email,$title));
}
/**
* set receipient for bounce error mails
* @param $email
* @param null $title
*/
public function setErrors($email, $title=null) {
$this->set('Sender', $this->buildMail($email,$title));
}
/**
* reset recipients if key was given, or restart whole smtp plugin
* @param null $key
*/
public function reset($key=null) {
if ($key) {
$key = ucfirst($key);
$this->smtp->clear($key);
if (isset($this->recipients[$key]))
unset($this->recipients[$key]);
} else {
$this->recipients = [];
$this->initSMTP();
}
}
/**
* set message in plain text format
* @param $message
*/
public function setText($message) {
$this->setContent($message,'text/plain');
}
/**
* set message in HTML text format
* @param $message
*/
public function setHTML($message) {
$f3 = \Base::instance();
// we need a clean template instance for extending it one-time
$tmpl = new \Template();
// create traceable jump links
if ($f3->exists('mailer.jumplinks',$jumplink) && $jumplink)
$tmpl->extend('a', function($node) use($f3, $tmpl) {
if (isset($node['@attrib'])) {
$attr = $node['@attrib'];
unset($node['@attrib']);
} else
$attr = [];
if (isset($attr['href'])) {
if (!$f3->exists('mailer.jump_route',$ping_route))
$ping_route = '/mailer-jump';
$attr['href'] = $f3->get('SCHEME').'://'.$f3->get('HOST').$f3->get('BASE').
$ping_route.'?target='.urlencode($attr['href']);
}
$params = '';
foreach ($attr as $key => $value)
$params.=' '.$key.'="'.$value.'"';
return '<a'.$params.'>'.$tmpl->build($node).'</a>';
});
$message = $tmpl->build($tmpl->parse($message));
$this->setContent($message,'text/html');
}
/**
* set message contents by mime type
* @param string $data message data
* @param string $mime the mime type
* @param null $charset
*/
public function setContent($data, $mime, $charset=NULL) {
if (!$charset)
$charset=$this->charset;
$this->message[$mime] = [
'content'=>$data,
'type'=>$mime.'; charset='.$charset
];
}
/**
* add a file attachment
* @param $path
* @param null $alias
* @param null $cid
*/
public function attachFile($path, $alias=null, $cid=null) {
$this->smtp->attach($path,$alias,$cid);
}
/**
* send message
* @param $subject
* @param bool $mock
* @param bool|string $log log level [false,true,'verbose']
* @return bool
*/
public function send($subject, $mock=false, $log='verbose') {
foreach ($this->recipients as $key => $rcpts) {
$mails = [];
foreach ($rcpts as $mail=>$title)
$mails[] = $this->buildMail($mail,$title);
$this->set($key,implode(', ',$mails));
}
$this->smtp->set('Subject', $this->encodeHeader($this->encode($subject)));
$body = '';
$hash=uniqid(NULL,TRUE);
$multipart = count($this->message) > 1;
if ($multipart)
$this->smtp->set('Content-Type', 'multipart/alternative; boundary="'.$hash.'"');
foreach ($this->message as $msg) {
if ($multipart) {
$body .= '--'.$hash.static::$EOL;
$body .= 'Content-Type: '.$msg['type'].static::$EOL.static::$EOL;
} else
$this->smtp->set('Content-Type', $msg['type']);
$body .= $msg['content'].static::$EOL.static::$EOL;
}
if ($multipart)
$body .= '--'.$hash.'--'.static::$EOL;
$success = $this->smtp->send($this->encode($body),$log,$mock);
$f3 = \Base::instance();
if (!$success && $f3->exists('mailer.on.failure',$fail_handler))
$f3->call($fail_handler,[$this,$this->smtp->log()]);
return $success;
}
/**
* save the send mail to disk
* @param $filename
*/
public function save($filename) {
$f3 = \Base::instance();
$lines = explode("\n",$this->smtp->log());
$start = false;
$out = '';
for($i=0,$max=count($lines);$i<$max;$i++) {
if (!$start && preg_match('/^354.*?$/',$lines[$i],$matches)) {
$start=true;
continue;
} elseif (preg_match('/^250.*?$\s^QUIT/m',
$lines[$i].($i+1 < $max ? "\n".$lines[$i+1] : ''),$matches))
break;
if ($start)
$out.=$lines[$i]."\n";
}
if ($out) {
$path = $f3->get('mailer.storage_path');
if (!is_dir($path))
mkdir($path,0777,true);
$f3->write($path.$filename,$out);
}
}
/**
* queue this instance of mailer to process later
*/
public function queue ($subject) {
$this->subject = $subject;
Mailer::$queue[] = $this;
}
/**
* process all instances of mailer
*/
static public function processQueue () {
if (!isset(Mailer::$queue) || count(Mailer::$queue) == 0) {
return;
}
foreach (Mailer::$queue as $mailer) {
$mailer->send($mailer->subject);
}
}
/**
* expose smtp log
* @return mixed
*/
public function log() {
return $this->smtp->log();
}
/**
* receive and proceed message ping
* @param Base $f3
* @param $params
*/
static public function ping(\Base $f3, $params) {
$hash = $params['hash'];
// trigger ping event
if ($f3->exists('mailer.on.ping',$ping_handler))
$f3->call($ping_handler,[$hash]);
$img = new \Image();
// 1x1 transparent 8bit PNG
$img->load(base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMA'.
'AAAl21bKAAAABGdBTUEAALGPC/xhBQAAAANQTFRFAAAAp3o92gAAAAF0U'.
'k5TAEDm2GYAAAAKSURBVAjXY2AAAAACAAHiIbwzAAAAAElFTkSuQmCC'));
$img->render();
}
/**
* track clicked link and reroute
* @param Base $f3
*/
static public function jump(\Base $f3, $params) {
$target = $f3->get('GET.target');
// trigger jump event
if ($f3->exists('mailer.on.jump',$jump_handler))
$f3->call($jump_handler,[$target,$params]);
$f3->reroute(urldecode($target));
}
/**
* init routing
*/
static public function initTracking() {
/** @var \Base $f3 */
$f3 = \Base::instance();
if (!$f3->exists('mailer.ping_route',$ping_route))
$ping_route = '/mailer-ping/@hash.png';
$f3->route('GET '.$ping_route,'\Mailer::ping');
if (!$f3->exists('mailer.jump_route',$jump_route))
$jump_route = '/mailer-jump';
$f3->route('GET '.$jump_route,'\Mailer::jump');
}
}