Exemple #1
0
 /**
  * Connect to the SMTP server by instantiating a Net_SMTP object.
  *
  * @return Net_SMTP  The SMTP object.
  * @throws Horde_Mail_Exception
  */
 public function getSMTPObject()
 {
     if ($this->_smtp) {
         return $this->_smtp;
     }
     $this->_smtp = new Net_SMTP($this->_params['host'], $this->_params['port'], $this->_params['localhost']);
     /* Set pipelining. */
     if ($this->_params['pipelining']) {
         $this->_smtp->pipelining = true;
     }
     /* If we still don't have an SMTP object at this point, fail. */
     if (!$this->_smtp instanceof Net_SMTP) {
         throw new Horde_Mail_Exception('Failed to create a Net_SMTP object', self::ERROR_CREATE);
     }
     /* Configure the SMTP connection. */
     if ($this->_params['debug']) {
         $this->_smtp->setDebug(true);
     }
     /* Attempt to connect to the configured SMTP server. */
     $res = $this->_smtp->connect($this->_params['timeout']);
     if ($res instanceof PEAR_Error) {
         $this->_error('Failed to connect to ' . $this->_params['host'] . ':' . $this->_params['port'], $res, self::ERROR_CONNECT);
     }
     /* Attempt to authenticate if authentication has been enabled. */
     if ($this->_params['auth']) {
         $method = is_string($this->_params['auth']) ? $this->_params['auth'] : '';
         $res = $this->_smtp->auth($this->_params['username'], $this->_params['password'], $method);
         if ($res instanceof PEAR_Error) {
             $this->_error("{$method} authentication failure", $res, self::ERROR_AUTH);
         }
     }
     return $this->_smtp;
 }
 /**
  * @see CEvent::HandleEvent()
  * @see bxmail()
  *
  * @param string $to
  * @param string $subject
  * @param string $message
  * @param string $additionalHeaders Additional headers setted by Bitrix.
  *
  * @return bool
  */
 function custom_mail($to, $subject, $message, $additionalHeaders = '')
 {
     // Cache to send many mails in one script run.
     static $transport, $sender;
     try {
         if (!$sender) {
             if (!$transport) {
                 $host = COption::GetOptionString('sh.mailtransport', 'host');
                 if (COption::GetOptionInt('sh.mailtransport', 'ssl')) {
                     $host = 'ssl://' . $host;
                 }
                 $port = COption::GetOptionInt('sh.mailtransport', 'port');
                 $user = COption::GetOptionString('sh.mailtransport', 'username');
                 $password = COption::GetOptionString('sh.mailtransport', 'password');
                 $transport = new Net_SMTP($host, $port);
                 if (PEAR::isError($connectionResult = $transport->connect())) {
                     throw new Capall_MailTransportException($connectionResult);
                 }
                 // TODO Server without authentication?..
                 if (PEAR::isError($authenticationResult = $transport->auth($user, $password))) {
                     throw new Capall_MailTransportException($authenticationResult);
                 }
             }
             $sender = new Capall_MailTransport_Sender($transport);
         }
         $sender->send($to, $subject, $message, $additionalHeaders);
         return true;
     } catch (Capall_MailTransportException $error) {
         CEventLog::Log('WARNING', 'MAILTRANSPORT_ERROR', 'sh.mailtransport', null, $error->__toString());
         return false;
     } catch (Exception $error) {
         // Unknown error...
         return false;
     }
 }
