CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Team
    • Issues (Github)
    • YouTube Channel
    • Get Involved
    • Bakery
    • Featured Resources
    • Newsletter
    • Certification
    • My CakePHP
    • CakeFest
    • Facebook
    • Twitter
    • Help & Support
    • Forum
    • Stack Overflow
    • IRC
    • Slack
    • Paid Support
CakePHP

C CakePHP 3.8 Red Velvet API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 3.8
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Namespaces

  • Cake
    • Auth
      • Storage
    • Cache
      • Engine
    • Collection
      • Iterator
    • Command
    • Console
      • Exception
    • Controller
      • Component
      • Exception
    • Core
      • Configure
        • Engine
      • Exception
      • Retry
    • Database
      • Driver
      • Exception
      • Expression
      • Schema
      • Statement
      • Type
    • Datasource
      • Exception
    • Error
      • Middleware
    • Event
      • Decorator
    • Filesystem
    • Form
    • Http
      • Client
        • Adapter
        • Auth
      • Cookie
      • Exception
      • Middleware
      • Session
    • I18n
      • Formatter
      • Middleware
      • Parser
    • Log
      • Engine
    • Mailer
      • Exception
      • Transport
    • Network
      • Exception
    • ORM
      • Association
      • Behavior
        • Translate
      • Exception
      • Locator
      • Rule
    • Routing
      • Exception
      • Filter
      • Middleware
      • Route
    • Shell
      • Helper
      • Task
    • TestSuite
      • Fixture
      • Stub
    • Utility
      • Exception
    • Validation
    • View
      • Exception
      • Form
      • Helper
      • Widget
  • None

Classes

  • DebugTransport
  • MailTransport
  • SmtpTransport
  1: <?php
  2: /**
  3:  * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4:  * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5:  *
  6:  * Licensed under The MIT License
  7:  * For full copyright and license information, please see the LICENSE.txt
  8:  * Redistributions of files must retain the above copyright notice.
  9:  *
 10:  * @copyright     Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 11:  * @link          https://cakephp.org CakePHP(tm) Project
 12:  * @since         2.0.0
 13:  * @license       https://opensource.org/licenses/mit-license.php MIT License
 14:  */
 15: namespace Cake\Mailer\Transport;
 16: 
 17: use Cake\Mailer\AbstractTransport;
 18: use Cake\Mailer\Email;
 19: use Cake\Network\Exception\SocketException;
 20: use Cake\Network\Socket;
 21: use Exception;
 22: 
 23: /**
 24:  * Send mail using SMTP protocol
 25:  */
 26: class SmtpTransport extends AbstractTransport
 27: {
 28:     /**
 29:      * Default config for this class
 30:      *
 31:      * @var array
 32:      */
 33:     protected $_defaultConfig = [
 34:         'host' => 'localhost',
 35:         'port' => 25,
 36:         'timeout' => 30,
 37:         'username' => null,
 38:         'password' => null,
 39:         'client' => null,
 40:         'tls' => false,
 41:         'keepAlive' => false
 42:     ];
 43: 
 44:     /**
 45:      * Socket to SMTP server
 46:      *
 47:      * @var \Cake\Network\Socket|null
 48:      */
 49:     protected $_socket;
 50: 
 51:     /**
 52:      * Content of email to return
 53:      *
 54:      * @var array
 55:      */
 56:     protected $_content = [];
 57: 
 58:     /**
 59:      * The response of the last sent SMTP command.
 60:      *
 61:      * @var array
 62:      */
 63:     protected $_lastResponse = [];
 64: 
 65:     /**
 66:      * Destructor
 67:      *
 68:      * Tries to disconnect to ensure that the connection is being
 69:      * terminated properly before the socket gets closed.
 70:      */
 71:     public function __destruct()
 72:     {
 73:         try {
 74:             $this->disconnect();
 75:         } catch (Exception $e) {
 76:             // avoid fatal error on script termination
 77:         }
 78:     }
 79: 
 80:     /**
 81:      * Unserialize handler.
 82:      *
 83:      * Ensure that the socket property isn't reinitialized in a broken state.
 84:      *
 85:      * @return void
 86:      */
 87:     public function __wakeup()
 88:     {
 89:         $this->_socket = null;
 90:     }
 91: 
 92:     /**
 93:      * Connect to the SMTP server.
 94:      *
 95:      * This method tries to connect only in case there is no open
 96:      * connection available already.
 97:      *
 98:      * @return void
 99:      */
100:     public function connect()
101:     {
102:         if (!$this->connected()) {
103:             $this->_connect();
104:             $this->_auth();
105:         }
106:     }
107: 
108:     /**
109:      * Check whether an open connection to the SMTP server is available.
110:      *
111:      * @return bool
112:      */
113:     public function connected()
114:     {
115:         return $this->_socket !== null && $this->_socket->connected;
116:     }
117: 
118:     /**
119:      * Disconnect from the SMTP server.
120:      *
121:      * This method tries to disconnect only in case there is an open
122:      * connection available.
123:      *
124:      * @return void
125:      */
126:     public function disconnect()
127:     {
128:         if ($this->connected()) {
129:             $this->_disconnect();
130:         }
131:     }
132: 
133:     /**
134:      * Returns the response of the last sent SMTP command.
135:      *
136:      * A response consists of one or more lines containing a response
137:      * code and an optional response message text:
138:      * ```
139:      * [
140:      *     [
141:      *         'code' => '250',
142:      *         'message' => 'mail.example.com'
143:      *     ],
144:      *     [
145:      *         'code' => '250',
146:      *         'message' => 'PIPELINING'
147:      *     ],
148:      *     [
149:      *         'code' => '250',
150:      *         'message' => '8BITMIME'
151:      *     ],
152:      *     // etc...
153:      * ]
154:      * ```
155:      *
156:      * @return array
157:      */
158:     public function getLastResponse()
159:     {
160:         return $this->_lastResponse;
161:     }
162: 
163:     /**
164:      * Send mail
165:      *
166:      * @param \Cake\Mailer\Email $email Email instance
167:      * @return array
168:      * @throws \Cake\Network\Exception\SocketException
169:      */
170:     public function send(Email $email)
171:     {
172:         if (!$this->connected()) {
173:             $this->_connect();
174:             $this->_auth();
175:         } else {
176:             $this->_smtpSend('RSET');
177:         }
178: 
179:         $this->_sendRcpt($email);
180:         $this->_sendData($email);
181: 
182:         if (!$this->_config['keepAlive']) {
183:             $this->_disconnect();
184:         }
185: 
186:         return $this->_content;
187:     }
188: 
189:     /**
190:      * Parses and stores the response lines in `'code' => 'message'` format.
191:      *
192:      * @param string[] $responseLines Response lines to parse.
193:      * @return void
194:      */
195:     protected function _bufferResponseLines(array $responseLines)
196:     {
197:         $response = [];
198:         foreach ($responseLines as $responseLine) {
199:             if (preg_match('/^(\d{3})(?:[ -]+(.*))?$/', $responseLine, $match)) {
200:                 $response[] = [
201:                     'code' => $match[1],
202:                     'message' => isset($match[2]) ? $match[2] : null
203:                 ];
204:             }
205:         }
206:         $this->_lastResponse = array_merge($this->_lastResponse, $response);
207:     }
208: 
209:     /**
210:      * Connect to SMTP Server
211:      *
212:      * @return void
213:      * @throws \Cake\Network\Exception\SocketException
214:      */
215:     protected function _connect()
216:     {
217:         $this->_generateSocket();
218:         if (!$this->_socket->connect()) {
219:             throw new SocketException('Unable to connect to SMTP server.');
220:         }
221:         $this->_smtpSend(null, '220');
222: 
223:         $config = $this->_config;
224: 
225:         if (isset($config['client'])) {
226:             $host = $config['client'];
227:         } elseif ($httpHost = env('HTTP_HOST')) {
228:             list($host) = explode(':', $httpHost);
229:         } else {
230:             $host = 'localhost';
231:         }
232: 
233:         try {
234:             $this->_smtpSend("EHLO {$host}", '250');
235:             if ($config['tls']) {
236:                 $this->_smtpSend('STARTTLS', '220');
237:                 $this->_socket->enableCrypto('tls');
238:                 $this->_smtpSend("EHLO {$host}", '250');
239:             }
240:         } catch (SocketException $e) {
241:             if ($config['tls']) {
242:                 throw new SocketException('SMTP server did not accept the connection or trying to connect to non TLS SMTP server using TLS.', null, $e);
243:             }
244:             try {
245:                 $this->_smtpSend("HELO {$host}", '250');
246:             } catch (SocketException $e2) {
247:                 throw new SocketException('SMTP server did not accept the connection.', null, $e2);
248:             }
249:         }
250:     }
251: 
252:     /**
253:      * Send authentication
254:      *
255:      * @return void
256:      * @throws \Cake\Network\Exception\SocketException
257:      */
258:     protected function _auth()
259:     {
260:         if (isset($this->_config['username'], $this->_config['password'])) {
261:             $replyCode = (string)$this->_smtpSend('AUTH LOGIN', '334|500|502|504');
262:             if ($replyCode === '334') {
263:                 try {
264:                     $this->_smtpSend(base64_encode($this->_config['username']), '334');
265:                 } catch (SocketException $e) {
266:                     throw new SocketException('SMTP server did not accept the username.', null, $e);
267:                 }
268:                 try {
269:                     $this->_smtpSend(base64_encode($this->_config['password']), '235');
270:                 } catch (SocketException $e) {
271:                     throw new SocketException('SMTP server did not accept the password.', null, $e);
272:                 }
273:             } elseif ($replyCode === '504') {
274:                 throw new SocketException('SMTP authentication method not allowed, check if SMTP server requires TLS.');
275:             } else {
276:                 throw new SocketException('AUTH command not recognized or not implemented, SMTP server may not require authentication.');
277:             }
278:         }
279:     }
280: 
281:     /**
282:      * Prepares the `MAIL FROM` SMTP command.
283:      *
284:      * @param string $email The email address to send with the command.
285:      * @return string
286:      */
287:     protected function _prepareFromCmd($email)
288:     {
289:         return 'MAIL FROM:<' . $email . '>';
290:     }
291: 
292:     /**
293:      * Prepares the `RCPT TO` SMTP command.
294:      *
295:      * @param string $email The email address to send with the command.
296:      * @return string
297:      */
298:     protected function _prepareRcptCmd($email)
299:     {
300:         return 'RCPT TO:<' . $email . '>';
301:     }
302: 
303:     /**
304:      * Prepares the `from` email address.
305:      *
306:      * @param \Cake\Mailer\Email $email Email instance
307:      * @return array
308:      */
309:     protected function _prepareFromAddress($email)
310:     {
311:         $from = $email->getReturnPath();
312:         if (empty($from)) {
313:             $from = $email->getFrom();
314:         }
315: 
316:         return $from;
317:     }
318: 
319:     /**
320:      * Prepares the recipient email addresses.
321:      *
322:      * @param \Cake\Mailer\Email $email Email instance
323:      * @return array
324:      */
325:     protected function _prepareRecipientAddresses($email)
326:     {
327:         $to = $email->getTo();
328:         $cc = $email->getCc();
329:         $bcc = $email->getBcc();
330: 
331:         return array_merge(array_keys($to), array_keys($cc), array_keys($bcc));
332:     }
333: 
334:     /**
335:      * Prepares the message headers.
336:      *
337:      * @param \Cake\Mailer\Email $email Email instance
338:      * @return array
339:      */
340:     protected function _prepareMessageHeaders($email)
341:     {
342:         return $email->getHeaders(['from', 'sender', 'replyTo', 'readReceipt', 'to', 'cc', 'subject', 'returnPath']);
343:     }
344: 
345:     /**
346:      * Prepares the message body.
347:      *
348:      * @param \Cake\Mailer\Email $email Email instance
349:      * @return string
350:      */
351:     protected function _prepareMessage($email)
352:     {
353:         $lines = $email->message();
354:         $messages = [];
355:         foreach ($lines as $line) {
356:             if (!empty($line) && ($line[0] === '.')) {
357:                 $messages[] = '.' . $line;
358:             } else {
359:                 $messages[] = $line;
360:             }
361:         }
362: 
363:         return implode("\r\n", $messages);
364:     }
365: 
366:     /**
367:      * Send emails
368:      *
369:      * @return void
370:      * @param \Cake\Mailer\Email $email Cake Email
371:      * @throws \Cake\Network\Exception\SocketException
372:      */
373:     protected function _sendRcpt($email)
374:     {
375:         $from = $this->_prepareFromAddress($email);
376:         $this->_smtpSend($this->_prepareFromCmd(key($from)));
377: 
378:         $emails = $this->_prepareRecipientAddresses($email);
379:         foreach ($emails as $mail) {
380:             $this->_smtpSend($this->_prepareRcptCmd($mail));
381:         }
382:     }
383: 
384:     /**
385:      * Send Data
386:      *
387:      * @param \Cake\Mailer\Email $email Email instance
388:      * @return void
389:      * @throws \Cake\Network\Exception\SocketException
390:      */
391:     protected function _sendData($email)
392:     {
393:         $this->_smtpSend('DATA', '354');
394: 
395:         $headers = $this->_headersToString($this->_prepareMessageHeaders($email));
396:         $message = $this->_prepareMessage($email);
397: 
398:         $this->_smtpSend($headers . "\r\n\r\n" . $message . "\r\n\r\n\r\n.");
399:         $this->_content = ['headers' => $headers, 'message' => $message];
400:     }
401: 
402:     /**
403:      * Disconnect
404:      *
405:      * @return void
406:      * @throws \Cake\Network\Exception\SocketException
407:      */
408:     protected function _disconnect()
409:     {
410:         $this->_smtpSend('QUIT', false);
411:         $this->_socket->disconnect();
412:     }
413: 
414:     /**
415:      * Helper method to generate socket
416:      *
417:      * @return void
418:      * @throws \Cake\Network\Exception\SocketException
419:      */
420:     protected function _generateSocket()
421:     {
422:         $this->_socket = new Socket($this->_config);
423:     }
424: 
425:     /**
426:      * Protected method for sending data to SMTP connection
427:      *
428:      * @param string|null $data Data to be sent to SMTP server
429:      * @param string|bool $checkCode Code to check for in server response, false to skip
430:      * @return string|null The matched code, or null if nothing matched
431:      * @throws \Cake\Network\Exception\SocketException
432:      */
433:     protected function _smtpSend($data, $checkCode = '250')
434:     {
435:         $this->_lastResponse = [];
436: 
437:         if ($data !== null) {
438:             $this->_socket->write($data . "\r\n");
439:         }
440: 
441:         $timeout = $this->_config['timeout'];
442: 
443:         while ($checkCode !== false) {
444:             $response = '';
445:             $startTime = time();
446:             while (substr($response, -2) !== "\r\n" && ((time() - $startTime) < $timeout)) {
447:                 $bytes = $this->_socket->read();
448:                 if ($bytes === false || $bytes === null) {
449:                     break;
450:                 }
451:                 $response .= $bytes;
452:             }
453:             if (substr($response, -2) !== "\r\n") {
454:                 throw new SocketException('SMTP timeout.');
455:             }
456:             $responseLines = explode("\r\n", rtrim($response, "\r\n"));
457:             $response = end($responseLines);
458: 
459:             $this->_bufferResponseLines($responseLines);
460: 
461:             if (preg_match('/^(' . $checkCode . ')(.)/', $response, $code)) {
462:                 if ($code[2] === '-') {
463:                     continue;
464:                 }
465: 
466:                 return $code[1];
467:             }
468:             throw new SocketException(sprintf('SMTP Error: %s', $response));
469:         }
470:     }
471: }
472: 
Follow @CakePHP
#IRC
OpenHub
Rackspace
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Logos & Trademarks
  • Community
  • Team
  • Issues (Github)
  • YouTube Channel
  • Get Involved
  • Bakery
  • Featured Resources
  • Newsletter
  • Certification
  • My CakePHP
  • CakeFest
  • Facebook
  • Twitter
  • Help & Support
  • Forum
  • Stack Overflow
  • IRC
  • Slack
  • Paid Support

Generated using CakePHP API Docs