RubyonRails生产环境中发送邮件

2019-05-31

RubyonRails生产环境中发送邮件

1.开启SMTP服务

以QQ邮箱为例,在账户设置中开启POP3/SMTP服务获得授权码

2.配置代码

代码清单 1:配置应用,在生产环境中使用 QQ邮箱的SMTP

config/environments/production.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Rails.application.configure do
.
.
.
config.action_mailer.perform_caching = true
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
host = host_name
config.action_mailer.default_url_options = { host: host }
ActionMailer::Base.smtp_settings = {
:address => 'smtp.qq.com',
:port => 587,
:authentication => :login,
:user_name => user_name,
:domain => 'qq.com',
:password => user_password, # 此处为SMTP密钥授权码
:enable_starttls_auto => true
}
}
.
.
.
end

3.邮件程序模板

1.生成邮件程序(以密码重设为例)

$ rails generate mailer UserMailer password_reset

2.修改模板

app/mailers/user_mailer.rb

1
2
3
4
5
6
class UserMailer < ApplicationMailer
def password_reset(user)
@user =user
mail to: user.email , subject:"Password reset"
end
end

app/mailers/application_mailler.rb

1
2
3
4
class ApplicationMailer < ActionMailer::Base
default from: user_email
layout 'mailer'
end

app/views/user_mailer/password_reset.html.erb

1
2
3
4
5
6
7
8
9
10
11
12
<h1>Password reset</h1>

<p>
To reset your password click the link below:
</p>
<%= link_to "Reset Password",edit_password_reset_url(@user.reset_token,
email:@user.email) %>
<p>This link will expire in two hours.</p>
<p>
If you did not request your password to be reset, please ignore this email
and your password will stay as it is.
</p>

app/views/user_mailer/password_reset.text.erb

1
2
3
4
To reset your password click the link below:
<%= edit_password_reset_url(@user.reset_token,email:@user.email) %>
This link will expire in two hours.
If you did not request your password to be reset, please ignore this email and your password will stay as it is.

4.调用邮件方法

app/models/user.rb

1
2
3
4
#发送密码重设邮件
def send_password_reset_email
UserMailer.password_reset(self).deliver_now
end
-->