Rails宝典之第六十一式: Sending Email

这是一个使用Rails发送Email的简单指南

1,修改config/environments/development.rb,配置smtp
config.action_mailer.raise_delivery_errors = true

# set delivery method to :smtp, :sendmail or :test
config.action_mailer.delivery_method = :smtp

# these options are only needed if you choose smtp delivery
config.action_mailer.smtp_settings = {
  :address           => 'smtp.example.com',
  :port              => 25,
  :domain            => 'www.example.com',
  :authentication    => :login,
  :user_name         => 'www',
  :password          => 'secret'
}

在production环境下将上述配置移至environment.rb

2,生成mailer
ruby script/generate mailer user_mailer


3,修改UserMailer
class UserMailer < ActionMailer::Base
  def registration_confirmation(user)
    recipients  user.email
    from        "[email protected]"
    subject     "Thank you for Registering"
    body        :user => user
  end
end


4,修改Email模板views/user_mailer/registration_confirmation.rhtml
Hi <%= @user.name %>,
...


5,在UsersController中使用UserMailer
class UsersController < ApplicationController
  def create
    @user = User.new(params[:user])
    if @user.save
      UserMailer.deliver_registration_confirmation(@user)
      flash[:notice] = "Successfully registered"
      redirect_to user_path(@user)
    else
      render :action => 'new'
    end
  end

# ...
end

你可能感兴趣的:(Flash,Ruby,Rails)