Skip to content
ispcmail.inc.php 26.3 KiB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
<?php

/*
Copyright (c) 2012, Marius Cramer, pixcept KG
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
    * Neither the name of ISPConfig nor the names of its contributors
      may be used to endorse or promote products derived from this software without
      specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/**
 * email class
 *
 * @package pxFramework
 *
 */


class ispcmail {

	/**#@+
     * @access private
     */
	private $html_part;
	private $text_part;

	private $headers;

	private $_logged_in = false;
	private $_smtp_conn = null;

	private $_crlf = "\n";

	private $attach_type = 'application/octet-stream';
	private $attachments;
	private $mime_boundary;
	private $body = '';
	private $_mail_sender = '';
	private $_sent_mails = 0;
	private $user_agent = 'ISPConfig/3 (Mailer Class)';
	/**#@-*/



	/**
	 * set the mail charset
	 */
	private $mail_charset  = 'UTF-8';//'ISO-8859-1';

	/**#@+
     * Provide smtp credentials for smtp mail sending
     *
     * @access public
     */

	/**
	 * if set to true smtp is used instead of mail() to send emails
	 * @see mail
	 */
	private $use_smtp = false;

	/**
	 * the smtp helo string - use the mail server name here!
	 */
	private $smtp_helo = '';

	/**
	 * the smtp server to send mails
	 */
	private $smtp_host = '';

	/**
	 * the smtp port
	 */
	private $smtp_port = 25;

	/**
	 * if the smtp server needs authentication you can set the smtp user here
	 */
	private $smtp_user = '';

	/**
	 * if the smtp server needs authentication you can set the smtp password here
	 */
	private $smtp_pass = '';

	/**
	 * If you want to use tls/ssl specify it here
	 */
	private $smtp_crypt = ''; // tls or ssl
	/**
	 * How many mails should be sent via one single smtp connection
	 */
	private $smtp_max_mails = 20;

	/**
	 * Should the mail be signed
	 */
	private $sign_email = false;

	/**
	 * The cert and key to use for email signing
	 */
	private $sign_key = '';
	private $sign_key_pass = '';
	private $sign_cert = '';
	private $sign_bundle = '';
	private $_is_signed = false;

	/**
	 * get disposition notification
	 */
	private $notification = false;
	/**#@-*/

	public function __construct($options = array()) {
		$rand = md5(microtime());
		$this->mime_boundary = '==Multipart_Boundary_x' . $rand . 'x';

		$this->headers = array();
		$this->attachments = array();

		$this->headers['MIME-Version'] = '1.0';
		$this->headers['User-Agent'] = $this->user_agent;
		if(is_array($options) && count($options) > 0) $this->setOptions($options);
	}

	public function __destruct() {
		$this->finish();
	}



	/**
	 * Set option
	 *
	 * @param string $key the option to set
	 * @param string $value the option value to set
	 */
	public function setOption($key, $value) {
		switch($key) {
		case 'smtp_helo':
			$this->smtp_helo = $value;
			break;
		case 'smtp_host':
			$this->smtp_host = $value;
			break;
		case 'smtp_server':
			$this->smtp_host = $value;
			break;
		case 'smtp_port':
			$this->smtp_port = $value;
			break;
		case 'smtp_user':
			$this->smtp_user = $value;
			break;
		case 'smtp_pass':
			$this->smtp_pass = $value;
			break;
		case 'smtp_max_mails':
			$this->smtp_max_mails = intval($value);
			if($this->smtp_max_mails < 1) $this->smtp_max_mails = 1;
			break;
		case 'use_smtp':
			$this->use_smtp = ($value == true ? true : false);
			if($value == true) $this->_crlf = "\r\n";
			break;
		case 'smtp_crypt':
			if($value != 'ssl' && $value != 'tls') $value = '';
			$this->smtp_crypt = $value;
			break;
		case 'sign_email':
			$this->sign_email = ($value == true ? true : false);
			break;
		case 'sign_key':
			$this->sign_key = $value;
			break;
		case 'sign_key_pass':
			$this->sign_key_pass = $value;
			break;
		case 'sign_cert':
			$this->sign_cert = $value;
			break;
		case 'sign_bundle':
			$this->sign_bundle = $value;
			break;
		case 'mail_charset':
			$this->mail_charset = $value;
			break;
		case 'notify':
			$this->notification = ($value == true ? true : false);
			break;
		}
	}



	/** Detect the helo string if none given
	 *
	 */
	private function detectHelo() {
		if(isset($_SERVER['HTTP_HOST'])) $this->smtp_helo = (strpos($_SERVER['HTTP_HOST'], ':') !== false ? substr($_SERVER['HTTP_HOST'], 0, strpos($_SERVER['HTTP_HOST'], ':')) : $_SERVER['HTTP_HOST']);
		elseif(isset($_SERVER['SERVER_NAME'])) $this->smtp_helo = $_SERVER['SERVER_NAME'];
		else $this->smtp_helo = php_uname('n');
		if($this->smtp_helo == '') $this->smtp_helo = 'localhost';
		return $this->smtp_helo;
	}



	/**
	 * Set options
	 *
	 * @param array $options the options to set as an associative array key => value
	 */
	public function setOptions($options) {
		foreach($options as $key => $value) $this->setOption($key, $value);
	}



	/**
	 * Read a file's contents
	 *
	 * Simply gets the file's content
	 *
	 * @access public
	 * @param string $filename name and path of file to read
	 * @return string file content (can be binary)
	 */
	public function read_File($filename) {
		$content = '';

		$fp = fopen($filename, 'r');
		if(!$fp) return false;

		while(!feof($fp)) {
			$content .= fread($fp, 1024);
		}
		fclose($fp);

		return $content;
	}



	/**
	 * set smtp connection encryption
	 *
	 * @access public
	 * @param string $mode encryption mode (tls, ssl or empty string)
	 */
	public function setSMTPEncryption($mode = '') {
		if($mode != 'ssl' && $mode != 'tls') $mode = '';
		$this->smtp_crypt = $mode;
	}

	/**
	 * set a mail header
	 *
	 * Sets a single mail header to a given value
	 *
	 * @access public
	 * @param string $header header name to set
	 * @param string $value value to set in header field
	 */
	public function setHeader($header, $value) {
		if(strtolower($header) == 'bcc') $header = 'Bcc';
		elseif(strtolower($header) == 'cc') $header = 'Cc';
		elseif(strtolower($header) == 'from') $header = 'From';
		$this->headers["$header"] = $value;
	}



	/**
	 * get a mail header value
	 *
	 * Returns a value of a single mail header
	 *
	 * @access public
	 * @param string $header header name to get
	 * @return string header value
	 */
	public function getHeader($header) {
		if(strtolower($header) == 'bcc') $header = 'Bcc';
		elseif(strtolower($header) == 'cc') $header = 'Cc';
		elseif(strtolower($header) == 'from') $header = 'From';
		return isset($this->headers["$header"]) ? $this->headers["$header"] : '';
	}



	/**
	 * Set email sender
	 *
	 * Sets the email sender and optionally the sender's name
	 *
	 * @access public
	 * @param string $email sender email address
	 * @param string $name sender name
	 */
	public function setSender($email, $name = '') {
		if($name) $header = '"' . $name . '" <' . $email . '>';
		else $header = '<' . $email . '>';

		$this->_mail_sender = $email;

		$this->setHeader('From', $header);
	}



	/**
	 * Set mail subject
	 *
	 * @access public
	 * @param string $subject the mail subject
	 * @return string where-string for db query
	 */
	public function setSubject($subject) {
		$this->setHeader('Subject', $subject);
	}



	/**
	 * Get current mail subject
	 *
	 * @access public
	 * @return string mail subject
	 */
	public function getSubject() {
		return $this->headers['Subject'];
	}



	/**
	 * Set mail content
	 *
	 * Sets the mail html and plain text content
	 *
	 * @access public
	 * @param string $text plain text mail content (can be empty)
	 * @param string $html html mail content
	 */
	public function setMailText($text, $html = '') {
		$this->text_part = $text;
		$this->html_part = $html;
	}



