smtpmx.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  3. /**
  4. * SMTP MX
  5. *
  6. * SMTP MX implementation of the PEAR Mail interface. Requires the Net_SMTP class.
  7. *
  8. * PHP version 5
  9. *
  10. * LICENSE:
  11. *
  12. * Copyright (c) 2010, gERD Schaufelberger
  13. * All rights reserved.
  14. *
  15. * Redistribution and use in source and binary forms, with or without
  16. * modification, are permitted provided that the following conditions
  17. * are met:
  18. *
  19. * o Redistributions of source code must retain the above copyright
  20. * notice, this list of conditions and the following disclaimer.
  21. * o Redistributions in binary form must reproduce the above copyright
  22. * notice, this list of conditions and the following disclaimer in the
  23. * documentation and/or other materials provided with the distribution.
  24. * o The names of the authors may not be used to endorse or promote
  25. * products derived from this software without specific prior written
  26. * permission.
  27. *
  28. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  29. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  30. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  31. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  32. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  33. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  34. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  35. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  36. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  37. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  38. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  39. *
  40. * @category Mail
  41. * @package Mail_smtpmx
  42. * @author gERD Schaufelberger <gerd@php-tools.net>
  43. * @copyright 2010 gERD Schaufelberger
  44. * @license http://opensource.org/licenses/bsd-license.php New BSD License
  45. * @version CVS: $Id$
  46. * @link http://pear.php.net/package/Mail/
  47. */
  48. require_once 'Net/SMTP.php';
  49. /**
  50. * SMTP MX implementation of the PEAR Mail interface. Requires the Net_SMTP class.
  51. *
  52. *
  53. * @access public
  54. * @author gERD Schaufelberger <gerd@php-tools.net>
  55. * @package Mail
  56. * @version $Revision$
  57. */
  58. class Mail_smtpmx extends Mail {
  59. /**
  60. * SMTP connection object.
  61. *
  62. * @var object
  63. * @access private
  64. */
  65. var $_smtp = null;
  66. /**
  67. * The port the SMTP server is on.
  68. * @var integer
  69. * @see getservicebyname()
  70. */
  71. var $port = 25;
  72. /**
  73. * Hostname or domain that will be sent to the remote SMTP server in the
  74. * HELO / EHLO message.
  75. *
  76. * @var string
  77. * @see posix_uname()
  78. */
  79. var $mailname = 'localhost';
  80. /**
  81. * SMTP connection timeout value. NULL indicates no timeout.
  82. *
  83. * @var integer
  84. */
  85. var $timeout = 10;
  86. /**
  87. * use either PEAR:Net_DNS or getmxrr
  88. *
  89. * @var boolean
  90. */
  91. var $withNetDns = true;
  92. /**
  93. * PEAR:Net_DNS_Resolver
  94. *
  95. * @var object
  96. */
  97. var $resolver;
  98. /**
  99. * Whether to use VERP or not. If not a boolean, the string value
  100. * will be used as the VERP separators.
  101. *
  102. * @var mixed boolean or string
  103. */
  104. var $verp = false;
  105. /**
  106. * Whether to use VRFY or not.
  107. *
  108. * @var boolean $vrfy
  109. */
  110. var $vrfy = false;
  111. /**
  112. * Switch to test mode - don't send emails for real
  113. *
  114. * @var boolean $debug
  115. */
  116. var $test = false;
  117. /**
  118. * Turn on Net_SMTP debugging?
  119. *
  120. * @var boolean $peardebug
  121. */
  122. var $debug = false;
  123. /**
  124. * internal error codes
  125. *
  126. * translate internal error identifier to PEAR-Error codes and human
  127. * readable messages.
  128. *
  129. * @var boolean $debug
  130. * @todo as I need unique error-codes to identify what exactly went wrond
  131. * I did not use intergers as it should be. Instead I added a "namespace"
  132. * for each code. This avoids conflicts with error codes from different
  133. * classes. How can I use unique error codes and stay conform with PEAR?
  134. */
  135. var $errorCode = array(
  136. 'not_connected' => array(
  137. 'code' => 1,
  138. 'msg' => 'Could not connect to any mail server ({HOST}) at port {PORT} to send mail to {RCPT}.'
  139. ),
  140. 'failed_vrfy_rcpt' => array(
  141. 'code' => 2,
  142. 'msg' => 'Recipient "{RCPT}" could not be veryfied.'
  143. ),
  144. 'failed_set_from' => array(
  145. 'code' => 3,
  146. 'msg' => 'Failed to set sender: {FROM}.'
  147. ),
  148. 'failed_set_rcpt' => array(
  149. 'code' => 4,
  150. 'msg' => 'Failed to set recipient: {RCPT}.'
  151. ),
  152. 'failed_send_data' => array(
  153. 'code' => 5,
  154. 'msg' => 'Failed to send mail to: {RCPT}.'
  155. ),
  156. 'no_from' => array(
  157. 'code' => 5,
  158. 'msg' => 'No from address has be provided.'
  159. ),
  160. 'send_data' => array(
  161. 'code' => 7,
  162. 'msg' => 'Failed to create Net_SMTP object.'
  163. ),
  164. 'no_mx' => array(
  165. 'code' => 8,
  166. 'msg' => 'No MX-record for {RCPT} found.'
  167. ),
  168. 'no_resolver' => array(
  169. 'code' => 9,
  170. 'msg' => 'Could not start resolver! Install PEAR:Net_DNS or switch off "netdns"'
  171. ),
  172. 'failed_rset' => array(
  173. 'code' => 10,
  174. 'msg' => 'RSET command failed, SMTP-connection corrupt.'
  175. ),
  176. );
  177. /**
  178. * Constructor.
  179. *
  180. * Instantiates a new Mail_smtp:: object based on the parameters
  181. * passed in. It looks for the following parameters:
  182. * mailname The name of the local mail system (a valid hostname which matches the reverse lookup)
  183. * port smtp-port - the default comes from getservicebyname() and should work fine
  184. * timeout The SMTP connection timeout. Defaults to 30 seconds.
  185. * vrfy Whether to use VRFY or not. Defaults to false.
  186. * verp Whether to use VERP or not. Defaults to false.
  187. * test Activate test mode? Defaults to false.
  188. * debug Activate SMTP and Net_DNS debug mode? Defaults to false.
  189. * netdns whether to use PEAR:Net_DNS or the PHP build in function getmxrr, default is true
  190. *
  191. * If a parameter is present in the $params array, it replaces the
  192. * default.
  193. *
  194. * @access public
  195. * @param array Hash containing any parameters different from the
  196. * defaults.
  197. * @see _Mail_smtpmx()
  198. */
  199. function __construct($params)
  200. {
  201. if (isset($params['mailname'])) {
  202. $this->mailname = $params['mailname'];
  203. } else {
  204. // try to find a valid mailname
  205. if (function_exists('posix_uname')) {
  206. $uname = posix_uname();
  207. $this->mailname = $uname['nodename'];
  208. }
  209. }
  210. // port number
  211. if (isset($params['port'])) {
  212. $this->_port = $params['port'];
  213. } else {
  214. $this->_port = getservbyname('smtp', 'tcp');
  215. }
  216. if (isset($params['timeout'])) $this->timeout = $params['timeout'];
  217. if (isset($params['verp'])) $this->verp = $params['verp'];
  218. if (isset($params['test'])) $this->test = $params['test'];
  219. if (isset($params['peardebug'])) $this->test = $params['peardebug'];
  220. if (isset($params['netdns'])) $this->withNetDns = $params['netdns'];
  221. }
  222. /**
  223. * Constructor wrapper for PHP4
  224. *
  225. * @access public
  226. * @param array Hash containing any parameters different from the defaults
  227. * @see __construct()
  228. */
  229. function Mail_smtpmx($params)
  230. {
  231. $this->__construct($params);
  232. register_shutdown_function(array(&$this, '__destruct'));
  233. }
  234. /**
  235. * Destructor implementation to ensure that we disconnect from any
  236. * potentially-alive persistent SMTP connections.
  237. */
  238. function __destruct()
  239. {
  240. if (is_object($this->_smtp)) {
  241. $this->_smtp->disconnect();
  242. $this->_smtp = null;
  243. }
  244. }
  245. /**
  246. * Implements Mail::send() function using SMTP direct delivery
  247. *
  248. * @access public
  249. * @param mixed $recipients in RFC822 style or array
  250. * @param array $headers The array of headers to send with the mail.
  251. * @param string $body The full text of the message body,
  252. * @return mixed Returns true on success, or a PEAR_Error
  253. */
  254. function send($recipients, $headers, $body)
  255. {
  256. if (!is_array($headers)) {
  257. return PEAR::raiseError('$headers must be an array');
  258. }
  259. $result = $this->_sanitizeHeaders($headers);
  260. if (is_a($result, 'PEAR_Error')) {
  261. return $result;
  262. }
  263. // Prepare headers
  264. $headerElements = $this->prepareHeaders($headers);
  265. if (is_a($headerElements, 'PEAR_Error')) {
  266. return $headerElements;
  267. }
  268. list($from, $textHeaders) = $headerElements;
  269. // use 'Return-Path' if possible
  270. if (!empty($headers['Return-Path'])) {
  271. $from = $headers['Return-Path'];
  272. }
  273. if (!isset($from)) {
  274. return $this->_raiseError('no_from');
  275. }
  276. // Prepare recipients
  277. $recipients = $this->parseRecipients($recipients);
  278. if (is_a($recipients, 'PEAR_Error')) {
  279. return $recipients;
  280. }
  281. foreach ($recipients as $rcpt) {
  282. list($user, $host) = explode('@', $rcpt);
  283. $mx = $this->_getMx($host);
  284. if (is_a($mx, 'PEAR_Error')) {
  285. return $mx;
  286. }
  287. if (empty($mx)) {
  288. $info = array('rcpt' => $rcpt);
  289. return $this->_raiseError('no_mx', $info);
  290. }
  291. $connected = false;
  292. foreach ($mx as $mserver => $mpriority) {
  293. $this->_smtp = new Net_SMTP($mserver, $this->port, $this->mailname);
  294. // configure the SMTP connection.
  295. if ($this->debug) {
  296. $this->_smtp->setDebug(true);
  297. }
  298. // attempt to connect to the configured SMTP server.
  299. $res = $this->_smtp->connect($this->timeout);
  300. if (is_a($res, 'PEAR_Error')) {
  301. $this->_smtp = null;
  302. continue;
  303. }
  304. // connection established
  305. if ($res) {
  306. $connected = true;
  307. break;
  308. }
  309. }
  310. if (!$connected) {
  311. $info = array(
  312. 'host' => implode(', ', array_keys($mx)),
  313. 'port' => $this->port,
  314. 'rcpt' => $rcpt,
  315. );
  316. return $this->_raiseError('not_connected', $info);
  317. }
  318. // Verify recipient
  319. if ($this->vrfy) {
  320. $res = $this->_smtp->vrfy($rcpt);
  321. if (is_a($res, 'PEAR_Error')) {
  322. $info = array('rcpt' => $rcpt);
  323. return $this->_raiseError('failed_vrfy_rcpt', $info);
  324. }
  325. }
  326. // mail from:
  327. $args['verp'] = $this->verp;
  328. $res = $this->_smtp->mailFrom($from, $args);
  329. if (is_a($res, 'PEAR_Error')) {
  330. $info = array('from' => $from);
  331. return $this->_raiseError('failed_set_from', $info);
  332. }
  333. // rcpt to:
  334. $res = $this->_smtp->rcptTo($rcpt);
  335. if (is_a($res, 'PEAR_Error')) {
  336. $info = array('rcpt' => $rcpt);
  337. return $this->_raiseError('failed_set_rcpt', $info);
  338. }
  339. // Don't send anything in test mode
  340. if ($this->test) {
  341. $result = $this->_smtp->rset();
  342. $res = $this->_smtp->rset();
  343. if (is_a($res, 'PEAR_Error')) {
  344. return $this->_raiseError('failed_rset');
  345. }
  346. $this->_smtp->disconnect();
  347. $this->_smtp = null;
  348. return true;
  349. }
  350. // Send data
  351. $res = $this->_smtp->data($body, $textHeaders);
  352. if (is_a($res, 'PEAR_Error')) {
  353. $info = array('rcpt' => $rcpt);
  354. return $this->_raiseError('failed_send_data', $info);
  355. }
  356. $this->_smtp->disconnect();
  357. $this->_smtp = null;
  358. }
  359. return true;
  360. }
  361. /**
  362. * Recieve mx rexords for a spciefied host
  363. *
  364. * The MX records
  365. *
  366. * @access private
  367. * @param string $host mail host
  368. * @return mixed sorted
  369. */
  370. function _getMx($host)
  371. {
  372. $mx = array();
  373. if ($this->withNetDns) {
  374. $res = $this->_loadNetDns();
  375. if (is_a($res, 'PEAR_Error')) {
  376. return $res;
  377. }
  378. $response = $this->resolver->query($host, 'MX');
  379. if (!$response) {
  380. return false;
  381. }
  382. foreach ($response->answer as $rr) {
  383. if ($rr->type == 'MX') {
  384. $mx[$rr->exchange] = $rr->preference;
  385. }
  386. }
  387. } else {
  388. $mxHost = array();
  389. $mxWeight = array();
  390. if (!getmxrr($host, $mxHost, $mxWeight)) {
  391. return false;
  392. }
  393. for ($i = 0; $i < count($mxHost); ++$i) {
  394. $mx[$mxHost[$i]] = $mxWeight[$i];
  395. }
  396. }
  397. asort($mx);
  398. return $mx;
  399. }
  400. /**
  401. * initialize PEAR:Net_DNS_Resolver
  402. *
  403. * @access private
  404. * @return boolean true on success
  405. */
  406. function _loadNetDns()
  407. {
  408. if (is_object($this->resolver)) {
  409. return true;
  410. }
  411. if (!include_once 'Net/DNS.php') {
  412. return $this->_raiseError('no_resolver');
  413. }
  414. $this->resolver = new Net_DNS_Resolver();
  415. if ($this->debug) {
  416. $this->resolver->test = 1;
  417. }
  418. return true;
  419. }
  420. /**
  421. * raise standardized error
  422. *
  423. * include additional information in error message
  424. *
  425. * @access private
  426. * @param string $id maps error ids to codes and message
  427. * @param array $info optional information in associative array
  428. * @see _errorCode
  429. */
  430. function _raiseError($id, $info = array())
  431. {
  432. $code = $this->errorCode[$id]['code'];
  433. $msg = $this->errorCode[$id]['msg'];
  434. // include info to messages
  435. if (!empty($info)) {
  436. $search = array();
  437. $replace = array();
  438. foreach ($info as $key => $value) {
  439. array_push($search, '{' . strtoupper($key) . '}');
  440. array_push($replace, $value);
  441. }
  442. $msg = str_replace($search, $replace, $msg);
  443. }
  444. return PEAR::raiseError($msg, $code);
  445. }
  446. }