#
# Copyright (C) 2002-2004 Satoru Takabayashi <satoru@namazu.org> 
# Copyright (C) 2003-2005 Kouichirou Eto
#     All rights reserved.
#     This is free software with ABSOLUTELY NO WARRANTY.
#
# You can redistribute it and/or modify it under the terms of 
# the GNU General Public License version 2.
#

$LOAD_PATH << "../../lib" unless $LOAD_PATH.include?("../../lib")

module QuickML
  class MailSender
    def initialize (smtp_host, smtp_port, use_xverp = false)
      @smtp_port = smtp_port
      @smtp_host = smtp_host
      @use_xverp = use_xverp
      @xverp_available = false
    end

    def send (message, mail_from, recipients)
      recipients = [recipients] if recipients.kind_of?(String)
      s = TCPSocket.open(@smtp_host, @smtp_port) 
      send_command(s, nil, 220)
      send_command(s, "EHLO #{Socket.gethostname}", 250)
      if @use_xverp and @xverp_available and (not mail_from.empty?)
        send_command(s, "MAIL FROM: <#{mail_from}> XVERP===", 250)
      else
        send_command(s, "MAIL FROM: <#{mail_from}>", 250)
      end
      recipients.each {|recipient|
        send_command(s, "RCPT TO: <#{recipient}>", 250)
      }
      send_command(s, "DATA", 354)
      message.each_line {|line|
        line.sub!(/\r?\n/, "")
        line.sub!(/^\./, "..")
        line << "\r\n"
        s.print(line)
      }
      send_command(s, ".", 250)
      send_command(s, "QUIT", 221)
      s.close
    end

    private

    def send_command (s, command, code)
      s.print(command + "\r\n") if command
      begin
        line = s.gets
        @xverp_available = true if /^250-XVERP/.match(line)
      end while line[3] == ?-

      return_code = line[0,3].to_i
      if return_code == code
        line
      else
        raise "smtp-error: #{command} => #{line}"
      end
    end
  end
end

if $0 == __FILE__
  require "test/unit"
  $debug = true
end

if $debug
  class TestMLMailSender < Test::Unit::TestCase
    def test_all
    end
  end
end
