<?php

require_once('Mail.php');
require_once('Mail/mime.php');

class tgImap {
    var $conf;
    var $sender;
    var $bcc;
    var $reply;

    function __construct($conf) {
        $this->conf = $conf;
        $this->bcc = $conf['mail']['bcc'];
        $this->reply = $conf['mail']['reply'];
        $this->sender = $conf['mail']['sender'];

        // $params['debug'] = true;
        $params['host'] = $conf['mail']['smtpHost'];
        $params['localhost'] = $conf['mail']['smtpEhlo'];
        $params['username'] = $conf['mail']['smtpUser'];

        $this->smtp =& Mail::factory('smtp', $params);
    }

    function mail($to, $subject, $body) {
        /**
         * Falls eine Zeile der Nachricht mehr als 70 Zeichen enthälten könnte, 
         * sollte wordwrap() benutzt werden (http://de.php.net/manual/de/function.mail.php):
         *
         * $body = wordwrap($body, 70);
         * $header = 'From: '. $this->sender . "\n" .
         *           'Reply-To: '. $this->sender . "\n" .
         *           'Cc: ' . $this->cc . "\n" .
         *           'X-Mailer: PHP/' . phpversion() . "\n" .
         *           'MIME-Version: 1.0' . "\n" .
         *           'Content-type: text/plain; charset=UTF-8' . "\n".
         *           'Content-Transfer-Encoding: 8bit' . "\n";
         *
         * Replace line breaks on www.textgrid.de:
         *
         * $body = str_replace("\r\n", "\n", $body);
         * mail($to, $subject, $body, $header);
         */

        if (strpos($subject, 'Request Received') or strpos($subject, 'Anfrage eingegangen')) {
            $recipients = $to;
        } 
        else {
            $recipients = $to . ', ' . $this->bcc;
            $headers['Bcc'] = $this->bcc;
        }

        $headers['From']     = $this->sender;
        $headers['Reply-To'] = $this->reply;
        $headers['Subject']  = $subject;
        $headers['To']       = $to;

        $body = wordwrap($body, 70);
        $text = $body;
        // $html = '<html><body>' . nl2br($body) . '</body></html>';

        $mime = new Mail_mime(array('eol' => "\n",
            'head_charset' => 'UTF-8',
            'text_charset' => 'UTF-8',
            'text_encoding' => '8bit')
        );
        // $mime = new Mail_mime(array('eol' => "\n",
        //     'head_charset' => 'UTF-8',
        //     'html_charset' => 'UTF-8',
        //     'text_charset' => 'UTF-8',
        //     'text_encoding' => '8bit')
        // );

        $mime->setTXTBody($text);
        // $mime->setHTMLBody($html);

        $body = $mime->get();
        $headers = $mime->headers($headers);

        $this->smtp->send($recipients, $headers, $body);
    }
}

?>