parm530
9/18/2018 - 2:33 PM

Sending an Email

ActionMailer

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: "from@example.com"

end
  • 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: "from@example.com"
  
  def sample_email(user)
    @user = user
    mail(to: @user.email, subject: "Sample Email")
  end

end

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>
<html>
  <head>
    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
  </head>
  <body>
    <h1>Hi <%= @user.name %></h1>
    <p>
      Sample mail sent using smtp.
    </p>
  </body>
</html>
  • 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 <%= @user.name %>
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
    ExampleMailer.sample_email(User.first)
  end
end

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              => "smtp.gmail.com",
 :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