1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
|
#
# sendmail.rb
#
require 'tmail'
require 'net/smtp'
require 'nkf'
if ARGV.empty? or /\A--?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( ARGV[0] )
#
# get from-address and to-addresses
#
to = mail.destinations
from = mail.from_address
unless from then
from = ENV['USER']
if domain = (Socket.gethostname || ENV['HOSTNAME'] || ENV['HOST']) then
from += '@' + domain
end
end
$stderr.printf "%s -> %s\n", from, to.join(',')
#
# 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
#
body = mail.body
if NKF.guess(body) != NKF::BINARY 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_debug_output $stderr if $DEBUG
smtp.start {
str = mail.encoded
$stderr.print str if $DEBUG
smtp.sendmail str, from, to
}
|