Why can't I send emails from Rails in production using a typical ActionMailer config?

67 Views Asked by At

I had a look at 535-5.7.8 Username and Password not accepted in Rails Mailer using Gmail and their problem is similar to mine, and I'm not sure they got it resolved.

I set up 2fa with an app password on a gmail account.

I want to send account-activation and password-reset emails through that gmail account to our users.

Here's my configuration:

config.action_mailer.smtp_settings = {
    :address => 'smtp.gmail.com',
    :port => 587,
    :domain => 'appname.com',  # has not gone on line yet - does that matter?
    :user_name => ENV['GMAIL_APP_USER'],    # "[email protected]"
    :password =>  ENV['GMAIL_APP_PASSWORD'],
    :authentication => :plain,
    :enable_starttls_auto => true,
    :openssl_verify_mode => 'none',
  }
config.action_mailer.perform_caching = false
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.default_url_options = { :host => 'appname.com' } 
# again, it's not on line yet, but it seems like I need something
# I haven't found what exactly this field is for

Whenever I hit the endpoint that would deliver an email, I get this in my logs:

I, INFO -- : Delivered mail [email protected] (287.1ms)
   [ ("MYHOSTNAME" is my actual hostname, but it's not mentioned in the above config) ]
I, INFO -- : Completed 500 Internal Server Error in 587ms (ActiveRecord: 16.5ms | Allocations: 18589)
F, FATAL -- :
Net::SMTPAuthenticationError (535-5.7.8 Username and Password not accepted. Learn more at
):

app/models/user.rb:35:in `send_activation_email'
app/controllers/account_activations_controller.rb:18:in `create'

From another post I could see that the "Learn more" error message is from gmail/google, and basically that post told me to use an app password.

I am using an app password, and have enabled 2FA on that email account.

The app password as delivered consists of 4 sets of four-letter-sequences, each followed by one space. Whether I leave the spaces in or not, I get the same result.

Is there something I need to do to let gmail know this is an app password, and I haven't leaked the actual account password?

I've read a couple of dozen posts on this subject, and all say the same thing. Leading me to think I've failed to do something obvious.

The code's in github, but the credentials aren't. So if anyone's interested in digging in that deep, please get in touch with me and I'll explain how I feed the creds to the Rails app.

1

There are 1 best solutions below

0
Eric On

Figured it out...

Do not use double-quotes around your secrets in your .rbenv-vars file, or they'll become part of the actual string.

And you can pull the spaces out of the google app passwords. They separate them into four pieces so you can yell it across the room to your co-worker and not lose track of where you are.