2009-02-11

RailsのActionMailerによるメール送信

[目的]
Gmailのsmtpを利用して、メールを送信する。

[環境]
Rails 2.2.2
ActionMailer 2.2.2
Ruby 1.8.7
ubuntu 8.04

[作業方法]
(1)TLSライブラリのインストール(gmailのsmtp認証用)
 ◆フォルダ
vendor/plugins/action_mailer_tls
vendor/plugins/action_mailer_tls/lib

◆ファイル
  vendor/plugins/action_mailer_tls/init.rb

  init.rbの中身

require_dependency 'smtp_tls'


  vendor/plugins/action_mailer_tls/lib/smtp_tls.rb

smtp_tls.rbの中身

require "openssl"
require "net/smtp"

Net::SMTP.class_eval do
private
def do_start(helodomain, user, secret, authtype)
raise IOError, 'SMTP session already started' if @started
check_auth_args user, secret if user or secret

sock = timeout(@open_timeout) { TCPSocket.open(@address, @port) }
@socket = Net::InternetMessageIO.new(sock)
@socket.read_timeout = 60 #@read_timeout
@socket.debug_output = STDERR #@debug_output

check_response(critical { recv_response() })
do_helo(helodomain)

raise 'openssl library not installed' unless defined?(OpenSSL)
starttls
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.sync_close = true
ssl.connect
@socket = Net::InternetMessageIO.new(ssl)
@socket.read_timeout = 60 #@read_timeout
@socket.debug_output = STDERR #@debug_output
do_helo(helodomain)

authenticate user, secret, authtype if user
@started = true
ensure
unless @started
# authentication failed, cancel connection.
@socket.close if not @started and @socket and not @socket.closed?
@socket = nil
end
end

def do_helo(helodomain)
begin
if @esmtp
ehlo helodomain
else
helo helodomain
end
rescue Net::ProtocolError
if @esmtp
@esmtp = false
@error_occured = false
retry
end
raise
end
end

def starttls
getok('STARTTLS')
end

def quit
begin
getok('QUIT')
rescue EOFError
end
end
end


(2)config/environments/development.rbにSMTPの設定追加

delevopment.rbの最後に追記

config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => 'smtp.gmail.com',
:port => 587,
:authentication => :plain,
:user_name => 'xxxxxx@gmail.com',
:password => '******'
}


(3)ActionMailer modelの生成

>script/generate mailer NotifyMailer result


(4)NotifyMailer modelの修正

def result(sent_at = Time.now)
subject 'NotifyMailer#result'
recipients 'xxxx@xxxxx.xxxx' #とりあえずここ修正
from 'xxxx@xxxxxx.xxx' #とりあえずここ修正
sent_on sent_at
body :greeting => 'Hi,'
end

(5)○○controllerにアクションの記述


def mail
mail = NotifyMailer.create_result()
NotifyMailer.deliver(mail)
end

(6)送信テスト
http://localhost:3000/xxx/mailにて送信出来るか確認。


[参考]
Ruby on Rails/ActionMailerでTLSを使ったメール送信

0 件のコメント: