Search code examples
emailsmtpgmailruby-on-rails-5mailer

How do I send an email from Rails using Gmail?


I'm using Rails 5 and trying to send out some emails from my dev machine using Gmail as a relay. I have this mailer file, app/mailers/user_notifier.rb

class UserNotifier < ActionMailer::Base
  default from: RAILS_FROM_EMAIL

  # send notification email to user about the price
  def send_notification(user_notification, crypto_price)
    puts "user notification: #{user_notification.id}"
    @user = user_notification.user
    @crypto_price = crypto_price
    threshhold = user_notification.buy ? 'above' : 'below'
    puts "user: #{@user.email} currency: #{@user.currency}"
    mail( :to => @user.email,
    :subject => sprintf(Constants::USER_NOTIFICATION_SUBJECT, crypto_price.crypto_currency.name, threshhold, PriceHelper.format_price(user_notification.price, @user.currency) )  )
  end

And then I send the email from a Sidekiq worker like so

UserNotifier.send_notification(user_notification, price).deliver

Although I don't see any errors in my logs, the email is never delivered (I have checked my spam folder to verify this). Below is my config/environments/development.rb file.

  # ActionMailer Config
  config.action_mailer.smtp_settings = {
     address:              'smtp.gmail.com',
     port:                 587,
     domain:               'mybox.devbox.com',
     user_name:            'myusertest1',
     password:             'myuser99999',
     authentication:       'plain',
     enable_starttls_auto: true
  }
  config.action_mailer.delivery_method = :smtp
  # change to true to allow email to be sent during development
  config.action_mailer.perform_deliveries = true
  config.action_mailer.raise_delivery_errors = true
  config.action_mailer.default :charset => "utf-8"

Any ideas what could be going wrong or how I can troubleshoot this further?


Solution

  • I believe in Rails 5, the proper syntax would be

    UserNotifier.send_notification(user_notification, price).deliver_now

    ...and use full email as username.