#
# sendmail.rb
#

require 'tmail'
require 'net/smtp'
require 'nkf'


if ARGV.empty? or /--help|-h/ === ARGV[0] then
  $stderr.puts 'send mail script using local SMTP server'
  $stderr.puts 'To: and From: header must be correctly set'
  $stderr.puts 'usage:  ruby sendmail.rb <mailfile>'
  exit 1
end


#
# create mail object
#
mail = TMail::Mail.load_from( ARGV[0] )

#
# get from-address and to-addresses
#
to = mail.destinations
unless fr = mail.from_address then
  fr = ENV['USER']
  if dom = ENV['HOSTNAME'] || ENV['HOST'] then
    fr << '@' << dom
  end
end

#
# setup header fields
#
mail.delete 'bcc'
mail.delete 'received'
mail.date = Time.now
mail.delete_if {|n,v| v.empty? }
mail.mime_version = '1.0'

#
# setup mail body
#
textp = false
textp = (/text/i === mail.main_type(''))
body = mail.body
textp = (NKF.guess( body ) != NKF::BINARY)

if textp then
  mail.body = NKF.nkf( '-j -m0', body )
  mail.set_content_type( 'text', 'plain', {'charset' => 'iso-2022-jp'} )
  mail.encoding = '7bit'
else
  mail.body = [body].pack('m')
  mail.set_content_type( 'application', 'octet-stream' )
  mail.encoding = 'Base64'
end

#
# send mail
#
$stderr.puts "sending mail (file #{ARGV[0]}) to #{to.join(', ')}"
smtp = Net::SMTP.new
smtp.set_pipe $stderr if $DEBUG
smtp.start do
  str = mail.encoded
  $stderr.print str if $DEBUG
  smtp.sendmail str, fr, to
end
