Rails tutorial: Send email with rails

In rails we use ActionMailer to send email. For more detail about ActionMailer check this link:

http://guides.rubyonrails.org/action_mailer_basics.html

Now its time to create mailer. Use following line of command to create mailer. Here I created Blog Mailer which is used to send email to all blog subscriber when new blog published.

rails g mailer ArticleMailer

Which will create applicaiton and article mailer riles within app/mailer directory. And also create mailer layout to views/layouts directory and also create new directory called article_mailer within views.

Note: The application mailer and layout file only created if you generate first mailer to your rails applicaiton.

Now its time to edit the mailer.

class ArticleMailer < ApplicationMailer
  default from: 'notifications@example.com'

  def new_article(article)
    @article = article
    @url = article_url_full_url
    @subscribers = Subscriber.all
    @subscribers.each do |s|
      @user = s
      mail(to: @user.email, subject: 'New Article Published')
    end
  end
end

Here @url is the full url of your article path. You need to change based on your route configuration.

Once you configure the mailer action, now its time to configure the email body. Create and view file called new_article.html.erb to the app/views/article_mailer directory and edit this file as following.

<!DOCTYPE html>
<html>
  <head>
    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
  </head>
  <body>
    <h1>Hello <%= @user.email %>,</h1>
    <p>
      We have published a new blog article on our website : <%= @url %>
    </p>

    <p>Thanks & Regards,</p>
    <p>Admin</p>
  </body>
</html>

Now its time to call mailer from controller action.

ArticleMailer.new_article(@article).deliver_now

Where @article is newly published article about which we want to send newsletter.

Now its time to configure SMTP setting. You can check my previous post to configure SMTP setting.

http://www.ganeshkunwar.com.np/2018/01/10/rails-smtp-configuration-runtime

Feel free to add comment if you face any problem. I will try to fix those issues and reply.

27Shares

2 Comments on “Rails tutorial: Send email with rails”

  1. Hello there, just became alert to your blog through Google, and found that it’s truly informative. I am going to watch out for brussels. I’ll be grateful if you continue this in future. Many people will be benefited from your writing. Cheers!

Leave a Reply

Your email address will not be published. Required fields are marked *

Enter Captcha Here : *

Reload Image