Often, we want to send an email whenever certain events occur, such as a new resource being created.
Before we learn how to send emails, we're going to learn how to set up our app so that certain events can trigger methods based on rules we set up.
Callbacks are a feature in ActiveRecord that allow you to run a specified method in a model whenever a particular model is created, saved, updated and more.
http://edgeguides.rubyonrails.org/active_record_callbacks.html
Rails has a built-in way to make mail work easily on your app.
http://guides.rubyonrails.org/action_mailer_basics.html
rails g mailer UserMailer
# mailers/user_mailer.rb
def welcome_email(user)
@user = user
mail(to: @user.email, subject: "Welcome!")
end
In views/user_mailer/welcome_email.html.erb
:
Hello! This is an email that we are sending you, and we can use HTML in it!
<br/><br/>
See?
Usually in the controller:
UserMailer.welcome_email(current_user).deliver
Let's experiment with a few different callbacks to verify that we can trigger behavior upon certain actions.
Then, let's extend the Tasky project management app to send an email to the assignee of a task whenever it is updated.
config.action_mailer.raise_delivery_errors = true
config.action_mailer.perform_deliveries = true
config.action_mailer.default_url_options = { host: 'localhost:3000' }
config.action_mailer.smtp_settings = {
address: "smtp.gmail.com",
port: 587,
domain: "localhost:3000",
authentication: "plain",
enable_starttls_auto: true,
user_name: ENV["GMAIL_USERNAME"],
password: ENV["GMAIL_PASSWORD"]
}
ENV is the way you can access environment variables within Rails. If you are using sensitive information (such as your email passwords), you do not want to store them in code (since they get deployed to a public GitHub repository).
Instead, place environment variables inside your ~/.bash_profile
or equivalent:
export GMAIL_USERNAME='your.username@gmail.com'
export GMAIL_PASSWORD='your_password'
Then reference them in your Rails app:
user_name: ENV["GMAIL_USERNAME"],
password: ENV["GMAIL_PASSWORD"]