Rails tutorial: Send email with rails
In rails we use ActionMailer to send email. For more detail about ActionMailer check this link:
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: 'firstname.lastname@example.org' 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.
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.
Feel free to add comment if you face any problem. I will try to fix those issues and reply.