Exemple #3
0
 function Mail($to, $to_name, $from, $from_name, $subject, $text, $type = 'text')
 {
     //----
     include_once 'lib/PEAR/Net/SMTP.php';
     //----
     $to_name = $this->MailEsc($to_name);
     $from_name = $this->MailEsc($from_name);
     $subject = $this->MailEsc($subject);
     //----
     $headers = "MIME-Version: 1.0\r\n" . "Return-Path: {$from}\r\n" . "X-Mailer: MQL4 site\r\n" . "Date: " . date('r') . "\r\n" . "Message-Id: " . time() . '.' . preg_replace('/[^0-9a-z-]+/iu', '-', $to) . "@wr.com\r\n";
     //----
     if ($type == 'text') {
         $headers .= "Content-type: text/plain; charset=UTF-8\r\n";
     } else {
         $headers .= "Content-type: text/html; charset=UTF-8\r\n";
     }
     //----
     if ($to_name != '') {
         $headers .= "To: {$to_name} <{$to}>\r\n";
     } else {
         $headers .= "To: {$to}\r\n";
     }
     if ($from_name != '') {
         $headers .= "From: {$from_name} <{$from}>\r\n";
     } else {
         $headers .= "From: {$from}\r\n";
     }
     //----
     $smtp = new Net_SMTP(T_SMTP_SERVER, 25, T_SMTP_LOGIN);
     $smtp->connect();
     //----
     if (PEAR::isError($e = $smtp->auth(T_SMTP_LOGIN, T_SMTP_PASSWORD))) {
         $smtp->disconnect();
         return false;
     }
     //----
     if (PEAR::isError($smtp->mailFrom($from))) {
         $smtp->disconnect();
         return false;
     }
     //----
     if (PEAR::isError($smtp->rcptTo($to))) {
         $smtp->disconnect();
         return false;
     }
     //----
     if (PEAR::isError($smtp->data("Subject: {$subject}\r\n" . $headers . "\r\n" . $text))) {
         $smtp->disconnect();
         return false;
     }
     //----
     $smtp->disconnect();
     //----
     return true;
 }
Exemple #4
0
    public function deliver(&$Mailer, $settings = array())
    {
        $Message =& $Mailer->Message;
        
        $SmtpClient =& Mail::factory('smtp', $settings);

        include_once 'Net/SMTP.php';

        if (!($smtp = new Net_SMTP($SmtpClient->host, $SmtpClient->port, $SmtpClient->localhost))) {
            return PEAR::raiseError('unable to instantiate Net_SMTP object');
        }

        if ($SmtpClient->debug) {
            $smtp->setDebug(true);
        }

        if (PEAR::isError($smtp->connect($SmtpClient->timeout))) {
            trigger_error('unable to connect to smtp server '.$SmtpClient->host.':'.$SmtpClient->port, E_USER_NOTICE);
            return false;
        }

        if ($SmtpClient->auth) {
            $method = is_string($SmtpClient->auth) ? $SmtpClient->auth : '';

            if (PEAR::isError($smtp->auth($SmtpClient->username, $SmtpClient->password, $method))) {
                trigger_error('unable to authenticate to smtp server', E_USER_ERROR);
            }
        }

        $from = is_array($Message->from) ? array_shift(array_values($Message->from)) : $Message->from;

        if (PEAR::isError($smtp->mailFrom($from))) {
            trigger_error('unable to set sender to [' . $from . ']', E_USER_ERROR);
        }

        $recipients = $SmtpClient->parseRecipients($Message->getRecipients());
        
        if (PEAR::isError($recipients)) {
            return $recipients;
        }

        foreach ($recipients as $recipient) {
            if (PEAR::isError($res = $smtp->rcptTo($recipient))) {
                return PEAR::raiseError('unable to add recipient [' .
                $recipient . ']: ' . $res->getMessage());
            }
        }

        if (PEAR::isError($smtp->data($Mailer->getRawMessage()))) {
            return PEAR::raiseError('unable to send data');
        }

        $smtp->disconnect();
    }
Exemple #5
0
 function check()
 {
     $ff = HTML_FlexyFramework::get();
     if (empty($ff->Core_Notify) || empty($ff->Core_Notify['routes'])) {
         return;
     }
     $helo = $this->getHelo();
     echo "HELO : {$helo} \n";
     $error = array();
     foreach ($ff->Core_Notify['routes'] as $server => $settings) {
         if (empty($settings['domains']) || empty($settings['username']) || empty($settings['password'])) {
             $error[] = "{$server} - Missing domains / username / password";
             continue;
         }
         $socket_options = array('ssl' => array('verify_peer' => false, 'verify_peer_name' => false));
         if (empty($settings['port'])) {
             $settings['port'] = 25;
         }
         $smtp = new Net_SMTP($server, $settings['port'], $helo, false, 0, $socket_options);
         //            $smtp->setDebug(true);
         echo "Connecting : {$server}:{$settings['port']} \n";
         $res = $smtp->connect(10);
         if (is_a($res, 'PEAR_Error')) {
             $error[] = "{$server} - Cound not connect";
             continue;
         }
         echo "Login As : {$settings['username']}:{$settings['password']} \n";
         $res = $smtp->auth($settings['username'], $settings['password']);
         if (is_a($res, 'PEAR_Error')) {
             $error[] = "{$server} - Cound not login";
             continue;
         }
     }
     if (!empty($error)) {
         print_r($error);
         exit;
     }
     return;
 }
