-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPhpMailer.php
More file actions
275 lines (224 loc) · 9.3 KB
/
PhpMailer.php
File metadata and controls
275 lines (224 loc) · 9.3 KB
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
<?php
declare(strict_types=1);
/*
* This file is part of the QuidPHP package <https://quidphp.com>
* Author: Pierre-Philippe Emond <emondpph@gmail.com>
* License: https://github.com/quidphp/core/blob/master/LICENSE
*/
namespace Quid\Core\Service;
use Quid\Base;
use Quid\Core;
use Quid\Main;
// phpMailer
// class that provides methods to use phpmailer/phpmailer in order to send emails
class PhpMailer extends Core\ServiceMailerAlias
{
// config
protected static array $config = [
'ping'=>2, // fait un ping avant l'envoie
'kill'=>null, // permet de tuer le script après un envoie (permet d'afficher le debug)
'username'=>null, // username pour connexion smtp
'password'=>null, // password pour connection smtp
'host'=>null, // host smtp
'port'=>25, // port de connection smtp
'encryption'=>false, // type d'encryption pour la connexion smtp
'timeout'=>5, // durée maximale d'éxécution lors de l'envoie du courriel
'autoTls'=>true, // active ou non le autoTsl dans phpMailer
'allowSelfSigned'=>null, // permet le fonctionnement si le certificat ssl est self-signed, si null utilise configuration de base/server
'debug'=>0, // code de débogage
'output'=>'html', // output de débogagge, seulement si debug pas vide (pourrait être une callable)
'charset'=>null, // charset du message
'contentType'=>null, // contentType du message
'subject'=>null, // sujet du message
'body'=>null, // corps du message
'priority'=>null, // x-priority du message
'xmailer'=>null, // x-mailer du message
'bcc'=>null, // copie-conforme invisible
'cc'=>null,// copie-conforme
'replyTo'=>null, // addresse replyTo
'to'=>null, // address To
'from'=>null, // address from, note name et email ont plus de priorités
'header'=>null, // tableau header additionnels
'oauthProviders'=>[ // permet de lier un provider à une classe de gestion oauth
'google'=>\League\OAuth2\Client\Provider\Google::class]
];
// prepare
// prépare l'objet et créer l'instance de l'objet mailer
// une exception peut être envoyé si les options ne sont pas valides
final protected function prepare():void
{
$this->checkReady(false);
$mailer = new \PHPMailer\PHPMailer\PHPMailer();
$this->mailer = $mailer;
}
// prepareMailer
// met à jour l'objet du mailer à partir d'un tableau de configuration
final protected function prepareMailer(array $value):void
{
$mailer = $this->mailer();
$mailer->clearAllRecipients();
$mailer->clearAttachments();
$mailer->isMail();
if(!empty($value['host']) && !empty($value['port']))
{
$mailer->isSMTP();
$mailer->Host = $value['host'];
$mailer->Port = $value['port'];
$mailer->AuthType = '';
$mailer->SMTPAuth = false;
$mailer->SMTPSecure = '';
$mailer->SMTPAutoTLS = false;
$mailer->SMTPOptions = [];
if(!empty($value['username']) && is_string($value['username']))
{
$mailer->SMTPAuth = true;
if(!empty($value['username']))
$mailer->Username = $value['username'];
if(array_key_exists('xoauth2',$value) && is_array($value['xoauth2']) && !empty($value['xoauth2']))
{
['provider'=>$xoauthProvider,'client'=>$xoauthClient,'secret'=>$xoauthSecret,'refresh'=>$xoauthRefresh] = $value['xoauth2'];
$oauth = $this->makeOauth($value['username'],$xoauthProvider,$xoauthClient,$xoauthSecret,$xoauthRefresh);
$mailer->AuthType = 'XOAUTH2';
$mailer->setOAuth($oauth);
}
elseif(array_key_exists('password',$value) && is_string($value['password']) && !empty($value['password']))
$mailer->Password = $value['password'];
}
if(array_key_exists('encryption',$value))
$mailer->SMTPSecure = $value['encryption'];
if(array_key_exists('autoTls',$value))
$mailer->SMTPAutoTLS = $value['autoTls'];
if(array_key_exists('allowSelfSigned',$value))
{
$value['allowSelfSigned'] ??= Base\Server::allowSelfSignedCertificate();
if(!empty($value['allowSelfSigned']))
{
$options = ['ssl'=>['verify_peer'=>false,'verify_peer_name'=>false,'allow_self_signed'=>true]];
$mailer->SMTPOptions = $options;
}
}
if(array_key_exists('timeout',$value))
$mailer->Timeout = $value['timeout'];
if(array_key_exists('debug',$value) || array_key_exists('output',$value))
$this->setDebug($value['debug'] ?? null,$value['output'] ?? null);
}
}
// prepareMailerMessage
// prépare le message et met à jour l'objet du mailer à partir d'un tableau
final protected function prepareMailerMessage(array $value):void
{
$mailer = $this->mailer();
$keyMethods = ['bcc'=>'addBCC','cc'=>'addCC','replyTo'=>'addReplyTo','to'=>'addAddress','from'=>'setFrom'];
$mailer->CharSet = $value['charset'];
$mailer->ContentType = $value['contentType'];
$mailer->Subject = $value['subject'];
$mailer->Body = $value['body'];
$mailer->Priority = (!empty($value['priority']) && is_numeric($value['priority']))? $value['priority']:null;
$mailer->XMailer = (!empty($value['xmailer']) && is_string($value['xmailer']))? $value['xmailer']:'';
foreach ($keyMethods as $k => $method)
{
if(!empty($value[$k]) && is_array($value[$k]))
{
if(!empty($value[$k]['email']) && is_string($value[$k]['email']))
$mailer->$method($value[$k]['email'],$value[$k]['name'] ?? '');
else
{
foreach ($value[$k] as $address)
{
if(is_array($address) && !empty($address['email']) && is_string($address['email']))
$mailer->$method($address['email'],$address['name'] ?? '');
}
}
}
}
if(!empty($value['header']) && is_array($value['header']))
{
foreach ($value['header'] as $k => $v)
{
if(is_string($k) && is_scalar($v))
$mailer->addCustomHeader($k,$v);
}
}
}
// error
// retourne la dernière erreur sur l'objet mailer
final public function error():string
{
return $this->mailer()->ErrorInfo;
}
// trigger
// envoie le courriel maintenant
// retourne un booléean
final public function trigger($value):bool
{
$return = false;
$mailer = $this->mailer();
$value = Base\Arr::replace($this->attr(),$value);
$message = [];
if(!empty($value['host']) && !empty($value['port']) && !empty($value['ping']) && is_int($value['ping']))
static::checkPing($value['host'],$value['port'],$value['ping']);
$this->prepareMailer($value);
try
{
$message = $this->prepareMessage($value);
$this->prepareMailerMessage($message);
if($this->isActive())
{
$return = $mailer->send();
$this->afterSend($return,$value);
}
else
$return = true;
}
catch (\Exception $e)
{
Main\Exception::staticCatched($e);
}
finally
{
$this->log($return,$message);
}
return $return;
}
// afterSend
// callback après l'envoie, gère le kill
final protected function afterSend(bool $return,array $value):void
{
$debug = $value['debug'] ?? null;
$kill = $value['kill'] ?? null;
if($debug === true && $kill === null)
$kill = true;
if($kill === true)
static::boot()->response()->kill();
}
// setDebug
// change les options de débogagge de l'objet mailer
// mettre 2 pour output
final public function setDebug($debug=0,$output=null):self
{
$mailer = $this->mailer();
if($debug === true)
$debug = 2;
elseif($debug === false || $debug === null)
$debug = 0;
if(is_int($debug))
{
$mailer->SMTPDebug = $debug;
$mailer->Debugoutput = (is_string($output))? $output:'html';
}
return $this;
}
// makeOauth
// génère l'objet oauth, utilisépour les connexions via Google (xoauth2)
final public function makeOauth(string $username,string $type,string $client,string $secret,string $refresh):\PHPMailer\PHPMailer\OAuth
{
$class = $this->getAttr(['oauthProviders',$type]) ?? static::throw('invalidProvider',$type);
$oauthClass = \PHPMailer\PHPMailer\OAuth::class;
$provider = new $class(['clientId'=>$client,'clientSecret'=>$secret]);
$args = ['provider'=>$provider,'userName'=>$username,'clientId'=>$client,'clientSecret'=>$secret,'refreshToken'=>$refresh];
return new $oauthClass($args);
}
}
// init
PhpMailer::__init();
?>