	/**
	 * Read and attach a file
	 *
	 * Reads a file and attaches it to the current email
	 *
	 * @access public
	 * @param string $filename the file to read and attach
	 * @param string $display_name the name that will be displayed in the mail
	 * @see read_File
	 */
	public function readAttachFile($filename, $display_name = '') {
		if($display_name == '') {
			$path_parts = pathinfo($filename);
			$display_name = $path_parts["basename"];
			unset($path_parts);
		}
		$this->attachFile($this->read_File($filename), $display_name);
	}



	/**
	 * Attach a file
	 *
	 * Attaches a string (can be binary) as a file to the mail
	 *
	 * @access public
	 * @param string $content attachment data string
	 * @param string $filename name for file attachment
	 */
	public function attachFile($content, $filename) {
		$attachment = array('content' => $content,
			'filename' => $filename,
			'type' => 'application/octet-stream',
			'encoding' => 'base64'
		);
		$this->attachments[] = $attachment;
	}



	/**
	 * @access private
	 */
	private function create() {
		$attach = false;
		$html = false;
		$text = false;

		if($this->html_part) $html = true;
		if($this->text_part) $text = true;
		if(count($this->attachments) > 0) $attach = true;

		$textonly = false;
		$htmlonly = false;
		if($text == true && $html == false && $attach == false) {
			// only text
			$content_type = 'text/plain; charset="' . strtolower($this->mail_charset) . '"';
			if($this->mail_charset == 'UTF-8') {
				$this->headers['Content-Transfer-Encoding'] = '8bit';
			}
			$textonly = true;
		} elseif($text == true && $html == false && $attach == true) {
			// text and attachment
			$content_type = 'multipart/mixed; boundary="' . $this->mime_boundary . '"';
		} elseif($html == true && $text == true && $attach == false) {
			// html only (or text too)
			$content_type = 'multipart/alternative; boundary="' . $this->mime_boundary . '"';
		} elseif($html == true && $text == false && $attach == false) {
			// html only (or text too)
			$content_type = 'text/html; charset="' . strtolower($this->mail_charset) . '"';
			if($this->mail_charset == 'UTF-8') {
				$this->headers['Content-Transfer-Encoding'] = '8bit';
			}
			$htmlonly = true;
		} elseif($html == true && $attach == true) {
			// html and attachments
			$content_type = 'multipart/mixed; boundary="' . $this->mime_boundary . '"';
		}

		$this->headers['Content-Type'] = $content_type;

		if($textonly == false && $htmlonly == false) {
			$this->body = "This is a multi-part message in MIME format.\n\n";

			if($text) {
				/*$this->body .= "--{$this->mime_boundary}\n" .
                              "Content-Type:text/plain; charset=\"" . strtolower($this->mail_charset) . "\"\n" .
                              "Content-Transfer-Encoding: 7bit\n\n" . $this->text_part . "\n\n";*/
				$this->body .= "--{$this->mime_boundary}\n" .
					"Content-Type:text/plain; charset=\"UTF-8\"\n" .
					"Content-Transfer-Encoding: 8bit\n\n" . $this->text_part . "\n\n";
			}

			if($html) {
				/*$this->body .= "--{$this->mime_boundary}\n" .
                               "Content-Type:text/html; charset=\"" . strtolower($this->mail_charset) . "\"\n" .
                               "Content-Transfer-Encoding: 7bit\n\n" . $this->html_part . "\n\n";*/
				$this->body .= "--{$this->mime_boundary}\n" .
					"Content-Type:text/html; charset=\"UTF-8\"\n" .
					"Content-Transfer-Encoding: 8bit\n\n" . $this->html_part . "\n\n";
			}

			if($attach) {
				foreach($this->attachments as $att) {
					$this->body .= "--{$this->mime_boundary}\n" .
						"Content-Type: " . $att['type'] . "; name=\"" . $att['filename'] . "\"\n" .
						"Content-Transfer-Encoding: base64\n" .
						"Content-Disposition: attachment;\n\n" .
						chunk_split(base64_encode($att['content'])) . "\n\n";
				}
			}
			$this->body .= "--{$this->mime_boundary}--\n";
		} elseif($htmlonly == true) {
			$this->body = $this->html_part;
		} else {
			$this->body = $this->text_part;
		}

		if (isset($this->body)) {
			// Add message ID header
			$message_id = sprintf('<%s.%s@%s>', base_convert(time(), 10, 36), base_convert(rand(), 10, 36), $this->smtp_helo != '' ? $this->smtp_helo : $this->detectHelo());
			$this->headers['Message-ID'] = $message_id;
			return true;
		} else {
			return false;
		}
	}



