SendGrid With Ruby on Rails

Overview

It was time to implement the reset password for a user in our ongoing app. There was a need to send an email containing a generated token to the user. I thought it wise to leverage on a third-party application like SendGrid to handle this process for me.

Implementation Steps

  1. Signup with SendGrid

  2. Add the following in your config/environment.rb. Replace the variable with your SendGrid details.

ActionMailer::Base.smtp_settings = {
  :user_name => ENV["SENDGRID_USERNAME"],
  :password => ENV["SENDGRID_PASSWORD"],
  :domain => ENV["SENDGRID_DOMAIN"],
  :address => "smtp.sendgrid.net",
  :port => 587,
  :authentication => :plain,
  :enable_starttls_auto => true,
}

3. Run the below command to generate the usermailer

rails generate mailer UserNotifierMailer  

4. In the mailer/user_notifier_mailer.rb add the following script

class UserNotifierMailer < ApplicationMailer
  default :from => "from_email@gmail.com"
  def send_email(user)
    @user = user

    mail(:to => @user.email,
         :subject => "Password Reset",
         :body => "Copy the verification code: #")
  end
end

5. In your password controller call on the method created in your UserNotifierMailer. So it will look like the script below

def forgot
    if params[:email].blank?
      return render json: { error: "Email not present" }, status: :bad_request
    end

    user = User.find_by(:email => params[:email])

    if user.present?
      user.generate_password_token!
      UserNotifierMailer.send_email(user).deliver

      render json: { status: "ok" }, status: :ok
    else
      render json: { error: ["Email address not found. Please check and try again."] }, status: :not_found
    end
  end

6.Added the following route

  post "password/forgot", to: "passwords#forgot"

So when you hit the route above with an existing email in the database, a token will be generated and sent to the users email.

I will also like to lay emphasis on the port. SendGrid accepts unencrypted and TLS connections on ports 25587, & 2525. You can also connect via SSL on port 465.

Many hosting providers and ISPs block port 25 as a default practice. If this is the case, contact your host/ISP to find out which ports are open for outgoing SMTP relay. We recommend port 587 to avoid any rate-limiting that your server host may apply. The port is one issue you wouldn’t like to face.

Reference

SendGrid

Previous
Previous

Law of Demeter

Next
Next

Testing Pyramid