- 生成郵件相關(guān)文件
rails g mailer UserMailer accout_activation password_reset
- 開發(fā)環(huán)境中的郵件配置
config/environments/development.rb
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :test
host = 'localhost:3000'
config.action_mailer.default_url_options = {host: host}
- controller
app/mailers/application_mailer.rb
class ApplicationMailer < ActionMailer::Base
default from: "from@example.com"
layout 'mailer'
end
app/mailers/user_mailer.rb
class UserMailer < ApplicationMailer
# Subject can be set in your I18n file at config/locales/en.yml
# with the following lookup:
#
# en.user_mailer.account_activation.subject
#
def account_activation user
@greeting = "Hi"
@user = user
mail to: user.email, subject: "Account activation"
end
# Subject can be set in your I18n file at config/locales/en.yml
# with the following lookup:
#
# en.user_mailer.password_reset.subject
#
def password_reset user
@greeting = "Hi"
@user = user
mail to: user.email, subject: "Password reset"
end
end
這樣就可以在controllers
/models
/views
通過調(diào)用account_activation(user)
來發(fā)送郵件
UserMailer.account_activation(User.first).deliver_now
- view
在發(fā)郵件之前,需要先渲染出郵件的內(nèi)容碗誉,郵件有兩個模板視圖:html和text。與其它的views視力一樣弄跌,也可以在郵件的視圖中使用嵌入式ruby尝苇。
app/views/usermailer/account_activation.html.erb
<p>
<%= "#{@greeting}, #{@user.name}" %>
Welcome! Click on the link below to activate your account:
</p>
<%= link_to "Activate", edit_account_activation_url(@user.activation_token, email: @user.email) %>
or copy the link below
<%= edit_account_activation_url(@user.activation_token, email: @user.email) %>
app/views/usermailer/account_activation.text.erb
<%="#{@greeting}, #{@user.name}" %>
Welcome! Click on the link below to activate your account:
<%= edit_account_activation_url(@user.activation_token, email: @user.email) %>
- 預(yù)覽郵件內(nèi)容
test/mailer/preview/user_mailer_preview.rb
# Preview all emails at http://localhost:3000/rails/mailers/user_mailer
class UserMailerPreview < ActionMailer::Preview
# Preview this email at http://localhost:3000/rails/mailers/user_mailer/account_activation
def account_activation
user = User.first
user.activation_token = User.new_token
UserMailer.account_activation(user)
end
# Preview this email at http://localhost:3000/rails/mailers/user_mailer/password_reset
def password_reset
user = User.first
user.password_reset_token = User.new_token
UserMailer.password_reset(user)
end
end
注意其中的兩行:
# Preview this email at http://localhost:3000/rails/mailers/user_mailer/account_activation
# Preview this email at http://localhost:3000/rails/mailers/user_mailer/password_reset
只需要復(fù)制http://localhost:3000/rails/mailers/user_mailer/account_activation
就可以預(yù)覽郵件內(nèi)容了