package Mail;
use strict;

use System;
use Net::SMTP;

sub sendmail_server {
  my($class) = @_;
  if (System->get_testMode()) {
     return "localhost";
  } else {
     my $renv = System->get_renv();
     return $renv->{sendmail_server} || "localhost";
  }
}

sub mail {
  my($class, $to, $from, $subject, $data, $TO, $arg) = @_;

  my $renv = System->get_renv();
  my $sendmailServer = $arg->{sendmail_server} || $class->sendmail_server(); 
  
  my $ef = $renv->{email_from};
  if ($ef) {
    if ($ef =~ /\@/) {
       $from = $ef;
    } elsif ($ef !~ /\@/) {
       $from .= "\@$ef";
    }
  }

  $TO = 30 if (!$TO);
  my @parse = split(/\:/, $sendmailServer);
  my $port = $parse[1] || 25;

  my $smtp = Net::SMTP->new($sendmailServer, Timeout => $TO);
  if (!$smtp) {
     Debug->print2("Cannot create SMTP handle");
     return "Cannot create SMTP handle to $sendmailServer: $!";
  }
  
  # use utf-8 to support all locales
  # Xuefeng Yao 2/17/2005
  my $charset = "utf-8";

  #if ($arg->{locale}) {
  #  $charset = Net::Util->getCharSet($arg->{locale});
  #}
  my $ct = "Content-Type: text/plain; charset=$charset";

  my $text;
  $text = "From: $from\nTo: $to\n$ct\nSubject: $subject\n\n$data";

  if ($smtp->mail($from)) {
     if ($smtp->to($to)) {
       $smtp->data();
       $smtp->datasend($text);
       $smtp->dataend;
       $smtp->quit;
       return undef;
     } else {
       my $err = $smtp->message();
       $smtp->quit;
       return $err;
     }
  } else {
     my $err = $smtp->message();
     $smtp->quit;
     return $err;
  }
}

sub mailData {
  my($class, $to, $data, $TO, $arg) = @_;

  my $renv = System->get_renv();
  my $sendmailServer = $arg->{sendmail_server} || $class->sendmail_server();

  my $email_from     = $renv->{email_from};
  if ($email_from) {
    my $ix = index($email_from, "\@");
    $email_from = substr($email_from, $ix+1) if ($ix > 0);
  }

  $TO = 30 if (!$TO);

  my $smtp = Net::SMTP->new($sendmailServer, Timeout => $TO, Hello => $email_from );
  if (!$smtp) {
     Debug->print2("Cannot create SMTP handle");
     return "SMTP error";
  }

  if ($smtp->mail($email_from) && $smtp->to($to)) {
     $smtp->data();
     $smtp->datasend($data);
     $smtp->dataend;
     $smtp->quit;
     return undef;
  } else {
     my $err = $smtp->message();
     $smtp->quit;
     return $err;
  }
}


1;
