ActionMailer发送邮件
Posted mr-ranx
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ActionMailer发送邮件相关的知识,希望对你有一定的参考价值。
首先生成一个User邮件程序,
rails generate mailer UserMailer account_activation password_reset
email_activation password_reset分别是激活邮箱和重置密码的方法,运行命令后会自动在mailers生成一个user_mailer.rb文件,在ApplicationMailer中修改默认发送地址
default from: "from@example.com"
在user_mailer.rb文件中,有上面说的两个方法,
class UserMailer < ApplicationMailer
def email_activation(user)
@user = user
mail to: user.email, subject: "Email activation"
end
def password_reset(user)
@user = user
mail to: user.email, subject: "Password reset"
end
在app/views/user_mailer/email_activation.html.erb中激活邮箱的html格式
<h1>Sample App</h1>
<p>Hi <%= @user.name %>,</p>
<p> Welcome to the Sample App! Click on the link below to activate your account: </p>
<%= link_to "Activate", edit_account_activation_url(@user.activation_token,email: @user.email) %>
邮件相关配置
在config/environments/development.rb文件中
Rails.application.configure do
config.action_mailer.raise_delivery_errors = true
config.action_mailer.perform_deliveries = true
config.action_mailer.delivery_method = :smtp
host = ENV[‘HOST‘]
config.action_mailer.default_url_options = { host: host, protocol: ‘http‘ }
ActionMailer::Base.smtp_settings = {
:address => ‘smtp.sendcloud.net‘,
:port => 25,
:authentication => "login",
:user_name => ENV[‘APIUSER‘],
:password => ENV[‘APIKEY‘],
:domain => ‘from@example.com‘,
:enable_starttls_auto => true
}
end
我们在user.rb中写一下关于token验证的方法(我是在model中写的,因为user里面方法太多了,看着不好,写完在user里面继承一下就好了)
module ActivationPasswordResetDigest
extend ActiveSupport::Concern
class_methods do
# 返回指定字符串的哈希摘要
def digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end
# 返回一个随机令牌
def new_token
SecureRandom.urlsafe_base64
end
end
def create_activation_digest
self.activation_token = User.new_token
update!(activation_digest: User.digest(activation_token))
activation_token
end
def create_reset_digest
self.reset_token = User.new_token
update!(reset_digest: User.digest(reset_token))
update!(reset_sent_at: Time.zone.now)
reset_token
end
def authenticated?(attribute, token)
digest = send("#{attribute}_digest")
return false if digest.blank?
BCrypt::Password.new(digest).is_password?(token)
end
# 如果密码重设请求超时了,返回 true
def password_reset_expired?
reset_sent_at < 2.hours.ago
end
end
然后在需要发送邮件的Controller里面调用
UserMailer.email_activation(@user).deliver_later
在account_activation.html.erb中调用生成token的方法:
<%= link_to "激活邮箱",edit_email_activation_url(@user.create_activation_digest,
email: @user.login_email)%>
差不多就是这样啦,有疑问可以在主页通过邮箱联系我
以上是关于ActionMailer发送邮件的主要内容,如果未能解决你的问题,请参考以下文章
通过电子邮件发送ActionMailer中的当前用户 - Rails 5
使用 ActionMailer 和 Outlook/Mandrillapp SMTP 服务器发送邮件