How to send an email with mail gem in ruby on rails

3.2k Views Asked by At

I am trying to send an email using mail gem. But Unfortunately it is not working. This is my controller.

    def create
      fn = params["firstname"]
      ln = params["lastname"]
      email = params["email"]
      file = params["file"]
      summery = params["summery"]
      email_body = "Hello\n This is Your favorite website.\nA I want to personaly say hi."
      mail = Mail.new do
        from '[email protected]'
        to email
        subject "Saying Hi"
        body email_body
      end
      mail.add_file(filename: file.original_filename, content: File.read(file.tempfile.path)) unless file.nil?
      mail.deliver!
      render json: {message: "A bug has been created", success: true}, status: 201
    end

This code is producing this error

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

However when I am installing the mailcatcher and configure my controller to send the mail to mailcatcher, I can see the email in my mailcatcher UI.

Mail.defaults do
 delivery_method :smtp, address: "localhost", port: 1025
end

Also I have add this two lines to my config/environment/development.rb

config.action_mailer.raise_delivery_errors = true 
config.action_mailer.perform_deliveries = true

From my searches I saw that some people are mentioning that dont send email on development mode, however on this case I really want to test the full capability.

Update

As @Uzbekjon and @SimoneCarletti suggested I change my code to use the ActionMailer. I created the a file in app/mailer/ and I am calling that from my controller.

  def create
    fn = params["firstname"]
    ln = params["lastname"]
    email = params["email"]
    file = params["file"]
    summery = params["summery"]
     email_body = "Hello\n This is Your favorite website.\nA I want to personaly say hi."
    WelcomeMailer.welcome(fn, ln, email, file, email_body).deliver_now
    render json: {message: "An Email has been send", success: true}, status: 201
  end

and This is my mailer

class WelcomeMailer < ActionMailer::Base
  default from: "[email protected]"

  def welcome(first_name, last_name, email, file, email_body)
    attachments["#{file.original_filename}"] = File.read("#{file.tempfile.path}")
 mail(
   to: email, 
   subject: 'Welcome to My Awesome Site', 
   body: email_body
 )
  end
end

However I am still getting the same error.

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

Answer

So I found the solution. Yes you need to use the ActionMailer. After that you need to go to the config/environments/development.rb , and modify and add these lines:

  config.action_mailer.raise_delivery_errors = true
  config.action_mailer.perform_deliveries = true
  config.action_mailer.delivery_method = :smtp
  # SMTP settings for gmail
  config.action_mailer.smtp_settings = {
    :address              => "smtp.gmail.com",
    :port                 => 587,
    :user_name            => "YOUR EMAIL",
    :password             => "YOUR Password",
    :authentication       => "plain",
    :enable_starttls_auto => true
  }

Also If Gmail complained about this:

Net::SMTPAuthenticationError - 534-5.7.9 Application-specific password required

Go to this link and let less secure application access Gmail.

Other configurations are available for other services like Yahoo. Just Google it.

2

There are 2 best solutions below

2
On

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

Looks like mail gem is trying to connect to your local smtp server on port 25. Most probably you don't have the service running and receiving connections on port 25.

To solve, install and run sendmail or postfix on your machine.

PS. Use ActionMailer.

0
On

You don't have a mail server running on port 25. You can install postfix and start the server using

sudo postfix start

And then modify the settings in config/environments/development.rb

config.action_mailer.delivery_method = :sendmail

Hope this helps.