top of page

Sending Emails in Rails Applications

  • Writer: Mischelle L
    Mischelle L
  • Apr 12, 2018
  • 1 min read

Action Mailer is the Rails component that enables applications to send and receive emails. In Rails, emails are used by creating mailers that inherit from “ActionMailer::Base” in app/mailers. Those mailers have associated views that appear alongside controller views in app/views.

Now we will build a rails application which will send an email to the user when a new user is created. Let’s create a new rails application.

$ rails new sample_app
$ cd sample_app
$ rails generate scaffold user first_name:string last_name:string   phone_number:string email:string
$ rake db:migrate

Action Mailer- Configuration:

Following are the steps you have to follow to complete your configuration before proceeding with the actual work.

We will just add following lines of code in  config/environments/development.rb

config.action_mailer.delivery_method = :smtp

#It tells ActionMailer that you want to use the SMTP server.


Generate a Mailer :

We now have a basic application, let’s make use of ActionMailer. The mailer generator is similar to any other generator in rails.

$ rails g mailer example_mailer

#This will create a example_mailer.rb in the app\mailer directory.


Now we open up app/mailers/example_mailer.rb and add a mailer action that sends users a signup email.

app/mailers/example_mailer.rb


Now let’s write the mail we want to send to our users, and this can be done in app/views/example_mailer. Create a file sample_email.html.erb which is an email formatted in HTML.

app/views/example_mailer/sample_email.html.erb


We also need to create the text part for this email as not all clients prefer HTML emails. Create sample_email.text.erb in the app/views/example_mailer directory.

app/views/example_mailer/sample_email.text.erb


Now in the controller for the user model app/controllers/users_controller.rb, add a call to ExampleMailer.send_signup_email when a user is saved.


app/controllers/users_controller.rb

That’s it! When a new user object is saved, an email will be sent to the user via SendGrid.

 
 
 

Recent Posts

See All

Comments


© 2023 by Walkaway. Proudly created with Wix.com

  • Facebook Black Round
  • Google+ - Black Circle
  • Twitter Black Round
bottom of page