Tuesday, 18 January 2022
Logo
     
Home > Articles > Sending Emails In Rails Applications
article_img

Sending Emails In Rails Applications

ruby rails rubygems    about 4 years Ago     7318   156   Like

Introduction

In this article we will walk through a simple app to demonstrate how to send emails through a Rails application with ActionMailer, ActionMailer Preview, and through a third party email service provider such as Gmail or Mailgun. We will also demostrate how to use Active Job to send the email with a background processor.

You can find the code for this tutorial here

Sending Emails Using ActionMailer and Gmail

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 new_app_name
$ rails g scaffold user name:string email:string
$ rake db:migrate

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
create  app/mailers/example_mailer.rb
invoke  erb
create    app/views/example_mailer
invoke  test_unit
create    test/mailers/example_mailer_test.rb
create    test/mailers/previews/example_mailer_preview.rb

Our application is currently using Rails 4.2.0.beta4 so the rails generator has created preview files for our application by default as test/mailers/previews/example_mailer_preview.rb which we will be using later.

app/mailers/example_mailer.rb

class ExampleMailer < ActionMailer::Base
  default from: "from@example.com"
end

Now let’s write methods and customized email. First you should change the default email address from from@example.com to the email address you want use as the sender’s address.

class ExampleMailer < ActionMailer::Base
  default from: "from@example.com"

  def sample_email(user)
    @user = user
    mail(to: @user.email, subject: 'Sample Email') end end


This Site is all about collection of best resources

Users able to write own articles or share the resources they know

If you found any copy right issues, kindly CONTACT US. will take Immediate Action.
Subscribe To Us

Busy At Work?? Not Having Time To Know Whats Happening In Ruby World??

We will Send You Weekly Notifications About News, Jobs, Articls, Conferences etc..

Subscribe Now