Sending SMTP Emails from Rails: A Comprehensive Guide
• Alen Hujdur
Sending emails is a crucial aspect of many web applications, and Ruby on Rails provides a powerful framework for handling email communication. In this article, we will explore how to configure and send SMTP (Simple Mail Transfer Protocol) emails from a Rails application. We’ll cover everything from setting up the SMTP configuration to creating and sending emails using Rails’ Action Mailer.
Setting up SMTP Configuration
Since we will be working in localhost - development environment, first we have to configure file:
config/environments/development.rb
and add following code (you can place it near the end-block):
In this example we will also use environment variables (ENV[‘VARIABLE_NAME’]), insted of hardcoded values.
With tiny bash script we can ask a user to fill in email credentials + SMTP configuration:
project_root_folder/config_smtp.sh:
Next, we are going to run:
In application_mailer configure email variable app/mailers/application_mailer.rb:
Also in the file app/mailers/sending_notification_mailer.rb add the following method send_notification:
In app/views/sending_notification_mailer/send_notification.html.erb add the following html:
And finally call mailer from Rails controller app/controllers/subscribers_controller.rb:
Also we have to generate a model Subscriber with command: