/
SmtpTransport.php
460 lines (416 loc) · 12.4 KB
/
SmtpTransport.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
<?php
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 2.0.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\Mailer\Transport;
use Cake\Mailer\AbstractTransport;
use Cake\Mailer\Email;
use Cake\Network\Exception\SocketException;
use Cake\Network\Socket;
use Exception;
/**
* Send mail using SMTP protocol
*/
class SmtpTransport extends AbstractTransport
{
/**
* Default config for this class
*
* @var array
*/
protected $_defaultConfig = [
'host' => 'localhost',
'port' => 25,
'timeout' => 30,
'username' => null,
'password' => null,
'client' => null,
'tls' => false,
'keepAlive' => false
];
/**
* Socket to SMTP server
*
* @var \Cake\Network\Socket
*/
protected $_socket;
/**
* Content of email to return
*
* @var array
*/
protected $_content = [];
/**
* The response of the last sent SMTP command.
*
* @var array
*/
protected $_lastResponse = [];
/**
* Destructor
*
* Tries to disconnect to ensure that the connection is being
* terminated properly before the socket gets closed.
*/
public function __destruct()
{
try {
$this->disconnect();
} catch (Exception $e) {
// avoid fatal error on script termination
}
}
/**
* Connect to the SMTP server.
*
* This method tries to connect only in case there is no open
* connection available already.
*
* @return void
*/
public function connect()
{
if (!$this->connected()) {
$this->_connect();
$this->_auth();
}
}
/**
* Check whether an open connection to the SMTP server is available.
*
* @return bool
*/
public function connected()
{
return $this->_socket !== null && $this->_socket->connected;
}
/**
* Disconnect from the SMTP server.
*
* This method tries to disconnect only in case there is an open
* connection available.
*
* @return void
*/
public function disconnect()
{
if ($this->connected()) {
$this->_disconnect();
}
}
/**
* Returns the response of the last sent SMTP command.
*
* A response consists of one or more lines containing a response
* code and an optional response message text:
* ```
* [
* [
* 'code' => '250',
* 'message' => 'mail.example.com'
* ],
* [
* 'code' => '250',
* 'message' => 'PIPELINING'
* ],
* [
* 'code' => '250',
* 'message' => '8BITMIME'
* ],
* // etc...
* ]
* ```
*
* @return array
*/
public function getLastResponse()
{
return $this->_lastResponse;
}
/**
* Send mail
*
* @param \Cake\Mailer\Email $email Email instance
* @return array
* @throws \Cake\Network\Exception\SocketException
*/
public function send(Email $email)
{
if (!$this->connected()) {
$this->_connect();
$this->_auth();
} else {
$this->_smtpSend('RSET');
}
$this->_sendRcpt($email);
$this->_sendData($email);
if (!$this->_config['keepAlive']) {
$this->_disconnect();
}
return $this->_content;
}
/**
* Parses and stores the response lines in `'code' => 'message'` format.
*
* @param array $responseLines Response lines to parse.
* @return void
*/
protected function _bufferResponseLines(array $responseLines)
{
$response = [];
foreach ($responseLines as $responseLine) {
if (preg_match('/^(\d{3})(?:[ -]+(.*))?$/', $responseLine, $match)) {
$response[] = [
'code' => $match[1],
'message' => isset($match[2]) ? $match[2] : null
];
}
}
$this->_lastResponse = array_merge($this->_lastResponse, $response);
}
/**
* Connect to SMTP Server
*
* @return void
* @throws \Cake\Network\Exception\SocketException
*/
protected function _connect()
{
$this->_generateSocket();
if (!$this->_socket->connect()) {
throw new SocketException('Unable to connect to SMTP server.');
}
$this->_smtpSend(null, '220');
$config = $this->_config;
if (isset($config['client'])) {
$host = $config['client'];
} elseif ($httpHost = env('HTTP_HOST')) {
list($host) = explode(':', $httpHost);
} else {
$host = 'localhost';
}
try {
$this->_smtpSend("EHLO {$host}", '250');
if ($config['tls']) {
$this->_smtpSend('STARTTLS', '220');
$this->_socket->enableCrypto('tls');
$this->_smtpSend("EHLO {$host}", '250');
}
} catch (SocketException $e) {
if ($config['tls']) {
throw new SocketException('SMTP server did not accept the connection or trying to connect to non TLS SMTP server using TLS.', null, $e);
}
try {
$this->_smtpSend("HELO {$host}", '250');
} catch (SocketException $e2) {
throw new SocketException('SMTP server did not accept the connection.', null, $e2);
}
}
}
/**
* Send authentication
*
* @return void
* @throws \Cake\Network\Exception\SocketException
*/
protected function _auth()
{
if (isset($this->_config['username'], $this->_config['password'])) {
$replyCode = (string)$this->_smtpSend('AUTH LOGIN', '334|500|502|504');
if ($replyCode === '334') {
try {
$this->_smtpSend(base64_encode($this->_config['username']), '334');
} catch (SocketException $e) {
throw new SocketException('SMTP server did not accept the username.', null, $e);
}
try {
$this->_smtpSend(base64_encode($this->_config['password']), '235');
} catch (SocketException $e) {
throw new SocketException('SMTP server did not accept the password.', null, $e);
}
} elseif ($replyCode === '504') {
throw new SocketException('SMTP authentication method not allowed, check if SMTP server requires TLS.');
} else {
throw new SocketException('AUTH command not recognized or not implemented, SMTP server may not require authentication.');
}
}
}
/**
* Prepares the `MAIL FROM` SMTP command.
*
* @param string $email The email address to send with the command.
* @return string
*/
protected function _prepareFromCmd($email)
{
return 'MAIL FROM:<' . $email . '>';
}
/**
* Prepares the `RCPT TO` SMTP command.
*
* @param string $email The email address to send with the command.
* @return string
*/
protected function _prepareRcptCmd($email)
{
return 'RCPT TO:<' . $email . '>';
}
/**
* Prepares the `from` email address.
*
* @param \Cake\Mailer\Email $email Email instance
* @return array
*/
protected function _prepareFromAddress($email)
{
$from = $email->getReturnPath();
if (empty($from)) {
$from = $email->getFrom();
}
return $from;
}
/**
* Prepares the recipient email addresses.
*
* @param \Cake\Mailer\Email $email Email instance
* @return array
*/
protected function _prepareRecipientAddresses($email)
{
$to = $email->getTo();
$cc = $email->getCc();
$bcc = $email->getBcc();
return array_merge(array_keys($to), array_keys($cc), array_keys($bcc));
}
/**
* Prepares the message headers.
*
* @param \Cake\Mailer\Email $email Email instance
* @return array
*/
protected function _prepareMessageHeaders($email)
{
return $email->getHeaders(['from', 'sender', 'replyTo', 'readReceipt', 'to', 'cc', 'subject', 'returnPath']);
}
/**
* Prepares the message body.
*
* @param \Cake\Mailer\Email $email Email instance
* @return string
*/
protected function _prepareMessage($email)
{
$lines = $email->message();
$messages = [];
foreach ($lines as $line) {
if ((!empty($line)) && ($line[0] === '.')) {
$messages[] = '.' . $line;
} else {
$messages[] = $line;
}
}
return implode("\r\n", $messages);
}
/**
* Send emails
*
* @return void
* @param \Cake\Mailer\Email $email Cake Email
* @throws \Cake\Network\Exception\SocketException
*/
protected function _sendRcpt($email)
{
$from = $this->_prepareFromAddress($email);
$this->_smtpSend($this->_prepareFromCmd(key($from)));
$emails = $this->_prepareRecipientAddresses($email);
foreach ($emails as $mail) {
$this->_smtpSend($this->_prepareRcptCmd($mail));
}
}
/**
* Send Data
*
* @param \Cake\Mailer\Email $email Email instance
* @return void
* @throws \Cake\Network\Exception\SocketException
*/
protected function _sendData($email)
{
$this->_smtpSend('DATA', '354');
$headers = $this->_headersToString($this->_prepareMessageHeaders($email));
$message = $this->_prepareMessage($email);
$this->_smtpSend($headers . "\r\n\r\n" . $message . "\r\n\r\n\r\n.");
$this->_content = ['headers' => $headers, 'message' => $message];
}
/**
* Disconnect
*
* @return void
* @throws \Cake\Network\Exception\SocketException
*/
protected function _disconnect()
{
$this->_smtpSend('QUIT', false);
$this->_socket->disconnect();
}
/**
* Helper method to generate socket
*
* @return void
* @throws \Cake\Network\Exception\SocketException
*/
protected function _generateSocket()
{
$this->_socket = new Socket($this->_config);
}
/**
* Protected method for sending data to SMTP connection
*
* @param string|null $data Data to be sent to SMTP server
* @param string|bool $checkCode Code to check for in server response, false to skip
* @return string|null The matched code, or null if nothing matched
* @throws \Cake\Network\Exception\SocketException
*/
protected function _smtpSend($data, $checkCode = '250')
{
$this->_lastResponse = [];
if ($data !== null) {
$this->_socket->write($data . "\r\n");
}
$timeout = $this->_config['timeout'];
while ($checkCode !== false) {
$response = '';
$startTime = time();
while (substr($response, -2) !== "\r\n" && ((time() - $startTime) < $timeout)) {
$bytes = $this->_socket->read();
if ($bytes === false || $bytes === null) {
break;
}
$response .= $bytes;
}
if (substr($response, -2) !== "\r\n") {
throw new SocketException('SMTP timeout.');
}
$responseLines = explode("\r\n", rtrim($response, "\r\n"));
$response = end($responseLines);
$this->_bufferResponseLines($responseLines);
if (preg_match('/^(' . $checkCode . ')(.)/', $response, $code)) {
if ($code[2] === '-') {
continue;
}
return $code[1];
}
throw new SocketException(sprintf('SMTP Error: %s', $response));
}
}
}