jollyOldSaintNixon
jollyOldSaintNixon

Reputation: 13

How to avoid a 500 Internal Server Error when using the Rails ActionMailer on Heroku

I am trying to send an email to a user upon sign up in my web app, which is built with Rails in the back end and React-Redux on the front end. I used a gem called letter_opener when testing on a local server, and everything seemed to work fine. When I tried it live on Heroku, I got back a 500 error, and I'm not sure what is wrong.

I tried reading the ActionMailer docs, but it didn't seem to mention any issue like this.

The method in the UserMailer:

def welcome_email(user)
    @user = user
    mail(to: @user.email, subject: "Welcome")
end

Relevant code in UsersController:

def create
   # ...
   email = UserMailer.welcome_email(@user)
   email.deliver_now   # This line throws the error
   # ...
end

The error from the Heroku logs:

Errno::ECONNREFUSED (Connection refused - connect(2) for "localhost" port 25):

I expected to the email to be delivered, or at least to have a more informative error message. I am not sure why Rails is looking at localhost's port 25.

Upvotes: 0

Views: 797

Answers (2)

user11831257
user11831257

Reputation:

Chris is right, Heroku doesn't provide an SMTP server and you've to use an Addon. I'll further add on how you can proceed with using sendgrid addon which is free upto much extent.

First, goto your Heroku app -> Enable sendgrid addon. Then you'll be given sendgrid credentials. Keep them safe.

In your config/environments/production.rb add:

config.action_mailer.delivery_method = :smtp
config.action_mailer.default_url_options = { host: "your-domain.com", protocol: 'https' }

Then in your config/environment.rb file add:

...
# Initialize the Rails application.
Rails.application.initialize!

# Add sendgrid support
if Rails.env.production?
  ActionMailer::Base.smtp_settings = {
    :user_name => "sendgrid_username",
    :password => "sendgrid_password",
    :domain => "your-domain.com",
    :address => "sendgrid_hostname",
    :port => 3000, # sendgrid_port
    :authentication => :plain,
    :enable_starttls_auto => true
  }
end

Change the credentials above as required. Also consider using ENV variables for above credentials.

Upvotes: 0

Chris
Chris

Reputation: 137215

I am not sure why Rails is looking at localhost's port 25.

ActionMailer defaults to localhost:25, and you probably only changed your development configuration.

Errno::ECONNREFUSED (Connection refused - connect(2) for "localhost" port 25)

Heroku doesn't provide an SMTP server, and there certainly won't be one on localhost. Use an email addon or some other third-party mail service of your choice.

You'll probably have to modify config/environments/production.rb to use whatever mail service you choose.

Upvotes: 1

Related Questions