ActionMailerのメールをgmailのsmtpサーバを使って送信

ぐぐったらいろいろでたのですが、一点だけ注意することがある。

lib/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

以下の設定をconfig/environment.rbに書き加える
その際にrequire "action_mailer"で再ロードしないと以下のようなエラーが発
生する。
uninitialized constant ActionMailer (NameError)

なんでやねん!

  require "smtp_tls"
  require "action_mailer" # <- これがないとなぜかserver起動とgenerateでこける

  ActionMailer::Base.delivery_method = :smtp
  ActionMailer::Base.smtp_settings = {
    :address => "smtp.gmail.com",
    :port => 587,
    :authentication => :plain,
    :user_name => "user",
    :password => 'pass'}

またぐぐったらこんなようなことが買いてあった
ちょっと面倒なので全部は読んでないけどモジュールのロード関係?

ActionMailerでGmailの続き – zorioの日記

微妙によく解らんけど解決したのでとりあえずよしとする。

Tags: , , , , ,

This entry was posted on 土曜日, 7月 18th, 2009 at 7:13 PM and is filed under ruby, 日記. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply