【发布时间】:2010-12-29 11:16:39
【问题描述】:
当用户注册我的服务时,我如何发送欢迎电子邮件?
另外,我如何更改来自 Devise 的电子邮件 :from 和 :subject 字段?
谢谢
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 devise
当用户注册我的服务时,我如何发送欢迎电子邮件?
另外,我如何更改来自 Devise 的电子邮件 :from 和 :subject 字段?
谢谢
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 devise
我不能使用“已批准”的答案,因为我没有使用 Devise 的 :confirmable。
我不喜欢其他解决方案,因为您必须使用模型回调,即使您在控制台或管理界面中创建他的帐户,它也会始终发送欢迎电子邮件。我的应用程序能够从 CSV 文件中大量导入用户。我不希望我的应用一个接一个地向所有 3000 人发送一封惊喜电子邮件,但我确实希望创建自己帐户的用户收到一封欢迎电子邮件。 解决办法:
1) 覆盖 Devise 的注册控制器:
#registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
def create
super
UserMailer.welcome(resource).deliver unless resource.invalid?
end
end
2) 告诉 Devise 你覆盖了它的注册控制器:
# routes.rb
devise_for :users, controllers: { registrations: "registrations" }
当然,您可以调整“UserMailer”和“devise_for :users”以匹配您正在使用的模型名称。
【讨论】:
resource:RegistrationsMailer.welcome(resource).deliver if resource.persisted?
unless @user.invalid? 确保在注册完成之前不会发送它。
我通过覆盖设计的确认来做到这一点!方法:https://gist.github.com/982181
class User < ActiveRecord::Base
devise :invitable, :database_authenticatable, :registerable, :recoverable,
:rememberable, :confirmable, :validatable, :encryptable
# ...
# devise confirm! method overriden
def confirm!
welcome_message
super
end
# ...
private
def welcome_message
UserMailer.welcome_message(self).deliver
end
end
【讨论】:
这是一个很棒的讨论。覆盖 benoror 建议的方法会很好。如果您认为您可能想要捕获其他用户事件,那么正如其他人在其他地方所建议的那样,Observer 类可能是最干净的方法。此解决方案适用于 Rails 3.0.x 和 3.1。
要设置观察者,您对应用程序文件进行以下更改,将此观察者添加到您可能已经拥有的任何其他观察者中。
#config/application.rb
config.active_record.observers = :user_observer
然后在models目录下新建一个文件:
#app/models/user_observer.rb
class UserObserver < ActiveRecord::Observer
def after_create(user)
Notifier.user_new(user).deliver
end
end
如果您有一个练习创建用户功能的黄瓜测试,您可以将此步骤添加到该功能并使用工作步骤备份它以检查测试邮件数组中的电子邮件。
#features/users/sign_up.feature for example
Scenario: User signs up with valid data
...
And I should receive an email with "[Text from your welcome message]"
#features/common_steps.rb
Then /^I should receive an email with "([^"]*)"$/ do |value|
# this will get the most recent email, so we can check the email headers and body.
ActionMailer::Base.deliveries.should_not be_empty
@email = ActionMailer::Base.deliveries.last
@email.body.should include(value)
#@email.from.should == ["no-reply@example.com"]
end
你的环境/test.rb 应该有这些设置来构建一个邮件数组而不是发送:
config.action_mailer.delivery_method = :test
config.action_mailer.perform_deliveries = true
不用说您可以在消息中测试更多内容(to、from 等),但如果您愿意,这将以 BDD 方式开始。
另请参阅一些深入了解此问题的旧 StackOverflow 线程,包括:
【讨论】:
查看您的 config/devise.rb
您可以在您的语言环境文件 (config/locales/devise.en.yml) 中更改主题
【讨论】: