Ruby on Rails Devise Gem, specify email template from a controller - ruby-on-rails

I have a controller which inherited from ApplicationController
where I send reset password insturctions, is there any way to specify template?
#user=User.find_by_email(email);
if #user.nil?
render :status=>404, :json=>{:message=>"User not found or email format is invalid."}
return
else
#user.devise_mailer.reset_password_instructions(#user).deliver
render :status=>200, :json=>{:message=>"Reset password instructions have been sent."}
end
As you see in the snippet above, #user.devise_mailer.reset_password_instructions(#user).deliver
Sends reset password instructions, but it takes default email template, which I don't wanna change. I need to create another template and somehow specify to use it

Create your own mailer then. See http://guides.rubyonrails.org/action_mailer_basics.html for details. Once you have a new mailer, in the controller, instead of:
#user.devise_mailer.reset_password_instructions(#user).deliver
you'd do something like:
YourMailer.reset_password_instructions(#user).deliver
You may want to reuse parts of Devise in your mailer: check out devise sources for that: https://github.com/plataformatec/devise/blob/master/lib/devise/mailers/helpers.rb
Another thing you may try is redefining devise template by putting a file named app/views/devise/mailer/reset_password_instructions.html.erb in your application directory. Of course you can base your implementation on devise sources as well: https://github.com/plataformatec/devise/blob/master/app/views/devise/mailer/reset_password_instructions.html.erb

Related

Devise Reconfirmable - alternative email is not picked

I am allowing users to change their email in Devise.
Since this commit : https://github.com/heartcombo/devise/commit/ce071502eeb5c5c5199436f6694bfb6103010c4a it is possible to send an alternative email than the usual "Welcome" Registration email.
Devise mailer now includes a specific method for this: https://github.com/heartcombo/devise/blob/master/app/mailers/devise/mailer.rb
I have then created 2 different views in my my_model/views/mailer folder: email_changed.html.erb and email_changed.text.erb
Though this alternative email is never picked. The original Welcome email is sent instead...
Am I missing something ?
===
My Devise version is 4.7.3 (also I am coming from an old version)
and my devise initializer has config.reconfirmable = true
I have seen this hack but I guess it shouldn't need be used anymore : How to send two different emails for devise confirmable and devise reconfirmable?
Is that my_model/views/mailer folder right? according to the code (*) it should be views/my_model/mailer.
https://github.com/heartcombo/devise/blob/45b831c4ea5a35914037bd27fe88b76d7b3683a4/lib/devise/mailers/helpers.rb#L66
I would suggest you to copy that helper file inside your project so you can put some byebug statement and properly debug it.

Customize Devise Passwords error message

I've a project that implements devise and I'm having trouble overriding the Passwords controller's messages.
When a wrong email address is entered by the user, Devise by default gives
Unable to find user with email {email}
I cant find the key to override this message in the devise.en.yml and can't find anything with the similar message on the devise repo as well.
Do I have an option other than to override the controller? Any help is appreciated.
Thanks
Add a new locale having the following structure:
en:
devise_token_auth:
passwords:
user_not_found: "Your custom message"
This message will be displayed when an invalid email is passed in the forgot password form.
Originally this message comes from the devise_token_auth gem. But if you have the same locale in your locale files, it will override the gem's locale.
It doesn't matter which *.en.yml file you will put this locale into. It can be devise.en.yml, or you can add a new file called devise_token_auth.en.yml. Only the structure matters.
as described in the following link you can generate the devise controller with
rails generate devise:controllers user
then you can over-ride the create or update action. If you include super in the new action, it will call the parent controller action and then execute the code.
You can also over-ride the devise messages as explained in this post, you just need to create that locale in your settings
en:
devise_token_auth:
sessions:
not_confirmed: "your message overwritten"

sending emails using templates in Mandrill

I've read through the docs and still am unclear on how to actually use these templates in mandrill.
Currently I have a rails app with the standard Rails mailers (located in: App > views > welcome_mailer > welcome_email.html.erb) being sent through the Mandrill SMTP setup. This is working fine.
Now, I have a template in Mandrill ready to go, now what?
How do I actually use this template, do I need to adjust the code on my app to make a different call, or do I need to do something on the mandrill dashboard to tell it to use the new template instead of the rails version being sent now.
How do I actually use this template?
Thank you in advance.
You can use mandrill_mailer gem, inherit your mailer from MandrillMailer::TemplateMailer and then send it as usual InvitationMailer.invite(invitation).deliver.
Without any gems :
To use mandrill template you first need to create one in your mandrill account and then in your mailer add a correct header which tells the name of the template. Then mandrill will by magic automatically call that template.
Example:
# app/mailers
class CardMailer < ActionMailer::Base
default from: "admin#domain.ch"
def welcome(card)
mail to: card.responsable.email,
from: "\"Andrey\" <admin#domain.ch>",
subject: 'Welcome in my website'
headers['X-MC-MergeVars'] = "{\"TYPE\":\"#{card.card_type.name}\"}" # variables
headers['X-MC-Template'] = "welcome" # template
headers['X-MC-AutoText'] = 1 # generate text version
headers['X-MC-InlineCSS'] = "true" # inline css
end
end
In my case, it uses my "welcome" template. Just use the name of your mandrill template.
As you can see, there are many other headers available. See the full-list here.
Note : even if you don't use rails template any more, you still need one in your view.

Rails + Devise => Use Devise Mailer globally to handle all of the mail sending?

I would like to use the devise mailer globally,
since that way I would not have to add another mailer to my app and just use the devise one, to send custom mails outside the devise views/controllers.
Already digged to long for this, anyone know how I can make this possible?
If the point is to only have one mailer, it's perhaps more straightforward to have your one single mailer just extend the DeviseMailer. E.g. in app/mailer
# app/mailers/mailer.rb
class Mailer < Devise::Mailer
# add all your custom mailer methods
end
This setup will, for example, cause all emails (from Devise and otherwise) to all be sent with the app/layouts/mailer.html.erb template.
Note that to do this you do need to move the Devise mailer templates from app/views/devise/mailer to just app/views/mailer.

How do I preview emails in Rails?

This might be a dumb question but when I'm putting together an HTML email in Rails, is there a particularly easy built-in way to preview the template it in the browser or do I need to write some sort of custom controller that pulls it in as its view?
Action Mailer now has a built in way of previewing emails in Rails 4.1. For example, check this out:
# located in test/mailers/previews/notifier_mailer_preview.rb
class NotifierPreview < ActionMailer::Preview
# Accessible from http://localhost:3000/rails/mailers/notifier/welcome
def welcome
Notifier.welcome(User.first)
end
end
Daniel's answer is a good start, but if your email templates contain any dynamic data, it won't work. E.g. suppose your email is an order receipt and within it you print out #order.total_price - using the previous method the #order variable will be nil.
Here's a little recipe I use:
First, since this email preview functionality is definitely for internal use only, I set up some generic routes in the admin namespace:
#routes.rb
MySite::Application.routes.draw do
namespace :admin do
match 'mailer(/:action(/:id(.:format)))' => 'mailer#:action'
end
end
Next, I create the controller. In this controller, I create one method per email template. Since most emails contain dynamic data, we need to populate whatever member variables the template expects.
This could be done with fixtures, but I typically prefer to just grab some pseudo-random real data. Remember - this is NOT a unit test - this is purely a development aid. It doesn't need to produce the same result every single time - in fact - it's probably better if it doesn't!
#app/controllers/admin/mailer_controller.rb
class Admin::MailerController < Admin::ApplicationController
def preview_welcome()
#user = User.last
render :file => 'mailer/welcome.html.erb', :layout => 'mailer'
end
end
Note that when we render the template, we use layout=>:mailer. This embeds the body of your email inside the HTML email layout that you've created instead of inside your typical web application layout (e.g. application.html.erb).
And that's pretty much it. Now I can visit http://example.com/admin/mailer/preview_welcome to preview change to my welcome email template.
37Signals also has their own mail testing gem called mail_view. It's pretty fantastic.
The easiest setup I've seen is MailCatcher. Setup took 2 minutes, and it works for new mailers out of the box.
I use email_preview. Give it a try.
Easiest solution in rails 6: just remember one url:
http://localhost:3000/rails/mailers
I'm surprised no one's mentioned letter_opener. It's a gem that will render and open emails as a browser page whenever an email is delivered in dev.
I recently wrote a gem named Maily to preview, edit (template file) and deliver the application emails via a browser. It also provides a friendly way to hook data, a flexible authorization system and a minimalist UI.
I have planned to add new features in the near future, like:
Multiple hooks per email
Parametrize emails via UI (arguments of mailer method)
Play with translations keys (list, highlight, ...)
I hope it can help you.
rails generates a mail preview if you use rails g mailer CustomMailer.
You will get a file CustomMailerPreview inside spec/mailers/previews folder.
Here you can write your method that will call the mailer and it'll generate a preview.
For ex -
class CustomMailerPreview < ActionMailer::Preview
def contact_us_mail_preview
CustomMailer.my_mail(user: User.first)
end
end
Preview all emails at http://localhost:3000/rails/mailers/custom_mailer
You can use Rails Email Preview
REP is a rails engine to preview and test send emails, with I18n support, easy premailer integration, and optional CMS editing with comfortable_mexican_sofa.
There is no way to preview it directly out of the Mailer.
But as you wrote, you can write a controller, which looks something like this.
class EmailPreviewsControllers < ActionController::Base
def show
render "#{params[:mailer]}_mailer/#{params[:method]}"
end
end
But I think, that's not the best way to test emails, if they look correctly.
Rails Email Preview helps us to quickly view the email in web browser in development mode.
1) Add “gem ‘rails_email_preview’, ‘~> 0.2.29’ “ to gem file and bundle install.
2) Run “rails g rails_email_preview:install” this creates initializer in config folder and add routes.
3) Run “rails g rails_email_preview:update_previews” this crates mailer_previews folder in app directory.
Generator will add a stub to each of your emails, then u populate the stub with mock data.
Ex:
class UserMailerPreview
def invitation
UserMailer.invitation mock_user(‘Alice’), mock_user(‘Bob’)
end
def welcome
UserMailer.welcome mock_user
end
private
def mock_user(name = ‘Bill Gates’)
fake_id User.new(name: name, email: “user#{rand 100}#test.com”)
end
def fake_id(obj)
obj.define_singleton_method(:id) { 123 + rand(100) }
obj
end
end
4) Parameters in search query will be available as an instance variable to preview class. Ex: if we have a URL like
“/emails/user_mailer_preview-welcome?user_id=1” #user_id is defined in welcome method of UserMailerPreview it helps us to send mail to specific user.
class UserMailerPreview
def welcome
user = #user_id ? User.find(#user_id) : mock_user
UserMailer.welcome(user)
end
end
5) To access REP url’s like this
rails_email_preview.rep_root_url
rails_email_preview.rep_emails_url
rails_email_preview.rep_email_url(‘user_mailer-welcome’)
6) We can send emails via REP, this will use environment mailer settings. Uncomment this line in the initializer to disable sending mail in test environment.
config.enable_send_email = false
Source : RailsCarma Blog : Previewing Emails in Rails Applications With the Mail_View Gem
I prefer mails_viewer gem. This gem is quite useful as it save the HTML template into tmp folder.

Resources