📅  最后修改于: 2023-12-03 15:04:47.214000             🧑  作者: Mango
在 Ruby on Rails 中,我们经常需要发送电子邮件来通知用户或将数据转发给其他人。因此,发送测试邮件是非常有必要的。
config/environments/development.rb
文件中:config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => 'smtp.gmail.com',
:port => 587,
:user_name => '[your email address]',
:password => '[your email password]',
:authentication => :plain,
:enable_starttls_auto => true
}
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
UserMailer
类,其继承自 ActionMailer::Base
。这个类将使用上面的配置,在测试环境下发送电子邮件:class UserMailer < ActionMailer::Base
default from: 'from@example.com'
def welcome_email(user)
@user = user
@url = 'http://example.com/login'
mail(to: @user.email, subject: 'Welcome to My Awesome Site')
end
end
app/views/user_mailer/welcome_email.html.erb
和 app/views/user_mailer/welcome_email.text.erb
。这些视图将被 Email 使用来生成邮件内容。<!-- welcome_email.html.erb -->
<h1>Welcome <%= @user.name %>!</h1>
<p>
You have successfully signed up to My Awesome Site!
You can now login to your account at the following URL:
<%= link_to @url, @url %>
</p>
<!-- welcome_email.text.erb -->
Welcome <%= @user.name %>!
You have successfully signed up to My Awesome Site!
You can now login to your account at the following URL: <%= @url %>
UserMailer
来发送测试邮件:class UsersController < ApplicationController
def create
@user = User.new(params[:user])
if @user.save
UserMailer.welcome_email(@user).deliver_now
redirect_to @user
else
render :new
end
end
end
在 Ruby on Rails 中,发送测试邮件非常简单。我们只需要设置 action_mailer
的配置信息,并在控制器中调用 UserMailer
,就可以将测试邮件发送出去了。