Sending Confirmation Emails

Sending email in Rails requires three basic steps:

  1. Configuring how the email is to be sent
  2. Determining when to send the email
  3. Specifying what we want to say in the email.

We’ll cover each of these three in turn.

Configuring email

Email configuration is part of a Rails application’s environment and involves a Rails.application.configure block. If we want to use the same configuration for development, testing, and production, add the configuration to environment.rb in the config directory; Otherwise, add different configurations to the appropriate files in the config/environments directory.

Inside the block, we need to have one or more statements. We first have to decide how we want our mail to be delivered:

config.action_mailer.delivery_method = :smtp

Alternatives to :smtp include :sendmail and :test.

The :smtp and :sendmail options are used when we want Action Mailer to attempt to deliver email. We’ll clearly want to use one of these methods in production.

The :test setting is great for unit and functional testing. Email won’t be delivered, but will instead be appended to an array, which is accessible via the ActionMailer::Base.deliveries attribute. This is the default delivery method in the test environment. Interestingly, though, the default in development mode is :smtp. If we want Rails to deliver email during the development of our application, this is good. If we’d rather disable email delivery in development mode, edit the development.rb file in the config/environments directory and add the following lines:

Rails.application.configure do 
   config.action_mailer.delivery_method = :test
end

The :sendmail setting delegates mail delivery to our local system’s sendmail program, which is assumed to be in /usr/sbin. This delivery mechanism isn’t particularly portable, because sendmail isn’t always installed in this directory for every operating system. It also relies on our local sendmail supporting the -i and -t command options.

We achieve more portability by leaving this option at its default value of :smtp. If we do so, we’ll also need to specify some additional configuration to tell Action Mailer where to find an SMTP server to handle our outgoing email. This can be the machine running our web application, or it can be a separate box like at our ISP if we’re running Rails in a noncorporate environment. Our system administrator will be able to give us the settings for these parameters. We may also be able to determine them from our own mail client’s configuration.

The following are typical settings for Gmail. Adapt them as needed.

Get hands-on with 1200+ tech skills courses.