AbstractSmtpTransport.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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. /** Source Ip */
  25. protected $_sourceIp;
  26. /** Return an array of params for the Buffer */
  27. abstract protected function _getBufferParams();
  28. /**
  29. * Creates a new EsmtpTransport using the given I/O buffer.
  30. *
  31. * @param Swift_Transport_IoBuffer $buf
  32. * @param Swift_Events_EventDispatcher $dispatcher
  33. */
  34. public function __construct(Swift_Transport_IoBuffer $buf, Swift_Events_EventDispatcher $dispatcher)
  35. {
  36. $this->_eventDispatcher = $dispatcher;
  37. $this->_buffer = $buf;
  38. $this->_lookupHostname();
  39. }
  40. /**
  41. * Set the name of the local domain which Swift will identify itself as.
  42. *
  43. * This should be a fully-qualified domain name and should be truly the domain
  44. * you're using.
  45. *
  46. * If your server doesn't have a domain name, use the IP in square
  47. * brackets (i.e. [127.0.0.1]).
  48. *
  49. * @param string $domain
  50. *
  51. * @return Swift_Transport_AbstractSmtpTransport
  52. */
  53. public function setLocalDomain($domain)
  54. {
  55. $this->_domain = $domain;
  56. return $this;
  57. }
  58. /**
  59. * Get the name of the domain Swift will identify as.
  60. *
  61. * @return string
  62. */
  63. public function getLocalDomain()
  64. {
  65. return $this->_domain;
  66. }
  67. /**
  68. * Sets the source IP.
  69. *
  70. * @param string $source
  71. */
  72. public function setSourceIp($source)
  73. {
  74. $this->_sourceIp=$source;
  75. }
  76. /**
  77. * Returns the IP used to connect to the destination
  78. *
  79. * @return string
  80. */
  81. public function getSourceIp()
  82. {
  83. return $this->_sourceIp;
  84. }
  85. /**
  86. * Start the SMTP connection.
  87. */
  88. public function start()
  89. {
  90. if (!$this->_started) {
  91. if ($evt = $this->_eventDispatcher->createTransportChangeEvent($this)) {
  92. $this->_eventDispatcher->dispatchEvent($evt, 'beforeTransportStarted');
  93. if ($evt->bubbleCancelled()) {
  94. return;
  95. }
  96. }
  97. try {
  98. $this->_buffer->initialize($this->_getBufferParams());
  99. } catch (Swift_TransportException $e) {
  100. $this->_throwException($e);
  101. }
  102. $this->_readGreeting();
  103. $this->_doHeloCommand();
  104. if ($evt) {
  105. $this->_eventDispatcher->dispatchEvent($evt, 'transportStarted');
  106. }
  107. $this->_started = true;
  108. }
  109. }
  110. /**
  111. * Test if an SMTP connection has been established.
  112. *
  113. * @return bool
  114. */
  115. public function isStarted()
  116. {
  117. return $this->_started;
  118. }
  119. /**
  120. * Send the given Message.
  121. *
  122. * Recipient/sender data will be retrieved from the Message API.
  123. * The return value is the number of recipients who were accepted for delivery.
  124. *
  125. * @param Swift_Mime_Message $message
  126. * @param string[] $failedRecipients An array of failures by-reference
  127. *
  128. * @return int
  129. */
  130. public function send(Swift_Mime_Message $message, &$failedRecipients = null)
  131. {
  132. $sent = 0;
  133. $failedRecipients = (array) $failedRecipients;
  134. if ($evt = $this->_eventDispatcher->createSendEvent($this, $message)) {
  135. $this->_eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed');
  136. if ($evt->bubbleCancelled()) {
  137. return 0;
  138. }
  139. }
  140. if (!$reversePath = $this->_getReversePath($message)) {
  141. throw new Swift_TransportException(
  142. 'Cannot send message without a sender address'
  143. );
  144. }
  145. $to = (array) $message->getTo();
  146. $cc = (array) $message->getCc();
  147. $bcc = (array) $message->getBcc();
  148. $message->setBcc(array());
  149. try {
  150. $sent += $this->_sendTo($message, $reversePath, $to, $failedRecipients);
  151. $sent += $this->_sendCc($message, $reversePath, $cc, $failedRecipients);
  152. $sent += $this->_sendBcc($message, $reversePath, $bcc, $failedRecipients);
  153. } catch (Exception $e) {
  154. $message->setBcc($bcc);
  155. throw $e;
  156. }
  157. $message->setBcc($bcc);
  158. if ($evt) {
  159. if ($sent == count($to) + count($cc) + count($bcc)) {
  160. $evt->setResult(Swift_Events_SendEvent::RESULT_SUCCESS);
  161. } elseif ($sent > 0) {
  162. $evt->setResult(Swift_Events_SendEvent::RESULT_TENTATIVE);
  163. } else {
  164. $evt->setResult(Swift_Events_SendEvent::RESULT_FAILED);
  165. }
  166. $evt->setFailedRecipients($failedRecipients);
  167. $this->_eventDispatcher->dispatchEvent($evt, 'sendPerformed');
  168. }
  169. $message->generateId(); //Make sure a new Message ID is used
  170. return $sent;
  171. }
  172. /**
  173. * Stop the SMTP connection.
  174. */
  175. public function stop()
  176. {
  177. if ($this->_started) {
  178. if ($evt = $this->_eventDispatcher->createTransportChangeEvent($this)) {
  179. $this->_eventDispatcher->dispatchEvent($evt, 'beforeTransportStopped');
  180. if ($evt->bubbleCancelled()) {
  181. return;
  182. }
  183. }
  184. try {
  185. $this->executeCommand("QUIT\r\n", array(221));
  186. } catch (Swift_TransportException $e) {}
  187. try {
  188. $this->_buffer->terminate();
  189. if ($evt) {
  190. $this->_eventDispatcher->dispatchEvent($evt, 'transportStopped');
  191. }
  192. } catch (Swift_TransportException $e) {
  193. $this->_throwException($e);
  194. }
  195. }
  196. $this->_started = false;
  197. }
  198. /**
  199. * Register a plugin.
  200. *
  201. * @param Swift_Events_EventListener $plugin
  202. */
  203. public function registerPlugin(Swift_Events_EventListener $plugin)
  204. {
  205. $this->_eventDispatcher->bindEventListener($plugin);
  206. }
  207. /**
  208. * Reset the current mail transaction.
  209. */
  210. public function reset()
  211. {
  212. $this->executeCommand("RSET\r\n", array(250));
  213. }
  214. /**
  215. * Get the IoBuffer where read/writes are occurring.
  216. *
  217. * @return Swift_Transport_IoBuffer
  218. */
  219. public function getBuffer()
  220. {
  221. return $this->_buffer;
  222. }
  223. /**
  224. * Run a command against the buffer, expecting the given response codes.
  225. *
  226. * If no response codes are given, the response will not be validated.
  227. * If codes are given, an exception will be thrown on an invalid response.
  228. *
  229. * @param string $command
  230. * @param int[] $codes
  231. * @param string[] $failures An array of failures by-reference
  232. *
  233. * @return string
  234. */
  235. public function executeCommand($command, $codes = array(), &$failures = null)
  236. {
  237. $failures = (array) $failures;
  238. $seq = $this->_buffer->write($command);
  239. $response = $this->_getFullResponse($seq);
  240. if ($evt = $this->_eventDispatcher->createCommandEvent($this, $command, $codes)) {
  241. $this->_eventDispatcher->dispatchEvent($evt, 'commandSent');
  242. }
  243. $this->_assertResponseCode($response, $codes);
  244. return $response;
  245. }
  246. /** Read the opening SMTP greeting */
  247. protected function _readGreeting()
  248. {
  249. $this->_assertResponseCode($this->_getFullResponse(0), array(220));
  250. }
  251. /** Send the HELO welcome */
  252. protected function _doHeloCommand()
  253. {
  254. $this->executeCommand(
  255. sprintf("HELO %s\r\n", $this->_domain), array(250)
  256. );
  257. }
  258. /** Send the MAIL FROM command */
  259. protected function _doMailFromCommand($address)
  260. {
  261. $this->executeCommand(
  262. sprintf("MAIL FROM: <%s>\r\n", $address), array(250)
  263. );
  264. }
  265. /** Send the RCPT TO command */
  266. protected function _doRcptToCommand($address)
  267. {
  268. $this->executeCommand(
  269. sprintf("RCPT TO: <%s>\r\n", $address), array(250, 251, 252)
  270. );
  271. }
  272. /** Send the DATA command */
  273. protected function _doDataCommand()
  274. {
  275. $this->executeCommand("DATA\r\n", array(354));
  276. }
  277. /** Stream the contents of the message over the buffer */
  278. protected function _streamMessage(Swift_Mime_Message $message)
  279. {
  280. $this->_buffer->setWriteTranslations(array("\r\n." => "\r\n.."));
  281. try {
  282. $message->toByteStream($this->_buffer);
  283. $this->_buffer->flushBuffers();
  284. } catch (Swift_TransportException $e) {
  285. $this->_throwException($e);
  286. }
  287. $this->_buffer->setWriteTranslations(array());
  288. $this->executeCommand("\r\n.\r\n", array(250));
  289. }
  290. /** Determine the best-use reverse path for this message */
  291. protected function _getReversePath(Swift_Mime_Message $message)
  292. {
  293. $return = $message->getReturnPath();
  294. $sender = $message->getSender();
  295. $from = $message->getFrom();
  296. $path = null;
  297. if (!empty($return)) {
  298. $path = $return;
  299. } elseif (!empty($sender)) {
  300. // Don't use array_keys
  301. reset($sender); // Reset Pointer to first pos
  302. $path = key($sender); // Get key
  303. } elseif (!empty($from)) {
  304. reset($from); // Reset Pointer to first pos
  305. $path = key($from); // Get key
  306. }
  307. return $path;
  308. }
  309. /** Throw a TransportException, first sending it to any listeners */
  310. protected function _throwException(Swift_TransportException $e)
  311. {
  312. if ($evt = $this->_eventDispatcher->createTransportExceptionEvent($this, $e)) {
  313. $this->_eventDispatcher->dispatchEvent($evt, 'exceptionThrown');
  314. if (!$evt->bubbleCancelled()) {
  315. throw $e;
  316. }
  317. } else {
  318. throw $e;
  319. }
  320. }
  321. /** Throws an Exception if a response code is incorrect */
  322. protected function _assertResponseCode($response, $wanted)
  323. {
  324. list($code) = sscanf($response, '%3d');
  325. $valid = (empty($wanted) || in_array($code, $wanted));
  326. if ($evt = $this->_eventDispatcher->createResponseEvent($this, $response,
  327. $valid))
  328. {
  329. $this->_eventDispatcher->dispatchEvent($evt, 'responseReceived');
  330. }
  331. if (!$valid) {
  332. $this->_throwException(
  333. new Swift_TransportException(
  334. 'Expected response code ' . implode('/', $wanted) . ' but got code ' .
  335. '"' . $code . '", with message "' . $response . '"',
  336. $code)
  337. );
  338. }
  339. }
  340. /** Get an entire multi-line response using its sequence number */
  341. protected function _getFullResponse($seq)
  342. {
  343. $response = '';
  344. try {
  345. do {
  346. $line = $this->_buffer->readLine($seq);
  347. $response .= $line;
  348. } while (null !== $line && false !== $line && ' ' != $line{3});
  349. } catch (Swift_TransportException $e) {
  350. $this->_throwException($e);
  351. } catch (Swift_IoException $e) {
  352. $this->_throwException(
  353. new Swift_TransportException(
  354. $e->getMessage())
  355. );
  356. }
  357. return $response;
  358. }
  359. /** Send an email to the given recipients from the given reverse path */
  360. private function _doMailTransaction($message, $reversePath, array $recipients, array &$failedRecipients)
  361. {
  362. $sent = 0;
  363. $this->_doMailFromCommand($reversePath);
  364. foreach ($recipients as $forwardPath) {
  365. try {
  366. $this->_doRcptToCommand($forwardPath);
  367. $sent++;
  368. } catch (Swift_TransportException $e) {
  369. $failedRecipients[] = $forwardPath;
  370. }
  371. }
  372. if ($sent != 0) {
  373. $this->_doDataCommand();
  374. $this->_streamMessage($message);
  375. } else {
  376. $this->reset();
  377. }
  378. return $sent;
  379. }
  380. /** Send a message to the given To: recipients */
  381. private function _sendTo(Swift_Mime_Message $message, $reversePath, array $to, array &$failedRecipients)
  382. {
  383. if (empty($to)) {
  384. return 0;
  385. }
  386. return $this->_doMailTransaction($message, $reversePath, array_keys($to),
  387. $failedRecipients);
  388. }
  389. /** Send a message to the given Cc: recipients */
  390. private function _sendCc(Swift_Mime_Message $message, $reversePath, array $cc, array &$failedRecipients)
  391. {
  392. if (empty($cc)) {
  393. return 0;
  394. }
  395. return $this->_doMailTransaction($message, $reversePath, array_keys($cc),
  396. $failedRecipients);
  397. }
  398. /** Send a message to all Bcc: recipients */
  399. private function _sendBcc(Swift_Mime_Message $message, $reversePath, array $bcc, array &$failedRecipients)
  400. {
  401. $sent = 0;
  402. foreach ($bcc as $forwardPath => $name) {
  403. $message->setBcc(array($forwardPath => $name));
  404. $sent += $this->_doMailTransaction(
  405. $message, $reversePath, array($forwardPath), $failedRecipients
  406. );
  407. }
  408. return $sent;
  409. }
  410. /** Try to determine the hostname of the server this is run on */
  411. private function _lookupHostname()
  412. {
  413. if (!empty($_SERVER['SERVER_NAME'])
  414. && $this->_isFqdn($_SERVER['SERVER_NAME']))
  415. {
  416. $this->_domain = $_SERVER['SERVER_NAME'];
  417. } elseif (!empty($_SERVER['SERVER_ADDR'])) {
  418. $this->_domain = sprintf('[%s]', $_SERVER['SERVER_ADDR']);
  419. }
  420. }
  421. /** Determine is the $hostname is a fully-qualified name */
  422. private function _isFqdn($hostname)
  423. {
  424. // We could do a really thorough check, but there's really no point
  425. if (false !== $dotPos = strpos($hostname, '.')) {
  426. return ($dotPos > 0) && ($dotPos != strlen($hostname) - 1);
  427. } else {
  428. return false;
  429. }
  430. }
  431. /**
  432. * Destructor.
  433. */
  434. public function __destruct()
  435. {
  436. $this->stop();
  437. }
  438. }