How to send mails via devise
Devise is a popular authentication gem for Ruby on Rails applications. To send emails via Devise, you'll need to configure Devise to use a mailer and set up a mailer class to handle the email sending. Here's a step-by-step guide:
Step 1: Configure Devise
In your config/initializers/devise.rb
file, add the following line to enable email notifications:
config.mailer_sender = '[email protected]'
Replace [email protected]
with the email address you want to use as the sender.
Step 2: Create a Mailer Class
Create a new file called user_mailer.rb
in your app/mailers
directory:
# app/mailers/user_mailer.rb
class UserMailer < Devise::Mailer
helper :application
include Devise::Controllers::UrlHelpers
def confirmation_instructions(record, token, opts={})
@record = record
@token = token
mail to: record.email, subject: "Confirmation instructions"
end
def reset_password_instructions(record, token, opts={})
@record = record
@token = token
mail to: record.email, subject: "Reset password instructions"
end
def unlock_instructions(record, token, opts={})
@record = record
@token = token
mail to: record.email, subject: "Unlock instructions"
end
def email_change(record, opts={})
@record = record
mail to: record.email, subject: "Email changed"
end
end
This mailer class defines four methods: confirmation_instructions
, reset_password_instructions
, unlock_instructions
, and email_change
. Each method sends an email to the user with a specific subject and content.
Step 3: Configure the Mailer
In your config/environments/production.rb
file (or development.rb
if you're testing), add the following line to configure the mailer:
config.action_mailer.default_url_options = { host: 'your_host.com', port: 443 }
Replace your_host.com
with your application's domain name.
Step 4: Send Emails
Now, when a user signs up, confirms their email, resets their password, or changes their email, Devise will use the UserMailer
class to send an email to the user.
You can test the email sending by running the following command in your terminal:
rails c
UserMailer.confirmation_instructions(User.first, User.first.confirmation_token).deliver_now
This will send a confirmation email to the first user in your database.
That's it! With these steps, you should be able to send emails via Devise in your Ruby on Rails application.