9/18/2018 - 2:33 PM

Sending an Email


Sending an Email

  • Set up an app (where a User model has an email)
  • Next, run rails g mailer name_of_mailer
    • This will create some files in app/mailers/name_of_mailer.rb and some in the test unit
# app/mailers/name_of_mailer.rb

class NameOfMailer < ActionMailer:: Base
  default from: ""

  • Add custom functions to customize your email
  • Change the default email to the email address you want to use as the sender's email address
# app/mailers/name_of_mailer.rb

class NameOfMailer < ActionMailer:: Base
  default from: ""
  def sample_email(user)
    @user = user
    mail(to:, subject: "Sample Email")


Mail Contents

  • To write the actual contents of the mail, navigate to app/views/name_of_mailer and create a file with a .html.erb extension
<!DOCTYPE html>
    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
    <h1>Hi <%= %></h1>
      Sample mail sent using smtp.
  • You can also create a text version, incase you prefer your user's to not have an HTML email
  • In the same directory, create a file with a .text.erb extension
Hi <%= %>
Sample mail sent using smtp.

Previewing an Email

  • You can preview an email before sending it out by navigating in the browser to /rails/name_of_mailer/function_name
    • in the case below: http://localhost:3000/rails/mailers/example_mailer/sample_mail_preview
  • But first you will need to set up a user, so in test/mailers/previews/name_of_mailer_preview.rb use the following code:
class ExampleMailerPreview < ActionMailer::Preview
  def sample_mail_preview

How does Rails send emails?

  • By default, Rails uses SMTP (Simple Mail Transfer Protocol)
  • You will need to provide SMTP configurations in environment settings config/environments/
  • Store the email and password in the secrets.yml file
config.action_mailer.delivery_method = :smtp
# SMTP settings for gmail
config.action_mailer.smtp_settings = {
 :address              => "",
 :port                 => 587,
 :user_name            => ENV['gmail_username'],
 :password             => ENV['gmail_password'],
 :authentication       => "plain",
:enable_starttls_auto => true
  • Typically, you want to send emails from the production environment (you can still send to dev environment, makes more sense to not clog up emails in dev env)

Sending an email linked to Controller Action

  • In the action that you want the email to be sent: NameOfMailer.sample_email(@user).deliver