- 生成邮件相关文件
rails g mailer UserMailer accout_activation password_reset
- 开发环境中的邮件配置
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: "[email protected]"
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
通过调用account_activation(user)
来发送邮件
UserMailer.account_activation(User.first).deliver_now
- view
在发邮件之前,需要先渲染出邮件的内容,邮件有两个模板视图:html和text。与其它的views视力一样,也可以在邮件的视图中使用嵌入式ruby。
app/views/usermailer/account_activation.html.erb
<%= "#{@greeting}, #{@user.name}" %>
Welcome! Click on the link below to activate your account:
<%= 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) %>
- 预览邮件内容
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
只需要复制http://localhost:3000/rails/mailers/user_mailer/account_activation
就可以预览邮件内容了