	/**
	 * Function to sign an email body
	 */
	private function sign() {
		if($this->sign_email == false || $this->sign_key == '' || $this->sign_cert == '') return false;
		if(function_exists('openssl_pkcs7_sign') == false) return false;

		$tmpin = tempnam(sys_get_temp_dir(), 'sign');
		$tmpout = tempnam(sys_get_temp_dir(), 'sign');
		if(!file_exists($tmpin) || !is_writable($tmpin)) return false;

		file_put_contents($tmpin, 'Content-Type: ' . $this->getHeader('Content-Type') . "\n\n" . $this->body);
		$tmpf_key = tempnam(sys_get_temp_dir(), 'sign');
		file_put_contents($tmpf_key, $this->sign_key);
		$tmpf_cert = tempnam(sys_get_temp_dir(), 'sign');
		file_put_contents($tmpf_cert, $this->sign_cert);
		if($this->sign_bundle != '')  {
			$tmpf_bundle = tempnam(sys_get_temp_dir(), 'sign');
			file_put_contents($tmpf_bundle, $this->sign_bundle);
			openssl_pkcs7_sign($tmpin, $tmpout, 'file://' . realpath($tmpf_cert), array('file://' . realpath($tmpf_key), $this->sign_key_pass), array(), PKCS7_DETACHED, realpath($tmpf_bundle));
		} else {
			openssl_pkcs7_sign($tmpin, $tmpout, 'file://' . realpath($tmpf_cert), array('file://' . realpath($tmpf_key), $this->sign_key_pass), array());
		}
		unlink($tmpin);
		unlink($tmpf_cert);
		unlink($tmpf_key);
		if(file_exists($tmpf_bundle)) unlink($tmpf_bundle);

		if(!file_exists($tmpout) || !is_readable($tmpout)) return false;
		$this->body = file_get_contents($tmpout);
		unlink($tmpout);

		unset($this->headers['Content-Type']);
		unset($this->headers['MIME-Version']);

		$this->_is_signed = true;
	}

	private function _char_to_hex($matches) {
		return '=' . strtoupper(dechex(ord($matches[1])));
	}



	/**
	 * Function to encode a header if necessary
	 * according to RFC2047
	 * @access private
	 */
	private function _encodeHeader($input, $charset = 'ISO-8859-1') {
		preg_match_all('/(\s?\w*[\x80-\xFF]+\w*\s?)/', $input, $matches);
		foreach ($matches[1] as $value) {
			$replacement = preg_replace_callback('/([\x20\x80-\xFF])/', array($this, '_char_to_hex'), $value);
			$input = str_replace($value, '=?' . $charset . '?Q?' . $replacement . '?=', $input);
		}

		return $input;
	}



