Sending Emails

Episode #8 by Teacher's Avatar David Kimura

Summary

This episode is a prelude to ActiveJob and background processing. Learn how to send emails using an external mail service with Rails.
rails mail 5:26

Resources

Summary

# visitors#send_contact
  from = params[:contact][:from]
  subject = params[:contact][:subject]
  message = params[:contact][:message]
  ContactMailer.send_contact(from,subject,message).deliver_now

# bash
  rails g mailer contact_mailer send_contact

# contact_mailer.rb
    def send_contact(from,subject,message)
      @from = from 
      @subject = subject 
      @message = message 
      mail to: "support@driftingruby.com", subject: @subject
    end

# test/mailers/previews/contact_mailer_preview.rb
    def send_contact
      from = 'sample@driftingruby.com'
      subject = 'Site Feedback'
      message = 'You should really have more episodes about different taco flavorings.'
      ContactMailer.send_contact(from,subject,message)
    end

# views/contact_mailer/send_contact.html.erb
<p>You have received a message from <%= @from %>.</p>
<p><%= @message %></p>