Exemple #6
0
// Security because webroot.
require 'Net/SMTP.php';
$host = 'mail.example.com';
$from = '*****@*****.**';
$rcpt = array('*****@*****.**', '*****@*****.**');
$subj = "Subject: Test Message\n";
$body = "Body Line 1\nBody Line 2";
/* Create a new Net_SMTP object. */
if (!($smtp = new Net_SMTP($host))) {
    die("Unable to instantiate Net_SMTP object\n");
}
/* Connect to the SMTP server. */
if (PEAR::isError($e = $smtp->connect())) {
    die($e->getMessage() . "\n");
}
$smtp->auth('username', 'password');
/* Send the 'MAIL FROM:' SMTP command. */
if (PEAR::isError($smtp->mailFrom($from))) {
    die("Unable to set sender to <{$from}>\n");
}
/* Address the message to each of the recipients. */
foreach ($rcpt as $to) {
    if (PEAR::isError($res = $smtp->rcptTo($to))) {
        die("Unable to add recipient <{$to}>: " . $res->getMessage() . "\n");
    }
}
/* Set the body of the message. */
if (PEAR::isError($smtp->data($subj . "\r\n" . $body))) {
    die("Unable to send data\n");
}
/* Disconnect from the SMTP server. */
Exemple #7
0
 /**
  * Implements Mail::send() function using SMTP.
  * 
  * @param mixed $recipients Either a comma-seperated list of recipients
  *              (RFC822 compliant), or an array of recipients,
  *              each RFC822 valid. This may contain recipients not
  *              specified in the headers, for Bcc:, resending
  *              messages, etc.
  *
  * @param array $headers The array of headers to send with the mail, in an
  *              associative array, where the array key is the
  *              header name (ie, 'Subject'), and the array value
  *              is the header value (ie, 'test'). The header
  *              produced from those values would be 'Subject:
  *              test'.
  *
  * @param string $body The full text of the message body, including any
  *               Mime parts, etc.
  *
  * @return mixed Returns true on success, or a PEAR_Error
  *               containing a descriptive error message on
  *               failure.
  * @access public
  */
 function send($recipients, $headers, $body)
 {
     include_once 'Net/SMTP.php';
     if (!($smtp = new Net_SMTP($this->host, $this->port))) {
         return new PEAR_Error('unable to instantiate Net_SMTP object');
     }
     if (PEAR::isError($smtp->connect())) {
         return new PEAR_Error('unable to connect to smtp server ' . $this->host . ':' . $this->port);
     }
     if ($this->auth) {
         if (PEAR::isError($smtp->auth($this->username, $this->password))) {
             return new PEAR_Error('unable to authenticate to smtp server');
         }
         if (PEAR::isError($smtp->identifySender())) {
             return new PEAR_Error('unable to identify smtp server');
         }
     }
     list($from, $text_headers) = $this->prepareHeaders($headers);
     if (!isset($from)) {
         return new PEAR_Error('No from address given');
     }
     if (PEAR::isError($smtp->mailFrom($from))) {
         return new PEAR_Error('unable to set sender to [' . $from . ']');
     }
     $recipients = $this->parseRecipients($recipients);
     foreach ($recipients as $recipient) {
         if (PEAR::isError($res = $smtp->rcptTo($recipient))) {
             return new PEAR_Error('unable to add recipient [' . $recipient . ']: ' . $res->getMessage());
         }
     }
     if (PEAR::isError($smtp->data($text_headers . "\n" . $body))) {
         return new PEAR_Error('unable to send data');
     }
     $smtp->disconnect();
     return true;
 }
 /**
  * Implements Mail::send() function using SMTP.
  *
  * @param mixed $recipients Either a comma-seperated list of recipients
  *              (RFC822 compliant), or an array of recipients,
  *              each RFC822 valid. This may contain recipients not
  *              specified in the headers, for Bcc:, resending
  *              messages, etc.
  *
  * @param array $headers The array of headers to send with the mail, in an
  *              associative array, where the array key is the
  *              header name (e.g., 'Subject'), and the array value
  *              is the header value (e.g., 'test'). The header
  *              produced from those values would be 'Subject:
  *              test'.
  *
  * @param string $body The full text of the message body, including any
  *               Mime parts, etc.
  *
  * @return mixed Returns true on success, or a PEAR_Error
  *               containing a descriptive error message on
  *               failure.
  * @access public
  */
 function send($recipients, $headers, $body)
 {
     include_once 'Net/SMTP.php';
     if (!($smtp = new Net_SMTP($this->host, $this->port, $this->localhost))) {
         return new PEAR_Error('unable to instantiate Net_SMTP object');
     }
     if (PEAR::isError($smtp->connect())) {
         return new PEAR_Error('unable to connect to smtp server ' . $this->host . ':' . $this->port);
     }
     if ($this->auth) {
         $method = is_string($this->auth) ? $this->auth : '';
         if (PEAR::isError($smtp->auth($this->username, $this->password, $method))) {
             return new PEAR_Error('unable to authenticate to smtp server');
         }
     }
     list($from, $text_headers) = $this->prepareHeaders($headers);
     /*
      * Since few MTAs are going to allow this header to be forged unless
      * it's in the MAIL FROM: exchange, we'll use Return-Path instead of
      * From: if it's set.
      */
     if (!empty($headers['Return-Path'])) {
         $from = $headers['Return-Path'];
     }
     if (!isset($from)) {
         return new PEAR_Error('No from address given');
     }
     if (PEAR::isError($smtp->mailFrom($from))) {
         return new PEAR_Error('unable to set sender to [' . $from . ']');
     }
     $recipients = $this->parseRecipients($recipients);
     foreach ($recipients as $recipient) {
         if (PEAR::isError($res = $smtp->rcptTo($recipient))) {
             return new PEAR_Error('unable to add recipient [' . $recipient . ']: ' . $res->getMessage());
         }
     }
     if (PEAR::isError($smtp->data($text_headers . "\r\n" . $body))) {
         return new PEAR_Error('unable to send data');
     }
     $smtp->disconnect();
     return true;
 }