	/**
	 * Function to encode the subject if necessary
	 * according to RFC2047
	 * @access private
	 */
	private function _encodeSubject($input, $charset = 'ISO-8859-1') {
		if(preg_match('/(?:[\xC2-\xDF][\x80-\xBF]|\xE0[\xA0-\xBF][\x80-\xBF]|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}|\xED[\x80-\x9F][\x80-\xBF]|\xF0[\x90-\xBF][\x80-\xBF]{2}|[\xF1-\xF3][\x80-\xBF]{3}|\xF4[\x80-\x8F][\x80-\xBF]{2})/s', $input)) {
			// needs encoding
			if(function_exists('imap_8bit')) {
				$input = "=?utf-8?Q?" . str_replace("?","=3F", imap_8bit($input)) . "?=";
			} else {
				$input = '=?utf-8?B?' . base64_encode($input) . '?=';

		return $input;
	}



	/**
	 * @access private
	 */
	private function _smtp_login() {
		$this->_smtp_conn = fsockopen(($this->smtp_crypt == 'ssl' ? 'tls://' : '') . $this->smtp_host, $this->smtp_port, $errno, $errstr, 30);
		$response = fgets($this->_smtp_conn, 515);
		if(empty($this->_smtp_conn)) return false;

		//Say Hello to SMTP
		if($this->smtp_helo == '') $this->detectHelo();
		fputs($this->_smtp_conn, 'HELO ' . $this->smtp_helo . $this->_crlf);
		$response = fgets($this->_smtp_conn, 515);

		// ENCRYPTED?
		if($this->smtp_crypt == 'tls') {
			fputs($this->_smtp_conn, 'STARTTLS' . $this->_crlf);
			fgets($this->_smtp_conn, 515);
			
			stream_context_set_option($this->_smtp_conn, 'ssl', 'verify_host', false);
			stream_context_set_option($this->_smtp_conn, 'ssl', 'verify_peer', false);
			stream_context_set_option($this->_smtp_conn, 'ssl', 'allow_self_signed', true);
			stream_socket_enable_crypto($this->_smtp_conn, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
		}

		//AUTH LOGIN
		fputs($this->_smtp_conn, 'AUTH LOGIN' . $this->_crlf);
		$response = fgets($this->_smtp_conn, 515);

		//Send username
		fputs($this->_smtp_conn, base64_encode($this->smtp_user) . $this->_crlf);
		$response = fgets($this->_smtp_conn, 515);

		//Send password
		fputs($this->_smtp_conn, base64_encode($this->smtp_pass) . $this->_crlf);
		$response = fgets($this->_smtp_conn, 515);

		$this->_logged_in = true;
		return true;
	}



	/**
	 * @access private
	 */
	private function _smtp_close() {
		$this->_logged_in = false;

		if(empty($this->_smtp_conn)) {
			return false;
		}

		fputs($this->_smtp_conn, 'QUIT' . $this->_crlf);
		$response = @fgets($this->_smtp_conn, 515);
		return true;
	}

	private function _extract_names($data) {
		$senders = array();

		$data = stripslashes(preg_replace("'(\t|\r|\n)'", '', $data));

		if(trim($data) == '') return $senders;

		$armail = array();
		$counter = 0;  $inthechar = 0;
		$chartosplit = ',;'; $protectchar = '"'; $temp = '';
		$closed = 1;

		for($i = 0; $i < strlen($data); $i++) {
			$thischar = $data[$i];
			if($thischar == '<' && $closed) $closed = 0;
			if($thischar == '>' && !$closed) $closed = 1;
			if($thischar == $protectchar) $inthechar = ($inthechar) ? 0 : 1;
			if((strpos($chartosplit, $thischar) !== false) && !$inthechar && $closed) {
				$armail[] = $temp;
				$temp = '';
			} else {
				$temp .= $thischar;
			}
		}

		if(trim($temp) != '') {
			$armail[] = trim($temp);
			unset($temp);
		}

		foreach($armail as $thisPart) {
			$thisPart = trim(preg_replace('/^"(.*)"$/i', '$1', trim($thisPart)));
			if($thisPart != '') {
				$email = '';
				$name = '';
				if(preg_match('/(.*)<(.*)>/i', $thisPart, $matches)) {
					$email = trim($matches[2]);
					$name = trim($matches[1]);
				} else {
					if(preg_match('/([-a-z0-9_$+.]+@[-a-z0-9_.]+[-a-z0-9_]+)((.*))/i', $thisPart, $matches)) {
						$email = $matches[1];
						$name = $matches[2];
					} else {
						$email = $thisPart;
					}
				}

				$email = preg_replace('/<(.*)\\>/', '$1', $email);
				$name = preg_replace('/"(.*)"/', '$1', trim($name));
				$name = preg_replace('/\((.*)\)/', '$1', $name);

				if($name == '') $name = $email;
				if($email == '') $email = $name;
				$senders[] = array(
					'name' => $name,
					'mail' => $email
				);
				unset($name);
				unset($email);
			}
		}
		unset($armail);
		unset($thisPart);

		return $senders;
	}

	/**
	 * Send the mail to one or more recipients
	 *
	 * The recipients can be either a string (1 recipient email without name) or an associative array of recipients with names as keys and email addresses as values.
	 *
	 * @access public
	 * @param mixed $recipients one email address or array of recipients with names as keys and email addresses as values
	 */
	public function send($recipients) {
		if(!is_array($recipients)) $recipients = array($recipients);

		if($this->use_smtp == true) $this->_crlf = "\r\n";
		else $this->_crlf = "\n";

		$this->create();
		if($this->sign_email == true) $this->sign();

		$subject = '';
		if (!empty($this->headers['Subject'])) {
			//$subject = $this->_encodeHeader($this->headers['Subject'], $this->mail_charset);
			$subject = $this->headers['Subject'];

			//$enc_subject = $this->_encodeHeader($subject, $this->mail_charset);
			$enc_subject = $this->_encodeSubject($subject, $this->mail_charset);
			unset($this->headers['Subject']);
		}

		if($this->notification == true) $this->setHeader('Disposition-Notification-To', $this->getHeader('From'));

		unset($this->headers['To']); // always reset the To header to prevent from sending to multiple users at once
		$this->headers['Date'] = date('r'); //date('D, d M Y H:i:s O');

		// Get flat representation of headers
		foreach ($this->headers as $name => $value) {
			if(strtolower($name) == 'to' || strtolower($name) == 'cc' || strtolower($name) == 'bcc') continue; // never add the To header
			$headers[] = $name . ': ' . $this->_encodeHeader($value, $this->mail_charset);
		}

		if($this->use_smtp == true) {
			$bcc_cc_sent = false;
			foreach($recipients as $recipname => $recip) {
				// Build mail headers, content etc.

				$m_recipients = array();
				$m_mail_content = '';

				$recipname = trim(str_replace('"', '', $recipname));
				$recip = $this->_encodeHeader($recip, $this->mail_charset);
				$recipname = $this->_encodeHeader($recipname, $this->mail_charset);

				//Email From
				$m_from = $this->_mail_sender;

				if($bcc_cc_sent == false) {
					$add_recips = array();
					if($this->getHeader('Cc') != '') $add_recips = array_merge($add_recips, $this->_extract_names($this->getHeader('Cc')));
					if($this->getHeader('Bcc') != '') $add_recips = array_merge($add_recips, $this->_extract_names($this->getHeader('Bcc')));
					foreach($add_recips as $add_recip) {
						if(!$add_recip['mail']) continue;
						$m_recipients[] = $this->_encodeHeader($add_recip['mail'], $this->mail_charset);
					}
					unset($add_recips);
					$bcc_cc_sent = true;
				}

				//Construct Headers
				if($recipname && !is_numeric($recipname)) $this->setHeader('To', $recipname . ' <' . $recip . '>');
				else $this->setHeader('To', $recip);

				$mail_content = 'Subject: ' . $enc_subject . $this->_crlf;
				$mail_content .= 'To: ' . $this->getHeader('To') . $this->_crlf;
				if($this->getHeader('Cc') != '') $mail_content .= 'Cc: ' . $this->_encodeHeader($this->getHeader('Cc'), $this->mail_charset) . $this->_crlf;
				$mail_content .= implode($this->_crlf, $headers) . $this->_crlf . ($this->_is_signed == false ? $this->_crlf : '') . $this->body;

				$m_mail_content = $mail_content;

				// Attempt SMTP login:

				if(!$this->_logged_in || !$this->_smtp_conn) {
					$result = $this->_smtp_login();
				}

				if($this->_sent_mails >= $this->smtp_max_mails) {
					// close connection to smtp and reconnect
					$this->_sent_mails = 0;
					$this->_smtp_close();
					$result = $this->_smtp_login();
				}
				$this->_sent_mails += 1;

				// Send mail or queue it

				if ($result) {
					$this->send_smtp($m_from, $m_recipients, $m_mail_content);
				} else {
					$this->add_to_queue($m_from, $m_recipients, $m_mail_content);
				}

				// hopefully message was correctly sent or queued now

				$result = true;
			}
		} else {
			if($this->getHeader('Bcc') != '') $headers[] = 'Bcc: ' . $this->_encodeHeader($this->getHeader('Bcc'), $this->mail_charset);
			if($this->getHeader('Cc') != '') $headers[] = 'Cc: ' . $this->_encodeHeader($this->getHeader('Cc'), $this->mail_charset);
			$rec_string = '';
			foreach($recipients as $recipname => $recip) {
				$recipname = trim(str_replace('"', '', $recipname));

				if($rec_string != '') $rec_string .= ', ';
				if($recipname && !is_numeric($recipname)) $rec_string .= $recipname . '<' . $recip . '>';
				else $rec_string .= $recip;
			}
			$to = $this->_encodeHeader($rec_string, $this->mail_charset);
			//$result = mail($to, $subject, $this->body, implode($this->_crlf, $headers));
			$result = mail($to, $enc_subject, $this->body, implode($this->_crlf, $headers));
		}

		// Reset the subject in case mail is resent
		if ($subject !== '') {
			$this->headers['Subject'] = $subject;
		}

		// Return
		return $result;
	}

	/**
	 * Send all mails in queue (usually called from cron)
	 */
	public function send_queue() {
		global $app;

		$mails = $app->db->queryAllRecords('SELECT * FROM sys_mailqueue');

		if (is_array($mails)) {
			foreach ($mails as $mail) {
				// Open SMTP connections if not open:

				if(!$this->_logged_in || !$this->_smtp_conn) {
					$result = $this->_smtp_login();
				}

				if($this->_sent_mails >= $this->smtp_max_mails) {
					// close connection to smtp and reconnect
					$this->_sent_mails = 0;
					$this->_smtp_close();
					$result = $this->_smtp_login();
				}
				$this->_sent_mails += 1;

				if (!$result) {
					return false;
				}

				// Send mail:

				$id = $mail['id'];
				$from = $mail['from_address'];
				$recipients = explode("\n", $mail['recipients']);
				$mail_content = $mail['mail_content'];

				$this->send_smtp($from, $recipients, $mail_content);

				// Delete from queue:

				$app->db->query('DELETE FROM sys_mailqueue WHERE id = ?', $id);
			}
		}
	}

	/**
         * Send mail via SMTP
         */
	private function send_smtp($from, $recipients, $mail_content) {
		// from:

		fputs($this->_smtp_conn, 'MAIL FROM: <' . $from . '>' . $this->_crlf);
		$response = fgets($this->_smtp_conn, 515);

		// recipients (To, Cc or Bcc):

		foreach ($recipients as $recipient) {
			fputs($this->_smtp_conn, 'RCPT TO: <' . $recipient . '>' . $this->_crlf);
			$response = fgets($this->_smtp_conn, 515);
		}

		// mail content:
		fputs($this->_smtp_conn, 'DATA' . $this->_crlf);
		$response = fgets($this->_smtp_conn, 515);

		fputs($this->_smtp_conn, $mail_content . $this->_crlf . '.' . $this->_crlf);
		$response = fgets($this->_smtp_conn, 515);

		// hopefully message was correctly sent now
		$result = true;

		return $result;
        }

	/**
         * Add mail to queue for sending later
         */
	private function add_to_queue($from, $recipients, $mail_content) {
		global $app;
		$app->db->query('INSERT INTO `sys_mailqueue` (`from_address`, `recipients`, `mail_content`) VALUES (?,?,?)', $from, implode("\n", $recipients), $mail_content);

	/**
	 * Close mail connections
	 *
	 * This closes an open smtp connection so you should always call this function in your script if you have finished sending all emails
	 *
	 * @access public
	 */
	public function finish() {
		if($this->use_smtp == true) $this->_smtp_close();

		$rand = md5(microtime());
		$this->mime_boundary = '==Multipart_Boundary_x' . $rand . 'x';

		$this->headers = array();
		$this->attachments = array();
		$this->text_part = '';
		$this->html_part = '';

		$this->headers['MIME-Version'] = '1.0';
		$this->headers['User-Agent'] = $this->user_agent;

		$this->smtp_helo = '';
		$this->smtp_host = '';
		$this->smtp_port = '';
		$this->smtp_user = '';
		$this->smtp_pass = '';
		$this->use_smtp = false;
		$this->smtp_crypt = false;
		$this->mail_charset = 'UTF-8';
		$this->_sent_mails = 0;

		return;
	}

}

?>