Hello party people and polar bears! You were probably wondering how it is you send email using Ruby on Rails. Here’s how you create an automated email system that sends a confirmation email to each new user that registers to your app:

1. First off, in bash, you must generate your mailer, which uses the Rails generate command (pretty much the same way you generate a controller or a model). Assuming you’ve already created your Rails project, to create the mailer you must simply do the following:

cd ~/my_rails_project

rails generate mailer welcome_mailer

bundle install

2. The next thing to do would be to setup an SMTP transport for your mailer. This is done in /config/initializers/setup_mail.rb. If you don’t have that file in your Rails project, you should go ahead and create it.

This is how your setup_mail.rb file should look like:

ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
:address => "smtp.servername.com",
:port => 587,
:domain => "whatever.org",
:user_name => "username",
:password => "password",
:authentication => "plain",
:enable_starttls_auto => true
}

3. Then we’d need to tell Rails the specifics the email you want to send, like who to send it to, where does it come from, as well as the actual Subject and Content.

We do that by creating a method in the recently created mailer, which we’ll name registration_confirmation:

class WelcomeMailer < ActionMailer::Base

def registration_confirmation(user)

mail :to => user, :from => "email@domain.com", :subject => "Subject line"

end
end

4. Assuming you want the email to have some content as well, we can now go ahead and create the HTML and Plain text versions of your email. That’s done in /views/welcome_mailer/registration_confirmation.html.erb and /views/welcome_mailer/registration_confirmation.text.erb (you’ll have to create these files):

Hello, <%= @user.name %>

Thank you for registering!

Now, to actually make use of the Mailer, in the specific action (associated to a controller) you want the mailer used on – you simply need to add:

WelcomeMailer.registration_confirmation(@user).deliver

Privacy Preference Center