<?php

// Load PHP PEAR Mail and Mail_mime libs
require_once($php_mail_path);
require_once($php_mail_mime_path);

function send_mail($from, $to, $subject, $msg, $headers=array(), $attachments=array(),
                   $crlf="\r\n") {
  global $mail_send_method, $mail_headers, $mail_send_params, $mail_catch_all, $mail_sender;
  $mail_obj = Mail::factory($mail_send_method, $mail_send_params);

  if ($mail_catch_all) {
      $msg .= sprintf(
        _("\n\n\nMail initialy intended for %s."),
        (is_array($to)?implode(',', $to):$to));
      $to = $mail_catch_all;
  }

  if(is_array($mail_headers)) {
    $headers = array_merge($headers,$mail_headers);
  }
  $headers["To"] = $to;

  $to = array (
    'To' => $to
  );

  foreach(array_keys($headers) as $header) {
    if(strtoupper($header) == 'BCC') {
      $to['BCC'] = $headers[$header];
    }
    elseif(strtoupper($header) == 'CC') {
      $to['CC'] = $headers[$header];
    }
  }

  $mime = new Mail_mime(
    array(
      'eol' => $crlf,
      'text_charset' => 'utf8',
      'head_charset' => 'utf8',
    )
  );
  if ($from) {
    $mime->setFrom($from);
  }
  elseif ($mail_sender) {
    $mime->setFrom($mail_sender);
  }

  if ($subject) {
    $mime->setSubject($subject);
  }
  $mime->setTXTBody($msg);


  if (is_array($attachments) && !empty($attachments)) {
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    foreach ($attachments as $file => $filename) {
      $mime->addAttachment($file, $finfo->file($file), $filename);
    }
  }

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

  $ret = $mail_obj -> send($to,$headers,$body);

  if ($ret instanceof PEAR_Error) {
    logging('ERROR',"Error sending email to $to : ".$ret -> getMessage());
    return False;
  }
  return true;
}