adnan hajar
adnan hajar

Reputation: 47

sending email not working with rails

I built an example app to try to make the mailer work. The app is hosted on https://blooming-brushlands-80122.herokuapp.com, and the source code is here. Here's my config associated with action mailer:

config.action_mailer.delivery_method = :sendmail
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default_options = {from: '[email protected]'}

and for sending the mailer

 def create
      @user = User.new(user_params)

      respond_to do |format|
        if @user.save

          # Sends email to user when user is created.
          ExampleMailer.sample_email(@user).deliver

          format.html { redirect_to @user, notice: 'User was successfully created.' }
          format.json { render :show, status: :created, location: @user }
        else
          format.html { render :new }
          format.json { render json: @user.errors, status: :unprocessable_entity }
        end
      end
    end

The app does not send emails to users.

Does anyone have any idea why?

Upvotes: 0

Views: 637

Answers (1)

bkunzi01
bkunzi01

Reputation: 4561

This answer assumes you're using the free sendgrid Addon from Heroku since I see you're using sendmail. To add it just log into heroku and add it as a free resource. Since you didn't specify whether or not your trying to send emails locally or in production I added configs for both. In your config/environment/development.rb file you should do the following to send from your local:

  config.action_mailer.delivery_method = :smtp  #Yours used sendmail, change to this.
  config.action_mailer.perform_deliveries = true #Needed if this is dev env. file
  ActionMailer::Base.smtp_settings = {
    :address        => 'smtp.sendgrid.net',
    :port           => '587',
    :authentication => :plain,
    :user_name      => ENV['KUNZIG_SENDGRID_USERNAME'],
    :password       => ENV['KUNZIG_SENDGRID_PASSWORD'],
    :domain         => 'localhost:3000',
    :enable_starttls_auto => true
  }

Obviously replace the username and password with your own env. variables assigned by Heroku. Heroku's config. vars can be found under the settings tab. just click the "reveal" button.

Your environment/production.rb file would be something like:

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

Notice the only change is the domain name and environment variables since these are set automatically by Heroku when you add Sengrid as an addon. Also, change your deliver call in your controller to deliver_now so we know it's not a problem with your background worker config.

Upvotes: 1

Related Questions