メールの送信
はじめに
掲示板の書き込み通知や、何かの登録確認用などにメールを送る時に簡単に送れるようなクラスを作りましょう。
簡単な通知のみに使用するので、From, To, Cc, Bcc は user@domain をカンマで繋げたものだけで、日本語とかは考えてません。
sendmail.rb
class Sendmail
require "nkf"
SENDMAIL = "/usr/lib/sendmail"
def initialize( from, subject, body )
@from = from
@subject = subject
@body = body
end
def encode( str )
require "base64"
"=?ISO-2022-JP?B?" + b64encode( NKF.nkf( "-j", str ) ).chomp + "?="
end
def sendto( to, cc = nil, bcc = nil )
text = "From: #{@from}\n"
text += "To: #{to}\n"
text += "Cc: #{cc}\n" if cc
text += "Bcc: #{bcc}\n" if bcc
text += "Subject: #{encode( @subject )}\n"
text += "MIME-Version: 1.0\n"
text += "Content-Type: text/plain; charset=\"ISO-2022-JP\"\n"
text += "Content-Transfer-Encoding: 7bit\n"
text += "\n"
text += NKF.nkf( "-j", @body ) + "\n"
to = to.split( /,\s*/ )
to += cc.split( /,\s*/ ) if cc
to += bcc.split( /,\s*/ ) if bcc
[@from,*to].each do |t|
raise "Mail address error -> #{t}" if t !~ /^[0-9A-Za-z_\-\._]+@[0-9A-Za-z_\-\._]+$/
end
require "net/smtp"
Net::SMTP.start( 'localhost' ) do |smtp|
smtp.send_mail text, @from, to
end
end
end
require "nkf"
SENDMAIL = "/usr/lib/sendmail"
def initialize( from, subject, body )
@from = from
@subject = subject
@body = body
end
def encode( str )
require "base64"
"=?ISO-2022-JP?B?" + b64encode( NKF.nkf( "-j", str ) ).chomp + "?="
end
def sendto( to, cc = nil, bcc = nil )
text = "From: #{@from}\n"
text += "To: #{to}\n"
text += "Cc: #{cc}\n" if cc
text += "Bcc: #{bcc}\n" if bcc
text += "Subject: #{encode( @subject )}\n"
text += "MIME-Version: 1.0\n"
text += "Content-Type: text/plain; charset=\"ISO-2022-JP\"\n"
text += "Content-Transfer-Encoding: 7bit\n"
text += "\n"
text += NKF.nkf( "-j", @body ) + "\n"
to = to.split( /,\s*/ )
to += cc.split( /,\s*/ ) if cc
to += bcc.split( /,\s*/ ) if bcc
[@from,*to].each do |t|
raise "Mail address error -> #{t}" if t !~ /^[0-9A-Za-z_\-\._]+@[0-9A-Za-z_\-\._]+$/
end
require "net/smtp"
Net::SMTP.start( 'localhost' ) do |smtp|
smtp.send_mail text, @from, to
end
end
end
使いかた
sendmail = Sendmail.new( "tasuku@linux-life.net", "テスト", "テストメールです。" )
sendmail.sendto( "tasuku@linux-life.net" )
sendmail.sendto( "tasuku@linux-life.net" )
終わりに
最低限のことしか実装していないので、気を付けて使ってください。