Exemple #9
0
         // dirty hack using <img> tag...
         $_SESSION['subscribe_hack'] = 1;
     }
 }
 if (empty($smtpHost)) {
     $smtpHost = 'localhost';
 }
 // Try to connect to SMTP host
 set_include_path('../' . PATH_SEPARATOR . get_include_path());
 require_once '../libs/PEAR/Net/SMTP.php';
 $smtp = new Net_SMTP($smtpHost);
 $con = $smtp->connect();
 if (isset($_POST['smtp_auth'])) {
     $_SESSION['pref']['smtpauth_username'] = $_POST['smtpauth_username'];
     $_SESSION['pref']['smtpauth_password'] = $_POST['smtpauth_password'];
     if ($smtp->auth($_SESSION['pref']['smtpauth_username'], $_SESSION['pref']['smtpauth_password']) !== true) {
         $errors['smtp_error'] .= "The SMTP authentication details provided are incorrect. Please verify you have the correct username and password. Check your SMTP configuration for further details, or use an SMTP server which you have IP relay permissions.";
         $vars['smtphost'] = $_SESSION['pref']['smtphost'];
         $vars['smtpauth_username'] = $_SESSION['pref']['smtpauth_username'];
         $vars['smtpauth_password'] = $_SESSION['pref']['smtpauth_password'];
         $vars['admin_email'] = $_SESSION['pref']['admin_email'];
         $vars['smtp_auth_error'] = '1';
         $vars['smtp_auth_check'] = 'checked';
     } else {
         $_SESSION['pref']['smtpauth_username'] = '';
         $_SESSION['pref']['smtpauth_password'] = '';
     }
 }
 if (PEAR::isError($con)) {
     $errors['smtp_error'] = $con->getMessage();
     $vars['bad_smtp_host'] = $smtpHost;
function open_smtp(&$arr_mail_account, &$smtp, $account_no, $debug_flag)
{
    // account list array, from config.php
    global $arrAccountsSmtp;
    // $account_noの範囲チェック
    if ($account_no <= 0 || $account_no > count($arrAccountsSmtp)) {
        printf("<p>アカウント指定Noが範囲外です<br/>account=%d</p>\n", $account_no);
        return false;
    }
    // メールアカウント情報(サーバ名、ユーザ名、パスワード等)を得る
    $arr_mail_account = GetMailAccount($arrAccountsSmtp[$account_no - 1][1], 'smtp');
    if (!isset($arr_mail_account['server']) || !isset($arr_mail_account['user']) || !isset($arr_mail_account['password']) || strcmp($arr_mail_account['protocol'], 'smtp')) {
        print "<p>メールアカウント管理エラー(server/user/password値が得られないか、protocolがsmtpでない)</p>\n";
        return false;
    }
    // 新しい Net_SMTP オブジェクトを作成します
    if (!($smtp = new Net_SMTP($arr_mail_account['server'], $arr_mail_account['port']))) {
        print "<p>ネットワーク異常(SMTPオブジェクト作成不能)</p>";
        return false;
    }
    // デバッグ出力を、stdoutに送る
    if ($debug_flag) {
        $smtp->setDebug(true);
    }
    // SMTP サーバに接続します
    if (PEAR::isError($e = $smtp->connect())) {
        print "<p>ネットワーク異常(SMTPでコネクション不能)</p>";
        return false;
    }
    // ユーザ名、パスワードを用いてSMTPログオンします
    // (Digest-MD5, CRAMMD5, LOGIN, PLAINの順に暗号強度の高いもので接続します)
    if (PEAR::isError($e = $smtp->auth($arr_mail_account['user'], $arr_mail_account['password']))) {
        $smtp->disconnect();
        print "<p>SMTPサーバの認証に失敗</p>";
        return false;
    }
    printf("<p>接続:%s@%s:%s</p>\n", $arr_mail_account['user'], $arr_mail_account['server'], $arr_mail_account['port']);
    return true;
}
Exemple #11
0
 function deliver($catch_smtp_error = true)
 {
     global $pref, $atmail, $domains;
     $rcpt = array();
     // Make an array with the email addresses to deliver the
     // message to
     /*
     	    $rcpt = array_merge($rcpt, preg_split('/;|,/', $this->EmailTo));
     
     if (!empty($this->EmailCC))
     	$rcpt = array_merge($rcpt, preg_split('/;|,/', $this->EmailCC));
     
     if (!empty($this->EmailBCC))
     	$rcpt = array_merge($rcpt, preg_split('/;|,/', $this->EmailBCC));
     */
     $rcpt = $this->EmailTo;
     if (!empty($this->EmailCC)) {
         $rcpt .= ",{$this->EmailCC}";
     }
     if (!empty($this->EmailBCC)) {
         $rcpt .= ",{$this->EmailBCC}";
     }
     // Remove personal part - it is not needed for send RCPT cmd
     // and just causes problems for the address parser if it contains
     // certain utf-8 chars (e.g. Japanese)
     $rcpt = preg_replace('/".+?"/', '', $rcpt);
     $rcpt = Mail_RFC822::parseAddressList($rcpt, null, false);
     $mail = array();
     $groupmails = 0;
     // Loop through the non-existant recipients
     foreach ($rcpt as $entry) {
         // The entry is a group email-address
         if ($entry->host == 'Group') {
             $users = $this->abook->getgroup($entry->mailbox);
             foreach ($users as $user) {
                 // Skip emailing the selected user, if local, and the user does not exist any longer
                 if ($this->rcptOK($user)) {
                     $groupmails++;
                     array_push($mail, $user);
                 }
             }
         } elseif ($entry->host == 'SharedGroup') {
             $users = $this->abook->getsharedgroup($entry->mailbox);
             foreach ($users as $user) {
                 // Skip emailing the selected user, if local, and the user does not exist any longer
                 if ($this->rcptOK($user)) {
                     $groupmails++;
                     array_push($mail, $user);
                 }
             }
         } else {
             array_push($mail, stripslashes("{$entry->mailbox}@{$entry->host}"));
         }
     }
     // Block more then X outgoing recipients at a time ( useful to prevent spammers/bots abusing the service )
     if (count($mail) - $groupmails > $pref['max_recipients_per_msg']) {
         $this->smtperror("Cannot send to more than {$pref['max_recipients_per_msg']} users per email message.");
     }
     require_once 'Net/SMTP.php';
     $smtp = new Net_SMTP($pref['smtphost'], null, $_SERVER['HTTP_HOST']);
     //$smtp->setDebug(true);
     if ($smtp->connect(30) !== true) {
         if ($catch_smtp_error) {
             $this->smtperror("Error connecting to {$pref['smtphost']} - Check the hostname resolves, accepts incoming SMTP connections and is active.");
         } else {
             return false;
         }
     }
     // Check if we should use each account's username and password
     // for the SMTP
     if ($pref['smtp_per_account_auth']) {
         $pref['smtpauth_username'] = $atmail->auth->get_username();
         $pref['smtpauth_password'] = $atmail->auth->get_password();
     }
     // Optionally authenticate with the SMTP server
     if ($pref['smtpauth_username'] && $pref['smtpauth_password']) {
         if ($smtp->auth($pref['smtpauth_username'], $pref['smtpauth_password']) !== true) {
             if ($catch_smtp_error) {
                 $this->smtperror("Error authenticating to {$pref['smtphost']} - Check the SMTP authentication is correct");
             } else {
                 $this->smtp_error_msg = "Error authenticating to {$pref['smtphost']} - Check the SMTP authentication is correct";
                 return false;
             }
         }
     }
     $smtp->mailFrom($this->EmailFrom);
     $fails = array();
     //$smtp->setDebug(true);
     foreach ($mail as $v) {
         $res = $smtp->rcptTo($v);
         if (PEAR::isError($res)) {
             if ($catch_smtp_error) {
                 $output = $res->getMessage();
                 $this->smtperror("Could not send message to SMTP server. Check you have access to send messages via the server and that all To/CC/BCC addresses are valid\\nError: {$output}");
                 break;
             } else {
                 $fails[] = $v;
                 continue;
             }
         }
     }
     $res = $smtp->data($this->headers . "\r\n\r\n" . $this->body);
     if (PEAR::isError($res)) {
         if ($catch_smtp_error) {
             $this->smtperror("Message rejected by SMTP server. Check message content and attachments\\nServer Responded: " . $res->getMessage());
         } else {
             $this->smtp_error_msg = "Message rejected by SMTP server. Check message content and attachments\nServer Responded: " . $res->getMessage();
             return false;
         }
     } elseif ($pref['install_type'] == 'standalone') {
         // Only log sent msgs if running only as webmail client
         // as Exim already does this when in server mode
         foreach ($mail as $addr) {
             $addr = preg_replace('/\\s+/', '', $addr);
             $this->log->write_log("SendMail", "WebMail:{$_SERVER['REMOTE_ADDR']}:{$addr}");
         }
     }
     $smtp->disconnect();
     // Reset some fields back to the raw UTF8 copy, since it's sent to the browser
     $this->EmailSubject = $this->RawEmailSubject;
     return $fails;
 }
Exemple #12
0
 static function validate_login_smtp($username, $password)
 {
     $hostname = explode(":", SETUP_AUTH_HOSTNAME_SMTP);
     if (!isset($hostname[1])) {
         $hostname[1] = 25;
     }
     if (isset($hostname[2]) and !extension_loaded("openssl")) {
         sys_log_message_alert("login", sprintf("{t}%s is not compiled / loaded into PHP.{/t}", "SMTP / OpenSSL"));
         return false;
     }
     $smtp = new Net_SMTP((isset($hostname[2]) ? $hostname[2] . "://" : "") . $hostname[0], $hostname[1]);
     if (PEAR::isError($e = $smtp->connect(10)) or PEAR::isError($e = $smtp->auth($username, $password))) {
         sys_log_message_alert("login", sprintf("{t}Login failed from %s.{/t} (smtp) ({t}Username{/t}: %s, %s)", _login_get_remoteaddr(), $username, $e->getMessage()));
         return false;
     } else {
         return true;
     }
 }
 /**
  * Get Net_SMTP instance
  *
  * Returned instance must be authenticated and connected.
  *
  * @param string $provider
  *   Any provider defined in the 'netsmtp' variable
  *
  * @return Net_SMTP
  *   Or null if instance could not be created or could not connect
  *   to SMTP server
  */
 protected function getInstance($provider = self::PROVIDER_DEFAULT)
 {
     $isTLS = false;
     $config = variable_get('netsmtp');
     if (empty($config[$provider])) {
         $this->setError(sprintf("Provider '%s' does not exists, fallback on default", $provider), WATCHDOG_WARNING);
         if (empty($config[$provider])) {
             $this->setError(sprintf("Default provider is not set", $provider));
             return null;
         }
     }
     if (empty($config[$provider]['hostname'])) {
         $this->setError(sprintf("Provider '%s' has no hostname", $provider));
         return null;
     }
     $info = array_filter($config[$provider]) + array('port' => null, 'username' => null, 'use_ssl' => false, 'password' => '', 'localhost' => null);
     if ($info['use_ssl']) {
         if ('tls' === $info['use_ssl']) {
             $info['hostname'] = 'tls://' . $info['hostname'];
             $isTLS = true;
         } else {
             $info['hostname'] = 'ssl://' . $info['hostname'];
         }
         if (empty($info['port'])) {
             $info['port'] = self::DEFAULT_SSL_PORT;
         }
     }
     // Attempt connection
     $smtp = new Net_SMTP($info['hostname'], $info['port'], $info['localhost']);
     if ($this->PEAR->isError($e = $smtp->connect())) {
         $this->setError($e);
         return null;
     }
     if (!empty($info['username'])) {
         if ($this->PEAR->isError($e = $smtp->auth($info['username'], $info['password'], '', $isTLS))) {
             $this->setError($e);
             return null;
         }
     }
     // Finally! We did it I guess.
     return $smtp;
 }
Exemple #14
0
 /**
  * Sends and e-mail using Net_SMTP.
  *
  * @param Email $email
  * @return string Error message, or null upon success.
  */
 public static function smtp(&$email)
 {
     /*
         if ( isset($GLOBALS['phpmail']) && $GLOBALS['phpmail'] )
         {
           $rfc = new \Mail_RFC822();
           $pureAddresses = $rfc->parseAddressList($email->to());
           foreach( $pureAddresses as $address )
           {
             $to = $address->mailbox. "@". $address->host;
             mail( $to, $email->subject(), $email->body(), $email->headers() );
           }
           return;
         }
     */
     Log::debug("Mailer: subject:[" . $email->subject() . "], from:[" . $email->from() . "], to:" . print_r($email->recipients(), true));
     if (!Config::$smtpHost) {
         $error = "Mailer: no SMTP host supplied";
         Log::debug($error);
         return $error;
     }
     if (!($smtp = new \Net_SMTP(Config::$smtpHost, Config::$smtpPort, $_SERVER['SERVER_NAME']))) {
         $error = "Mailer: unable to instantiate Net_SMTP object";
         Log::debug($error);
         return $error;
     }
     // $smtp->setDebug(true);
     $pear = new \PEAR();
     if ($pear->isError($e = $smtp->connect())) {
         $error = "Mailer: connect error: " . $e->getMessage();
         Log::debug($error);
         return $error;
     }
     if (Config::$smtpUser && $pear->isError($e = $smtp->auth(Config::$smtpUser, Config::$smtpPass, Config::$smtpAuthType))) {
         $error = "Mailer: authentication error: " . $e->getMessage();
         Log::debug($error);
         return $error;
     }
     $rfc = new \Mail_RFC822();
     $pureAddresses = $rfc->parseAddressList($email->from());
     $from = $pureAddresses[0]->mailbox . "@" . $pureAddresses[0]->host;
     if ($pear->isError($e = $smtp->mailFrom($from))) {
         $error = "Unable to set sender to [{$from}]: " . $e->getMessage();
         Log::debug($error);
         return $error;
     }
     foreach ($email->recipients() as $toAddress) {
         $pureAddresses = $rfc->parseAddressList($toAddress);
         foreach ($pureAddresses as $address) {
             $to = $address->mailbox . "@" . $address->host;
             if ($pear->isError($e = $smtp->rcptTo($to))) {
                 $error = "Unable to set recipient to [{$to}]: " . $e->getMessage();
                 Log::debug($error);
                 return $error;
             }
         }
     }
     if ($pear->isError($e = $smtp->data($email->data()))) {
         $error = "Unable to set data: " . $e->getMessage();
         Log::debug($error);
         return $error;
     }
     Log::debug("Mailer: sent: " . $smtp->_arguments[0]);
     $smtp->disconnect();
     return null;
 }