package WebMailer;

use vars qw(@ISA @EXPORT);

use Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(send_mail);

require "jcode.pl";
# require "mimew.pl"; # MIME encode 用ライブラリ
	     
#---------------------------------------------------------------------------
#
#

# sendmailのパス設定
my $sendmail_path = '/usr/lib/sendmail';

# メールの出力先
my $mail_output = "| $sendmail_path -t";

#
my $maillog_dir = "./logs/";

#
my $mail_logfile = $maillog_dir."maillog";

#
my $send_mail_hook = 1; # 0 ... 送信内容をファイルに記録しない
                        # 1 ... 送信内容をファイルに記録する
#
my $send_mail_flag = 1; # 0 ... 送信しない, 1 ... 送信する

#
my $mailer_name = "";

sub send_mail {
    my ($fields) = @_;
    my $to = $fields->{'to'};
#    local $tmp_subject = $fields->{'subject'};
#    &jcode::convert(*tmp_subject,'jis');   # E-mail は 当然 JIS
#    my $subject = &MIME::mimeencode($tmp_subject);
#    my $subject = &MIME::mimeencode($fields->{'subject'});
    my $subject = $fields->{'subject'};
    my $body = $fields->{'body'};
    my $from = $fields->{'from'};
    my $cc = $fields->{'cc'};
    my $bcc = $fields->{'bcc'};
    my $date = &get_date_field();
    my $nolog = $fields->{'nolog'} ? 0 : 1;

    local $message = "";
    $message .= &smtp_header();
    $message .= "From: $from\n";
    $message .= "To: $to\n";
    $message .= "Cc: $cc\n" if ($cc);
    $message .= "Bcc: $bcc\n" if ($bcc);
    $message .= "Subject: $subject\n";
    $message .= "Date: $date\n";    
    $message .= "\n";
    $message .= "$body";

    &jcode::convert(*message,'jis');   # E-mail は 当然 JIS

    &send_mail_hook($message) if ($send_mail_hook && $nolog);
    return unless ($send_mail_flag);

    open(MAIL,"$mail_output");
    print MAIL $message;
    close(MAIL);
}

sub send_mail_hook {
    my ($message) = @_;
    my $date = &get_current_date_string();
	
    open (OUT, ">> $mail_logfile") or die "Open Error ($mail_logfile) in write";
    flock(OUT, 2);
    print OUT "===== ($date) =====\n";
    print OUT $message;
    close(OUT);
    chmod 0666, $mail_logfile;
}

sub smtp_header {
    my $html = "";
    $html .= qq|Content-Type: Text/Plain; charset=iso-2022-jp\n|;
    $html .= qq|Content-Transfer-Encoding: 7bit\n|;
    return ($html);
}

sub get_current_date_string {
    my($sec, $min, $hour, $day, $mon, $year) = localtime(time);
    $year += 1900;
    $mon++;
    sprintf("%04d%02d%02d%02d%02d%02d", $year, $mon, $day, $hour, $min, $sec);
}

sub get_date_field {
    my ($sec, $min, $hour, $day, $mon, $year, $wday) = localtime(time);
    $year += 1900;
    $mon++;
    my $weekday = ('Sun','Mon','Tue','Wed','Thu','Fri','Sat')[$wday];
    my $month = ('---', 'Jan','Feb','Mar','Apr','May','Jun',
		 'Jul','Aug','Sep','Oct','Nov','Dec')[$mon];
    return(sprintf("%s, %02d %s %04d %02d:%02d:%02d +0900",
		   $weekday, $day, $month, $year, $hour, $min, $sec));
}

1;
