AbstractSmtpTransport.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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 $buf, Swift_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($domain, 0, 1)) {
  62. if (filter_var($domain, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
  63. $domain = '['.$domain.']';
  64. } elseif (filter_var($domain, FILTER_VALIDATE_IP, FILTER_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. $bcc = (array) $message->getBcc();
  172. $tos = array_merge($to, $cc, $bcc);
  173. $message->setBcc([]);
  174. try {
  175. $sent += $this->sendTo($message, $reversePath, $tos, $failedRecipients);
  176. } finally {
  177. $message->setBcc($bcc);
  178. }
  179. if ($evt) {
  180. if ($sent == \count($to) + \count($cc) + \count($bcc)) {
  181. $evt->setResult(Swift_Events_SendEvent::RESULT_SUCCESS);
  182. } elseif ($sent > 0) {
  183. $evt->setResult(Swift_Events_SendEvent::RESULT_TENTATIVE);
  184. } else {
  185. $evt->setResult(Swift_Events_SendEvent::RESULT_FAILED);
  186. }
  187. $evt->setFailedRecipients($failedRecipients);
  188. $this->eventDispatcher->dispatchEvent($evt, 'sendPerformed');
  189. }
  190. $message->generateId(); //Make sure a new Message ID is used
  191. return $sent;
  192. }
  193. /**
  194. * Stop the SMTP connection.
  195. */
  196. public function stop()
  197. {
  198. if ($this->started) {
  199. if ($evt = $this->eventDispatcher->createTransportChangeEvent($this)) {
  200. $this->eventDispatcher->dispatchEvent($evt, 'beforeTransportStopped');
  201. if ($evt->bubbleCancelled()) {
  202. return;
  203. }
  204. }
  205. try {
  206. $this->executeCommand("QUIT\r\n", [221]);
  207. } catch (Swift_TransportException $e) {
  208. }
  209. try {
  210. $this->buffer->terminate();
  211. if ($evt) {
  212. $this->eventDispatcher->dispatchEvent($evt, 'transportStopped');
  213. }
  214. } catch (Swift_TransportException $e) {
  215. $this->throwException($e);
  216. }
  217. }
  218. $this->started = false;
  219. }
  220. /**
  221. * {@inheritdoc}
  222. */
  223. public function ping()
  224. {
  225. try {
  226. if (!$this->isStarted()) {
  227. $this->start();
  228. }
  229. $this->executeCommand("NOOP\r\n", [250]);
  230. } catch (Swift_TransportException $e) {
  231. try {
  232. $this->stop();
  233. } catch (Swift_TransportException $e) {
  234. }
  235. return false;
  236. }
  237. return true;
  238. }
  239. /**
  240. * Register a plugin.
  241. */
  242. public function registerPlugin(Swift_Events_EventListener $plugin)
  243. {
  244. $this->eventDispatcher->bindEventListener($plugin);
  245. }
  246. /**
  247. * Reset the current mail transaction.
  248. */
  249. public function reset()
  250. {
  251. $this->executeCommand("RSET\r\n", [250], $failures, true);
  252. }
  253. /**
  254. * Get the IoBuffer where read/writes are occurring.
  255. *
  256. * @return Swift_Transport_IoBuffer
  257. */
  258. public function getBuffer()
  259. {
  260. return $this->buffer;
  261. }
  262. /**
  263. * Run a command against the buffer, expecting the given response codes.
  264. *
  265. * If no response codes are given, the response will not be validated.
  266. * If codes are given, an exception will be thrown on an invalid response.
  267. * If the command is RCPT TO, and the pipeline is non-empty, no exception
  268. * will be thrown; instead the failing address is added to $failures.
  269. *
  270. * @param string $command
  271. * @param int[] $codes
  272. * @param string[] $failures An array of failures by-reference
  273. * @param bool $pipeline Do not wait for response
  274. * @param string $address the address, if command is RCPT TO
  275. *
  276. * @return string|null The server response, or null if pipelining is enabled
  277. */
  278. public function executeCommand($command, $codes = [], &$failures = null, $pipeline = false, $address = null)
  279. {
  280. $failures = (array) $failures;
  281. $seq = $this->buffer->write($command);
  282. if ($evt = $this->eventDispatcher->createCommandEvent($this, $command, $codes)) {
  283. $this->eventDispatcher->dispatchEvent($evt, 'commandSent');
  284. }
  285. $this->pipeline[] = [$command, $seq, $codes, $address];
  286. if ($pipeline && $this->pipelining) {
  287. return null;
  288. }
  289. $response = null;
  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. return $response;
  304. }
  305. /** Read the opening SMTP greeting */
  306. protected function readGreeting()
  307. {
  308. $this->assertResponseCode($this->getFullResponse(0), [220]);
  309. }
  310. /** Send the HELO welcome */
  311. protected function doHeloCommand()
  312. {
  313. $this->executeCommand(
  314. sprintf("HELO %s\r\n", $this->domain), [250]
  315. );
  316. }
  317. /** Send the MAIL FROM command */
  318. protected function doMailFromCommand($address)
  319. {
  320. $address = $this->addressEncoder->encodeString($address);
  321. $this->executeCommand(
  322. sprintf("MAIL FROM:<%s>\r\n", $address), [250], $failures, true
  323. );
  324. }
  325. /** Send the RCPT TO command */
  326. protected function doRcptToCommand($address)
  327. {
  328. $address = $this->addressEncoder->encodeString($address);
  329. $this->executeCommand(
  330. sprintf("RCPT TO:<%s>\r\n", $address), [250, 251, 252], $failures, true, $address
  331. );
  332. }
  333. /** Send the DATA command */
  334. protected function doDataCommand(&$failedRecipients)
  335. {
  336. $this->executeCommand("DATA\r\n", [354], $failedRecipients);
  337. }
  338. /** Stream the contents of the message over the buffer */
  339. protected function streamMessage(Swift_Mime_SimpleMessage $message)
  340. {
  341. $this->buffer->setWriteTranslations(["\r\n." => "\r\n.."]);
  342. try {
  343. $message->toByteStream($this->buffer);
  344. $this->buffer->flushBuffers();
  345. } catch (Swift_TransportException $e) {
  346. $this->throwException($e);
  347. }
  348. $this->buffer->setWriteTranslations([]);
  349. $this->executeCommand("\r\n.\r\n", [250]);
  350. }
  351. /** Determine the best-use reverse path for this message */
  352. protected function getReversePath(Swift_Mime_SimpleMessage $message)
  353. {
  354. $return = $message->getReturnPath();
  355. $sender = $message->getSender();
  356. $from = $message->getFrom();
  357. $path = null;
  358. if (!empty($return)) {
  359. $path = $return;
  360. } elseif (!empty($sender)) {
  361. // Don't use array_keys
  362. reset($sender); // Reset Pointer to first pos
  363. $path = key($sender); // Get key
  364. } elseif (!empty($from)) {
  365. reset($from); // Reset Pointer to first pos
  366. $path = key($from); // Get key
  367. }
  368. return $path;
  369. }
  370. /** Throw a TransportException, first sending it to any listeners */
  371. protected function throwException(Swift_TransportException $e)
  372. {
  373. if ($evt = $this->eventDispatcher->createTransportExceptionEvent($this, $e)) {
  374. $this->eventDispatcher->dispatchEvent($evt, 'exceptionThrown');
  375. if (!$evt->bubbleCancelled()) {
  376. throw $e;
  377. }
  378. } else {
  379. throw $e;
  380. }
  381. }
  382. /** Throws an Exception if a response code is incorrect */
  383. protected function assertResponseCode($response, $wanted)
  384. {
  385. if (!$response) {
  386. $this->throwException(new Swift_TransportException('Expected response code '.implode('/', $wanted).' but got an empty response'));
  387. }
  388. list($code) = sscanf($response, '%3d');
  389. $valid = (empty($wanted) || \in_array($code, $wanted));
  390. if ($evt = $this->eventDispatcher->createResponseEvent($this, $response,
  391. $valid)) {
  392. $this->eventDispatcher->dispatchEvent($evt, 'responseReceived');
  393. }
  394. if (!$valid) {
  395. $this->throwException(new Swift_TransportException('Expected response code '.implode('/', $wanted).' but got code "'.$code.'", with message "'.$response.'"', $code));
  396. }
  397. }
  398. /** Get an entire multi-line response using its sequence number */
  399. protected function getFullResponse($seq)
  400. {
  401. $response = '';
  402. try {
  403. do {
  404. $line = $this->buffer->readLine($seq);
  405. $response .= $line;
  406. } while (null !== $line && false !== $line && ' ' != $line[3]);
  407. } catch (Swift_TransportException $e) {
  408. $this->throwException($e);
  409. } catch (Swift_IoException $e) {
  410. $this->throwException(new Swift_TransportException($e->getMessage(), 0, $e));
  411. }
  412. return $response;
  413. }
  414. /** Send an email to the given recipients from the given reverse path */
  415. private function doMailTransaction($message, $reversePath, array $recipients, array &$failedRecipients)
  416. {
  417. $sent = 0;
  418. $this->doMailFromCommand($reversePath);
  419. foreach ($recipients as $forwardPath) {
  420. try {
  421. $this->doRcptToCommand($forwardPath);
  422. ++$sent;
  423. } catch (Swift_TransportException $e) {
  424. $failedRecipients[] = $forwardPath;
  425. } catch (Swift_AddressEncoderException $e) {
  426. $failedRecipients[] = $forwardPath;
  427. }
  428. }
  429. if (0 != $sent) {
  430. $sent += \count($failedRecipients);
  431. $this->doDataCommand($failedRecipients);
  432. $sent -= \count($failedRecipients);
  433. $this->streamMessage($message);
  434. } else {
  435. $this->reset();
  436. }
  437. return $sent;
  438. }
  439. /** Send a message to the given To: recipients */
  440. private function sendTo(Swift_Mime_SimpleMessage $message, $reversePath, array $to, array &$failedRecipients)
  441. {
  442. if (empty($to)) {
  443. return 0;
  444. }
  445. return $this->doMailTransaction($message, $reversePath, array_keys($to),
  446. $failedRecipients);
  447. }
  448. /**
  449. * Destructor.
  450. */
  451. public function __destruct()
  452. {
  453. try {
  454. $this->stop();
  455. } catch (Exception $e) {
  456. }
  457. }
  458. public function __sleep()
  459. {
  460. throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
  461. }
  462. public function __wakeup()
  463. {
  464. throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
  465. }
  466. }