[英]Rails 3: Send welcome e-mail using Devise
當用戶注冊我的服務時,如何發送歡迎電子郵件?
另外,如何更改電子郵件:來自Devise的from和:subject字段?
謝謝
我不能使用“已批准”的答案,因為我沒有使用Devise的:確認。
我不喜歡其他解決方案,因為你必須使用模型回調,即使你在控制台或管理界面中創建他的帳戶,也會發送歡迎電子郵件。 我的應用程序涉及從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”以匹配您正在使用的型號名稱。
我是通過覆蓋設計的確認來做到的! 方法: 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
毋庸置疑,您可以在消息中測試更多(來自,等等),但如果您願意,這將使您以BDD方式開始。
另請參閱一些較舊的StackOverflow線程,深入了解此問題包括:
查看你的config / devise.rb
您可以更改語言環境文件中的主題(config / locales / devise.en.yml)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.