Railsでサーバーを公開しようと思うと高価なレンタルサーバーか自宅サーバーになると思うのですが、自宅サーバーはできるだけ手っ取り早く完成させたい物です。
ActionMailerを使おうにも自前のメールサーバーの設定はめんどくさいので、Gmailを使おうと思い立ったのは良いのですが、Gmailって外部からの接続はSSLになっており、ActionMailerはそれに対応してないのでどうしようかなぁと思っていたところ、同じようなことを考える人がいました。
http://www.prestonlee.com/archives/63
http://21croissants.blogspot.com/2007/08/configuring-rails-to-use-gmails-smtp.html
lib/smtp_tls.rbとかに
[ruby]
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, authtype if user or secret
sock = timeout(@open_timeout) { TCPSocket.open(@address, @port) }
@socket = Net::InternetMessageIO.new(sock)
@socket.read_timeout = 60 #@read_timeout
check_response(critical { recv_response() })
do_helo(helodomain)
if starttls
raise ‘openssl library not installed’ unless defined?(OpenSSL)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.sync_close = true
ssl.connect
@socket = Net::InternetMessageIO.new(ssl)
@socket.read_timeout = 60 #@read_timeout
do_helo(helodomain)
end
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’) rescue return false
return true
end
def quit
begin
getok(‘QUIT’)
rescue EOFError, OpenSSL::SSL::SSLError
end
end
end
[/ruby]
を作っておいて
config/environment.rbに
[ruby]
require “smtp_tls”
ActionMailer::Base.smtp_settings = {
:address => “smtp.gmail.com”,
:port => 587,
:domain => “www.hogehoge.com”,
:authentication => :login,
:user_name => “********”,
:password => “********”
}
[/ruby]
を追加すればあとはActionMailerから同じように使えます。
p.s. preタグを今日はじめて知った。
p.s.2 ザリガニが見ていた…。さんからリンクもらったので見返してみたらtypoがあったので修正
hey it’s nice helps us in development mode.
hyfgtfrsde