vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php line 480

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of SwiftMailer.
  4.  * (c) 2004-2009 Chris Corbyn
  5.  *
  6.  * For the full copyright and license information, please view the LICENSE
  7.  * file that was distributed with this source code.
  8.  */
  9. /**
  10.  * Sends Messages over SMTP.
  11.  *
  12.  * @author Chris Corbyn
  13.  */
  14. abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport
  15. {
  16.     /** Input-Output buffer for sending/receiving SMTP commands and responses */
  17.     protected $buffer;
  18.     /** Connection status */
  19.     protected $started false;
  20.     /** The domain name to use in HELO command */
  21.     protected $domain '[127.0.0.1]';
  22.     /** The event dispatching layer */
  23.     protected $eventDispatcher;
  24.     protected $addressEncoder;
  25.     /** Whether the PIPELINING SMTP extension is enabled (RFC 2920) */
  26.     protected $pipelining null;
  27.     /** The pipelined commands waiting for response */
  28.     protected $pipeline = [];
  29.     /** Source Ip */
  30.     protected $sourceIp;
  31.     /** Return an array of params for the Buffer */
  32.     abstract protected function getBufferParams();
  33.     /**
  34.      * Creates a new EsmtpTransport using the given I/O buffer.
  35.      *
  36.      * @param string $localDomain
  37.      */
  38.     public function __construct(Swift_Transport_IoBuffer $bufSwift_Events_EventDispatcher $dispatcher$localDomain '127.0.0.1'Swift_AddressEncoder $addressEncoder null)
  39.     {
  40.         $this->buffer $buf;
  41.         $this->eventDispatcher $dispatcher;
  42.         $this->addressEncoder $addressEncoder ?? new Swift_AddressEncoder_IdnAddressEncoder();
  43.         $this->setLocalDomain($localDomain);
  44.     }
  45.     /**
  46.      * Set the name of the local domain which Swift will identify itself as.
  47.      *
  48.      * This should be a fully-qualified domain name and should be truly the domain
  49.      * you're using.
  50.      *
  51.      * If your server does not have a domain name, use the IP address. This will
  52.      * automatically be wrapped in square brackets as described in RFC 5321,
  53.      * section 4.1.3.
  54.      *
  55.      * @param string $domain
  56.      *
  57.      * @return $this
  58.      */
  59.     public function setLocalDomain($domain)
  60.     {
  61.         if ('[' !== substr($domain01)) {
  62.             if (filter_var($domainFILTER_VALIDATE_IPFILTER_FLAG_IPV4)) {
  63.                 $domain '['.$domain.']';
  64.             } elseif (filter_var($domainFILTER_VALIDATE_IPFILTER_FLAG_IPV6)) {
  65.                 $domain '[IPv6:'.$domain.']';
  66.             }
  67.         }
  68.         $this->domain $domain;
  69.         return $this;
  70.     }
  71.     /**
  72.      * Get the name of the domain Swift will identify as.
  73.      *
  74.      * If an IP address was specified, this will be returned wrapped in square
  75.      * brackets as described in RFC 5321, section 4.1.3.
  76.      *
  77.      * @return string
  78.      */
  79.     public function getLocalDomain()
  80.     {
  81.         return $this->domain;
  82.     }
  83.     /**
  84.      * Sets the source IP.
  85.      *
  86.      * @param string $source
  87.      */
  88.     public function setSourceIp($source)
  89.     {
  90.         $this->sourceIp $source;
  91.     }
  92.     /**
  93.      * Returns the IP used to connect to the destination.
  94.      *
  95.      * @return string
  96.      */
  97.     public function getSourceIp()
  98.     {
  99.         return $this->sourceIp;
  100.     }
  101.     public function setAddressEncoder(Swift_AddressEncoder $addressEncoder)
  102.     {
  103.         $this->addressEncoder $addressEncoder;
  104.     }
  105.     public function getAddressEncoder()
  106.     {
  107.         return $this->addressEncoder;
  108.     }
  109.     /**
  110.      * Start the SMTP connection.
  111.      */
  112.     public function start()
  113.     {
  114.         if (!$this->started) {
  115.             if ($evt $this->eventDispatcher->createTransportChangeEvent($this)) {
  116.                 $this->eventDispatcher->dispatchEvent($evt'beforeTransportStarted');
  117.                 if ($evt->bubbleCancelled()) {
  118.                     return;
  119.                 }
  120.             }
  121.             try {
  122.                 $this->buffer->initialize($this->getBufferParams());
  123.             } catch (Swift_TransportException $e) {
  124.                 $this->throwException($e);
  125.             }
  126.             $this->readGreeting();
  127.             $this->doHeloCommand();
  128.             if ($evt) {
  129.                 $this->eventDispatcher->dispatchEvent($evt'transportStarted');
  130.             }
  131.             $this->started true;
  132.         }
  133.     }
  134.     /**
  135.      * Test if an SMTP connection has been established.
  136.      *
  137.      * @return bool
  138.      */
  139.     public function isStarted()
  140.     {
  141.         return $this->started;
  142.     }
  143.     /**
  144.      * Send the given Message.
  145.      *
  146.      * Recipient/sender data will be retrieved from the Message API.
  147.      * The return value is the number of recipients who were accepted for delivery.
  148.      *
  149.      * @param string[] $failedRecipients An array of failures by-reference
  150.      *
  151.      * @return int
  152.      */
  153.     public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients null)
  154.     {
  155.         if (!$this->isStarted()) {
  156.             $this->start();
  157.         }
  158.         $sent 0;
  159.         $failedRecipients = (array) $failedRecipients;
  160.         if ($evt $this->eventDispatcher->createSendEvent($this$message)) {
  161.             $this->eventDispatcher->dispatchEvent($evt'beforeSendPerformed');
  162.             if ($evt->bubbleCancelled()) {
  163.                 return 0;
  164.             }
  165.         }
  166.         if (!$reversePath $this->getReversePath($message)) {
  167.             $this->throwException(new Swift_TransportException('Cannot send message without a sender address'));
  168.         }
  169.         $to = (array) $message->getTo();
  170.         $cc = (array) $message->getCc();
  171.         $tos array_merge($to$cc);
  172.         $bcc = (array) $message->getBcc();
  173.         $message->setBcc([]);
  174.         try {
  175.             $sent += $this->sendTo($message$reversePath$tos$failedRecipients);
  176.             $sent += $this->sendBcc($message$reversePath$bcc$failedRecipients);
  177.         } finally {
  178.             $message->setBcc($bcc);
  179.         }
  180.         if ($evt) {
  181.             if ($sent == count($to) + count($cc) + count($bcc)) {
  182.                 $evt->setResult(Swift_Events_SendEvent::RESULT_SUCCESS);
  183.             } elseif ($sent 0) {
  184.                 $evt->setResult(Swift_Events_SendEvent::RESULT_TENTATIVE);
  185.             } else {
  186.                 $evt->setResult(Swift_Events_SendEvent::RESULT_FAILED);
  187.             }
  188.             $evt->setFailedRecipients($failedRecipients);
  189.             $this->eventDispatcher->dispatchEvent($evt'sendPerformed');
  190.         }
  191.         $message->generateId(); //Make sure a new Message ID is used
  192.         return $sent;
  193.     }
  194.     /**
  195.      * Stop the SMTP connection.
  196.      */
  197.     public function stop()
  198.     {
  199.         if ($this->started) {
  200.             if ($evt $this->eventDispatcher->createTransportChangeEvent($this)) {
  201.                 $this->eventDispatcher->dispatchEvent($evt'beforeTransportStopped');
  202.                 if ($evt->bubbleCancelled()) {
  203.                     return;
  204.                 }
  205.             }
  206.             try {
  207.                 $this->executeCommand("QUIT\r\n", [221]);
  208.             } catch (Swift_TransportException $e) {
  209.             }
  210.             try {
  211.                 $this->buffer->terminate();
  212.                 if ($evt) {
  213.                     $this->eventDispatcher->dispatchEvent($evt'transportStopped');
  214.                 }
  215.             } catch (Swift_TransportException $e) {
  216.                 $this->throwException($e);
  217.             }
  218.         }
  219.         $this->started false;
  220.     }
  221.     /**
  222.      * {@inheritdoc}
  223.      */
  224.     public function ping()
  225.     {
  226.         try {
  227.             if (!$this->isStarted()) {
  228.                 $this->start();
  229.             }
  230.             $this->executeCommand("NOOP\r\n", [250]);
  231.         } catch (Swift_TransportException $e) {
  232.             try {
  233.                 $this->stop();
  234.             } catch (Swift_TransportException $e) {
  235.             }
  236.             return false;
  237.         }
  238.         return true;
  239.     }
  240.     /**
  241.      * Register a plugin.
  242.      */
  243.     public function registerPlugin(Swift_Events_EventListener $plugin)
  244.     {
  245.         $this->eventDispatcher->bindEventListener($plugin);
  246.     }
  247.     /**
  248.      * Reset the current mail transaction.
  249.      */
  250.     public function reset()
  251.     {
  252.         $this->executeCommand("RSET\r\n", [250], $failurestrue);
  253.     }
  254.     /**
  255.      * Get the IoBuffer where read/writes are occurring.
  256.      *
  257.      * @return Swift_Transport_IoBuffer
  258.      */
  259.     public function getBuffer()
  260.     {
  261.         return $this->buffer;
  262.     }
  263.     /**
  264.      * Run a command against the buffer, expecting the given response codes.
  265.      *
  266.      * If no response codes are given, the response will not be validated.
  267.      * If codes are given, an exception will be thrown on an invalid response.
  268.      * If the command is RCPT TO, and the pipeline is non-empty, no exception
  269.      * will be thrown; instead the failing address is added to $failures.
  270.      *
  271.      * @param string   $command
  272.      * @param int[]    $codes
  273.      * @param string[] $failures An array of failures by-reference
  274.      * @param bool     $pipeline Do not wait for response
  275.      * @param string   $address  The address, if command is RCPT TO.
  276.      *
  277.      * @return string|null The server response, or null if pipelining is enabled
  278.      */
  279.     public function executeCommand($command$codes = [], &$failures null$pipeline false$address null)
  280.     {
  281.         $failures = (array) $failures;
  282.         $seq $this->buffer->write($command);
  283.         if ($evt $this->eventDispatcher->createCommandEvent($this$command$codes)) {
  284.             $this->eventDispatcher->dispatchEvent($evt'commandSent');
  285.         }
  286.         $this->pipeline[] = [$command$seq$codes$address];
  287.         if ($pipeline && $this->pipelining) {
  288.             $response null;
  289.         } else {
  290.             while ($this->pipeline) {
  291.                 list($command$seq$codes$address) = array_shift($this->pipeline);
  292.                 $response $this->getFullResponse($seq);
  293.                 try {
  294.                     $this->assertResponseCode($response$codes);
  295.                 } catch (Swift_TransportException $e) {
  296.                     if ($this->pipeline && $address) {
  297.                         $failures[] = $address;
  298.                     } else {
  299.                         $this->throwException($e);
  300.                     }
  301.                 }
  302.             }
  303.         }
  304.         return $response;
  305.     }
  306.     /** Read the opening SMTP greeting */
  307.     protected function readGreeting()
  308.     {
  309.         $this->assertResponseCode($this->getFullResponse(0), [220]);
  310.     }
  311.     /** Send the HELO welcome */
  312.     protected function doHeloCommand()
  313.     {
  314.         $this->executeCommand(
  315.             sprintf("HELO %s\r\n"$this->domain), [250]
  316.             );
  317.     }
  318.     /** Send the MAIL FROM command */
  319.     protected function doMailFromCommand($address)
  320.     {
  321.         $address $this->addressEncoder->encodeString($address);
  322.         $this->executeCommand(
  323.             sprintf("MAIL FROM:<%s>\r\n"$address), [250], $failurestrue
  324.             );
  325.     }
  326.     /** Send the RCPT TO command */
  327.     protected function doRcptToCommand($address)
  328.     {
  329.         $address $this->addressEncoder->encodeString($address);
  330.         $this->executeCommand(
  331.             sprintf("RCPT TO:<%s>\r\n"$address), [250251252], $failurestrue$address
  332.             );
  333.     }
  334.     /** Send the DATA command */
  335.     protected function doDataCommand(&$failedRecipients)
  336.     {
  337.         $this->executeCommand("DATA\r\n", [354], $failedRecipients);
  338.     }
  339.     /** Stream the contents of the message over the buffer */
  340.     protected function streamMessage(Swift_Mime_SimpleMessage $message)
  341.     {
  342.         $this->buffer->setWriteTranslations(["\r\n." => "\r\n.."]);
  343.         try {
  344.             $message->toByteStream($this->buffer);
  345.             $this->buffer->flushBuffers();
  346.         } catch (Swift_TransportException $e) {
  347.             $this->throwException($e);
  348.         }
  349.         $this->buffer->setWriteTranslations([]);
  350.         $this->executeCommand("\r\n.\r\n", [250]);
  351.     }
  352.     /** Determine the best-use reverse path for this message */
  353.     protected function getReversePath(Swift_Mime_SimpleMessage $message)
  354.     {
  355.         $return $message->getReturnPath();
  356.         $sender $message->getSender();
  357.         $from $message->getFrom();
  358.         $path null;
  359.         if (!empty($return)) {
  360.             $path $return;
  361.         } elseif (!empty($sender)) {
  362.             // Don't use array_keys
  363.             reset($sender); // Reset Pointer to first pos
  364.             $path key($sender); // Get key
  365.         } elseif (!empty($from)) {
  366.             reset($from); // Reset Pointer to first pos
  367.             $path key($from); // Get key
  368.         }
  369.         return $path;
  370.     }
  371.     /** Throw a TransportException, first sending it to any listeners */
  372.     protected function throwException(Swift_TransportException $e)
  373.     {
  374.         if ($evt $this->eventDispatcher->createTransportExceptionEvent($this$e)) {
  375.             $this->eventDispatcher->dispatchEvent($evt'exceptionThrown');
  376.             if (!$evt->bubbleCancelled()) {
  377.                 throw $e;
  378.             }
  379.         } else {
  380.             throw $e;
  381.         }
  382.     }
  383.     /** Throws an Exception if a response code is incorrect */
  384.     protected function assertResponseCode($response$wanted)
  385.     {
  386.         if (!$response) {
  387.             $this->throwException(new Swift_TransportException('Expected response code '.implode('/'$wanted).' but got an empty response'));
  388.         }
  389.         list($code) = sscanf($response'%3d');
  390.         $valid = (empty($wanted) || in_array($code$wanted));
  391.         if ($evt $this->eventDispatcher->createResponseEvent($this$response,
  392.             $valid)) {
  393.             $this->eventDispatcher->dispatchEvent($evt'responseReceived');
  394.         }
  395.         if (!$valid) {
  396.             $this->throwException(new Swift_TransportException('Expected response code '.implode('/'$wanted).' but got code "'.$code.'", with message "'.$response.'"'$code));
  397.         }
  398.     }
  399.     /** Get an entire multi-line response using its sequence number */
  400.     protected function getFullResponse($seq)
  401.     {
  402.         $response '';
  403.         try {
  404.             do {
  405.                 $line $this->buffer->readLine($seq);
  406.                 $response .= $line;
  407.             } while (null !== $line && false !== $line && ' ' != $line[3]);
  408.         } catch (Swift_TransportException $e) {
  409.             $this->throwException($e);
  410.         } catch (Swift_IoException $e) {
  411.             $this->throwException(new Swift_TransportException($e->getMessage(), 0$e));
  412.         }
  413.         return $response;
  414.     }
  415.     /** Send an email to the given recipients from the given reverse path */
  416.     private function doMailTransaction($message$reversePath, array $recipients, array &$failedRecipients)
  417.     {
  418.         $sent 0;
  419.         $this->doMailFromCommand($reversePath);
  420.         foreach ($recipients as $forwardPath) {
  421.             try {
  422.                 $this->doRcptToCommand($forwardPath);
  423.                 ++$sent;
  424.             } catch (Swift_TransportException $e) {
  425.                 $failedRecipients[] = $forwardPath;
  426.             } catch (Swift_AddressEncoderException $e) {
  427.                 $failedRecipients[] = $forwardPath;
  428.             }
  429.         }
  430.         if (!= $sent) {
  431.             $sent += count($failedRecipients);
  432.             $this->doDataCommand($failedRecipients);
  433.             $sent -= count($failedRecipients);
  434.             $this->streamMessage($message);
  435.         } else {
  436.             $this->reset();
  437.         }
  438.         return $sent;
  439.     }
  440.     /** Send a message to the given To: recipients */
  441.     private function sendTo(Swift_Mime_SimpleMessage $message$reversePath, array $to, array &$failedRecipients)
  442.     {
  443.         if (empty($to)) {
  444.             return 0;
  445.         }
  446.         return $this->doMailTransaction($message$reversePatharray_keys($to),
  447.             $failedRecipients);
  448.     }
  449.     /** Send a message to all Bcc: recipients */
  450.     private function sendBcc(Swift_Mime_SimpleMessage $message$reversePath, array $bcc, array &$failedRecipients)
  451.     {
  452.         $sent 0;
  453.         foreach ($bcc as $forwardPath => $name) {
  454.             $message->setBcc([$forwardPath => $name]);
  455.             $sent += $this->doMailTransaction(
  456.                 $message$reversePath, [$forwardPath], $failedRecipients
  457.                 );
  458.         }
  459.         return $sent;
  460.     }
  461.     /**
  462.      * Destructor.
  463.      */
  464.     public function __destruct()
  465.     {
  466.         try {
  467.             $this->stop();
  468.         } catch (Exception $e) {
  469.         }
  470.     }
  471. }