Sending Emails in Rails Applications
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.
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.
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.
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.
That’s it! When a new user object is saved, an email will be sent to the user via SendGrid.