RubyでCGIスクリプトを作る下準備・Rubyからsendmailを使う

CGIスクリプトからメールを送信出来ると便利そうなので作る。
sendmailのオプションに-tを付けるとTo:、Cc:、Bcc:を解釈するようになる。

#!/usr/local/bin/ruby

#
# Rubyからsendmailを使うデモ
#

SENDMAIL = "/usr/libexec/sendmail/sendmail" # sendmailのパス

def sendmail sm_from, sm_to, sm_cc, sm_bcc, sm_sub, sm_com
  require "kconv"

  sm_sub = sm_sub.tojis
  sm_com = sm_com.tojis

  IO.popen("#{SENDMAIL} -t", "r+") { |io|
    io.print "From: #{sm_from}\n"
    io.print "To: #{sm_to}\n"
    io.print "Cc: #{sm_cc}\n" if sm_cc != nil
    io.print "Bcc: #{sm_bcc}\n" if sm_bcc != nil
    io.print "Subject: #{sm_sub}\n"
    io.print "MIME-Version: 1.0\n"
    io.print "Content-Type: text/plain; charset=\"ISO-2022-JP\"\n"
    io.print "Content-Transfer-Encoding: 7bit\n"
    io.print "\n"
    io.print "#{sm_com}\n"
  }
end

# from@hoge:差出人、to@hoge:宛先
sendmail("from@hoge", "to@hoge", nil, nil, "テストメール", "テスト")