SendGridでメールを送信する

1. mailerを作成

$ rails generate mailer UserNotifier

app/mailers/usernotifier.rb

class UserNotifier < ActionMailer::Base
  default :from => 'any_from_address@example.com'

  # send a signup email to the user, pass in the user object that   contains the user's email address
  def send_signup_email(user)
    @user = user
    mail( :to => @user.email,
    :subject => 'Thanks for signing up for our amazing app' )
  end
end

2. templateを作成
app/views/Usernotifier/send_signup_email.erb

<!DOCTYPE html>
<html>
  <head>
    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
  </head>
  <body>
    <h1>Thanks for signing up, <%= @user.name %>!</h1>
    <p>Thanks for joining and have a great day! Now sign in and do
awesome things!</p>
  </body>
</html>

3. SendGridを利用するように設定
config/environment.rb

ActionMailer::Base.smtp_settings = {
  :user_name => 'your_sendgrid_username',
  :password => 'your_sendgrid_password',
  :domain => 'yourdomain.com',
  :address => 'smtp.sendgrid.net',
  :port => 587,
  :authentication => :plain,
  :enable_starttls_auto => true
}

4. UserNotifier.send_signup_email(@user).deliverなどの様にして呼び出す。
app/controllers/users_controller.rb

class UsersController < ApplicationController
  def create
    # Create the user from params
    @user = User.new(params[:user])
    if @user.save
      # Deliver the signup email
      UserNotifier.send_signup_email(@user).deliver
      redirect_to(@user, :notice => 'User created')
    else
      render :action => 'new'
    end
  end
end