Errno::ECONNREFUSED: Connection refused - connect(2) for action mailer - ruby-on-rails

I have been working with rails since a long. Now I am facing a small issue in the ActionMailer. I want to send an email when user gets registered to confirm his registration.
I am able to send email in the development mode but where as not in the production mode.
the exception Errno::ECONNREFUSED: Connection refused - connect(2) is coming everytime when deliver method is called.
I have written the following code.
My SMTP config looks:
config.action_mailer.default_url_options = { :host => "localhost:3000" }
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.smtp_settings = {
:openssl_verify_mode => OpenSSL::SSL::VERIFY_NONE,
:ssl => true,
:enable_starttls_auto => true, #this is the important stuff!
:address => 'smtp.xxxx.xxx',
:port => xxx,
:domain => 'xxxxxx',
:authentication => :plain,
:user_name => 'xxxxxxx#xxx.xxx',
:password => 'xxxxxxxxx'
}
In the controller, I have written the following:
def confirm_registration_in_c
#user = User.find_by_email(asdf123#gmail.com)
if #user
UserMailer.confirm_registration(#user).deliver
end
end
In my user_mailer.rb :
class UserMailer < ActionMailer::Base
default from: "from#example.com"
def confirm_registration(user)
#user = user
#user_name = #user.name
email = #user.email
mail(:to => email, :subject => "Reset your password")
end
end
I am able to send email in the development mode in my local host, but I am not able to send the email in the dedicated server.
Can anybody help me please?

In my situation, I encountered similar problems when I was trying to making through a sending-email Rails app tutorial, the Heroku logs kept telling my that
......
Errno::ECONNREFUSED (Connection refused - connect(2) for "localhost" port 25):
......
After I compared my code with author's code, I got to find out that I had not setup my ActionMailer configurations in the config/environments/production.rb file.
Then I came to realized that I just had my config/environments/development.rb configured for sending-email, but I had not done it for my config/environments/production.rb.
So you may check it when your app's behavior difers between development and production.

Be sure you have configured your port correctly. I switched from gmail in development (port 587) to sending from my local server in production and was getting this error till I corrected the port to the one my server uses (port 25).

My problem is not identical to this question, but I feel many would found this thread via google.
If you use external SMTP service like sendgrid and has set up ActionMailer accordingly, yet it still gives this error:
Errno::ECONNREFUSED: Connection refused - connect(2) for "localhost" port 25
You may be passing config hash with String key, which are ignored. Keys must be symbols!
This may happen if it is de-serialized, what I did is to ensure keys are symbols:
config.action_mailer.smtp_settings = get_smtp_setting.symbolize_keys

for production you cant write
config.action_mailer.default_url_options = { :host => "localhost:3000" }
add production url for host, like,
config.action_mailer.default_url_options = { :host => "http://www.yourdomain.com" }

There is another reason for this error:
Errno::ECONNREFUSED: Connection refused - connect(2) for "localhost" port 25
It should be looked at SENDMAIL service on your server:
Is SENDMAIL installed?
Is SENDMAIL running?
I had this error due to the stopped SENDMAIL.
Good luck!

I had a similar issue with SendGrid and repeated Errno::ECONNREFUSED: Connection refused - connect(2) ) Finally I modified the way smtp settings were set by changing the definition within /config/environments/production.rb
from:
ActionMailer::Base.smtp_settings = {
to:
config.action_mailer.smtp_settings = {
this did the trick.

I just tracked down a similar problem while trying to deploy wordpress with Capistrano.
cap aborted!
Errno::ECONNREFUSED: Connection refused - connect(2) for "{my-ip-address}" port {my-ssh-port}
I would also get this similar error:
Tasks: TOP => git:create_release
(See full trace by running task with --trace)
The deploy has failed with an error: #<Errno::ECONNREFUSED: Connection refused - connect(2) for "my-ip-address" port {my-port}>
It turns out it was an issue with concurrent SSH sessions as my server runs Fail2Ban. To solve that I simply did the following:
Edit the jail that contains SSH configurations
$ sudo nano /etc/fail2ban/jail.local
look for [SSH] and set enabled = false
then find [ssh-ddos] and set enabled = false
Remember to restart Fail2Ban after your changes and open-ssh (if thats what your using)
$ sudo service fail2ban reload
$ sudo /etc/init.d/ssh reload
Its worth noting that the connection would be refused at different steps (tasks) in the deployment. For example after a reboot and a quick bundle exec cap production deploy:check everything appeared fine. Then I tried to deploy and received the same error, but during the execution of a different task. I also use UFW which I disabled and reenabled without issues. UFW was not the cause of the above problem.
I had a similar problem after I solved this. It was an issue with the current directory permissions. That's over here.

You may see a similar error message when using turbo_stream in rails 7 (or while doing the rails 7 demo).
If you do, run this and everything should work:
redis-server
More info here.

Related

Net::SMTPAuthenticationError (535-5.7.8 Username and Password not accepted.) Openshift production only

I'm trying to send an email through gmail/actionmailer, it works perfectly on my local development box, but when I try and run the same code on production server it gives me an Net::SMTPAuthenticationError (535-5.7.8 Username and Password not accepted.. I think this is because gmail is rejecting my login credentials from an unknown server.But I'm not sure! How do I fix it?
Background:
I am using the figaro gem, and I am setting my environment variables on the openshift server with: rhc set-env. I've checked that the environment variables are set on the server.
The questions here, here, and here are all good, but have not done anything to solve my problem. My problem is a bit different because it only shows up on my server, everything works fine on my local box.
Development:
In development mode, I have the figaro gem installed, and I have my configuration file stored in application.yml which is not checked into git.
Here are it's contents:
## config/application.yml
# Add configuration values here, as shown below.
gmail_username: 'PLACE_HOLDER_EMAIL#gmail.com'
gmail_password: 'PLACE_HOLDER_PASSWORD'
In my controller:
## PLACEHOLDER_controller.rb
def create
#placeholder = Placeholder.new(placeholder_params)
respond_to do |format|
if #placeholder.save
puts "SENDING..."
puts "Sending to: #{ENV['gmail_username']}..."
PLACEHOLDERMailer.placeholder_email(some, params).deliver
puts "SENT!"
end
end
Production:
## /config/environments/production.rb
# SMTP
config.action_mailer.delivery_method = :smtp
# SMTP settings for gmail
config.action_mailer.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:user_name => "#{ENV['gmail_username']}",
:password => "#{ENV['gmail_password']}",
:authentication => "plain",
:enable_starttls_auto => true
}
Production:
I push the code to my OpenShift repo with git, the server restarts, ostensibly everything is fine. Except that when I create a new placeholder, I get a 500 back from the server.
Here is the log output:
>> rhc tail -a MY_APP
SENDING...
Sending to: "PLACE_HOLDER_EMAIL#gmail.com"... ## This is the correct email! It's clearly pulling the proper values from ENV.
INFO -- : Rendered placeholder_mailer/placeholder_email.text.erb (0.1ms)
INFO -- :
Sent mail to 9739069711#txt.att.net (132.3ms)
INFO -- : Completed 500 Internal Server Error in 224ms
FATAL -- :
Net::SMTPAuthenticationError (535-5.7.8 Username and Password not accepted. Learn more at
):
app/controllers/placeholders_controller.rb:35:in `block in create'
app/controllers/placeholders_controller.rb:29:in `create'
Which says that the username and password were not accepted. Now, I know that I have the correct username and password. I'm fairly certain that's not the issue. I suspect that (as mentioned in the linked questions) smtp.gmail.com is rejecting my login from an unknown server.
Before anyone suggests it, I have already:
Disabled Two Factor Authentication
Tried creating an application specific password and using that instead. (Didn't work, I've now switched back to the regular account password)
Enabled access to less secure applications.
TL;DR
I'm trying to send an email from the server. When I run it on the server it gives me: Net::SMTPAuthenticationError (535-5.7.8 Username and Password not accepted.. I think this is because gmail is rejecting my login credentials from an unknown server. How do I fix it?
It turns out that gmail blocks you temporarily if you try to access it programatically more than once every ten minutes. I suppose I must have did this while I was testing the functionality.

On Heroku when sending mail through action mailer gives error

I created rails g mailer from this reference site. It is working fine on local there is no error. I also added {config.action_mailer.delivery_method = :smtp} with did smtp settings and deployed on heroku,
but now its giving error
We're sorry, but something went wrong. Please help.
For sending mail in production environment, do following thing -
1. In config/environments/production.rb
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'smtp.mail.com',
port: 587,
domain: 'YOUR_DOMAIN_GOES_HERE',
user_name: 'YOUR_EMAIL_ID_GOES_HERE',
password: 'YOUR_PASSWORD_GOES_HERE',
authentication: 'plain',
enable_starttls_auto: true }
and deploy this change on heroku and if you again found any error there, please check -
heroku stack:set cedar-14
then again deploy on heroku - git push heroku master.
Try it.
The Heroku platform itself doesn’t provide an email service. You need to use external services. Read their documentation about how to send emails from your app.

Rails email with gmail smtp error "Errno::ECONNREFUSED - No connection could be made because the target machine actively refused it."

When attempting to send email from within my Rails 3 app in development mode on my local machine, I received the following error:
Errno::ECONNREFUSED in RemindersController#create
No connection could be made because the target machine actively
refused it. - connect(2)
After spending several hours sifting through similar questions on SO and blog posts with none of the proposed solutions working, here is the solution I finally arrived at:
tl;dr
Change your smtp port setting to 25, instead of 587 which is in all the tutorials & docs.
Detailed answer (for humans):
Step 1. Go watch railscast #206 then come back. I'll wait.
Step 2. Get extra aggravated at how easy he makes it seem even though you're getting ridiculous errors.
Step 3. Go to app/config/environments/development.rb and change line 17 from false to true. This will show you where things are getting messed up.
# config.action_mailer.raise_delivery_errors = false
config.action_mailer.raise_delivery_errors = true
Step 4. Still in app/config/environments/development.rb add the following code before the last end statement. (You no longer need the app/config/initializers/setup_mail.rb file created in the screencast when you are in development mode and can safely delete it.)
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => "smtp.gmail.com",
:port => 25,
:user_name => "<your username>#gmail.com",
:password => "<your password>",
:authentication => "plain",
:enable_starttls_auto => true
}
Notes:
Notice we did not specify the :domain setting like in the tutorials
and it works fine.
Notice also that we used your_username #gmail.com as the
:user_name setting.
If you use 2-step authentication for your gmail account you will have
to generate a special app-specific
password. disclaimer: I did not try this.
AND THE BIG FAT ELEPHANT IN THE ROOM, is that we used :port => 25
NOT 587 despite the fact that nearly every single tutorial, SO question, and the rails guide only suggest 587. Granted, this could
possibly be because my work blocks port 587? I have no idea. But
this was my key problem no one solved for me. The way to find out if
this is your problem is to use telnet. If you are on windows you
have to first enable telnet by following these
instructions.
Then go to your command prompt and type telnet smtp.gmail.com 587
if it works you will get a response like 220 mx.google.com ESMTP
pi6sm33274849wic.3 - gsmtp. Otherwise it will tell you it could not
connect, in which case you can try it on a different port eg. telnet
smtp.gmail.com 25.
I hope this helps some lost soul.
I encountered this issue whilst reading through Agile Web Development with Rails 4 chapter 13, and it turned out that any email config stuff added to config/environment.rb was being ignored, despite the book indicating that "shared" email settings for all environments could be added there.
Moving the settings into config/environments/development.rb (and restarting the Rails server) fixed the issue, allowing emails to be sent on either port 25 or port 587 without any problems:
# development.rb
Rails.application.configure do
# ...blah blah blah...
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'smtp.gmail.com',
port: 587,
user_name: 'yourusername#gmail.com',
password: 'yourpassword',
authentication: 'plain',
enable_starttls_auto: true
}
end
NOTE: development.rb didn't contain any email-related settings originally, so I don't think that the values in environment.rb were being superseded - it's more like they simply had no effect. The I18n.default_locale = 'en-GB' line in environment.rb was working, though, so it's not like the file was being completely disregarded...

Rails Mailer "Net::OpenTimeout: execution expired" Exception on production server only

I am using Ruby MRI 2.0.0 and Rails 3.2.12 on a Ubuntu 12.04 TLS VPS and attempting to setup email notifications in my app. It was working fine a few days ago, but not anymore. My web host is OVH.
My SMTP settings:
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
ActionMailer::Base.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:user_name => 'sender#gmail.com',
:password => 'secret',
:authentication => 'plain',
:enable_starttls_auto => true
}
Using RAILS_ENV=production rails console:
class MyMailer < ActionMailer::Base
def test_email
sender = "sender#gmail.com"
receiver = "receiver#example.com"
mail from: sender, to: receiver, subject: "Hello!", body: "World!!"
end
end
=> nil
MyMailer.test_email.deliver
The output:
Net::OpenTimeout: execution expired
from ~/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/net/smtp.rb:540:in `initialize'
from ~/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/net/smtp.rb:540:in `open'
from ~/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/net/smtp.rb:540:in `tcp_socket'
from ~/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/net/smtp.rb:550:in `block in do_start'
from ~/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/net/smtp.rb:549:in `do_start'
from ~/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/net/smtp.rb:519:in `start'
from ~/.rvm/gems/ruby-2.0.0-p0#mygemset/gems/mail-2.4.4/lib/mail/network/delivery_methods/smtp.rb:144:in `deliver!'
from ~/.rvm/gems/ruby-2.0.0-p0#mygemset/gems/mail-2.4.4/lib/mail/message.rb:2034:in `do_delivery'
from ~/.rvm/gems/ruby-2.0.0-p0#mygemset/gems/mail-2.4.4/lib/mail/message.rb:229:in `block in deliver'
from ~/.rvm/gems/ruby-2.0.0-p0#mygemset/gems/actionmailer-3.2.12/lib/action_mailer/base.rb:415:in `block in deliver_mail'
from ~/.rvm/gems/ruby-2.0.0-p0#mygemset/gems/activesupport-3.2.12/lib/active_support/notifications.rb:123:in `block in instrument'
from ~/.rvm/gems/ruby-2.0.0-p0#mygemset/gems/activesupport-3.2.12/lib/active_support/notifications/instrumenter.rb:20:in `instrument'
from ~/.rvm/gems/ruby-2.0.0-p0#mygemset/gems/activesupport-3.2.12/lib/active_support/notifications.rb:123:in `instrument'
from ~/.rvm/gems/ruby-2.0.0-p0#mygemset/gems/actionmailer-3.2.12/lib/action_mailer/base.rb:413:in `deliver_mail'
from ~/.rvm/gems/ruby-2.0.0-p0#mygemset/gems/mail-2.4.4/lib/mail/message.rb:229:in `deliver'
from (irb):28
from ~/.rvm/gems/ruby-2.0.0-p0#mygemset/gems/railties-3.2.12/lib/rails/commands/console.rb:47:in `start'
from ~/.rvm/gems/ruby-2.0.0-p0#mygemset/gems/railties-3.2.12/lib/rails/commands/console.rb:8:in `start'
from ~/.rvm/gems/ruby-2.0.0-p0#mygemset/gems/railties-3.2.12/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'2.0.0p0 :029 >
I tried the following:
The exception_notification gem was added to the setup a few days ago. I tried to comment its line in Gemfile as well as its matching configuration, and run bundle install. After restarting the server, the issue is still present, even if I delete and recreate the gemset.
Test it out on a virtual machine (exact same setup as the VPS including iptables rules): works
Disable iptables rules: does not work
Manually connect to Gmail from the VPS using openssl: works (so this is not a firewall issue - see here: Connecting to smtp.gmail.com via command line);
Enable IMAP in Gmail account options (it was disabled): does not work
Use a different Gmail account: does not works
Replace Ruby 2.0.0 by Ruby 1.9.3
Upgrade to Rails 3.2.13
Does someone have a possible clue as to how to resolve this issue?
Thanks!
First, do a direct connection with Telnet:
telnet smtp-relay.sendinblue.com 587
Trying 94.143.17.4...
This is the basic connection troubleshooting, and works with any provider or port. Replace SendBlue and the 587 port with your actual hostname/port.
If you get this error:
telnet: Unable to connect to remote host: Connection timed out
then, the problem isn't in Rails.
In the above example, the problem is in the port number. Services like sendinblue or mandrill (I believe gmail too) don't support the 587 port anymore. "2525" is the new "587".
If you get a timeout on telnet, check this:
hostname: it's usual to people use "smtp.sendinblue.com" instead of "stmp-relay.sendinblue.com", "smtp.mandrill.com" instead of "smtp.mandrillapp.com", and so on.
port: 587 is obsolete. Major providers are now using 2525 instead. Major cloud services like DigitalOcean, block outgoing connections to 587 as well. That's why it will work on your pc, but not on your server. I won't even mention the "25" port, which is even more obsolete than 587. Also, some providers use specific non-default ones instead or imap.
ipv6 vs ipv4: check if the hostname is being translated as a IPv4. If not, try to disable IPv6 (see others answers).
hostname resolution: run the same telnet command on a machine that you know the email sending is working. Check if the translated ip (the xxx part of "Trying xxx...") is the same. If not, go back to your server and replace the hostname with this ip. If works, change your /etc/hosts and force the hostname to use this ip.
I probably had the same issue, my production application didn't send mails although everything in development was working fine. I also got the "Net::OpenTimeout" error.
My problem was that i was using a Google server in production, and it blocks ports 25, 465 and 587 on outbound connections.
Since I was using Mandrill for sending mails, I was able to switch the connecting port from 587 to 2525 and everything is okay now.
Here is also a temporary fix that may come in handy while waiting for your hosting provider to fix the issue:
Add the following lines to /etc/sysctl.conf:
#disable ipv6
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
net.ipv6.conf.lo.disable_ipv6 = 1
Now reload the sysctl service using the following command:
sudo sysctl -p
Now the apps are able to send emails again.
You can always know if IPv6 is enabled calling
cat /proc/sys/net/ipv6/conf/all/disable_ipv6
from terminal. Two possible answers:
0 => IPv6 is enabled;
1 => IPv6 disabled.
From: https://serverfault.com/questions/512744/timeout-error-in-all-my-apps-for-every-call-to-smtp-servers
The issue was due to an IPv6 misconfiguration on the production server and has now been fixed.
You can configure Ubuntu to prefer IPv4 over IPv6. This way you will be able to send emails and access IPv6-only sites. Edit /etc/gai.conf and uncomment the following line:
precedence ::ffff:0:0/96 100
Try this, if all above fails
I got it solved by adding this in application.rb under config
require 'net/http'
require 'openssl'
require 'resolv-replace'
If you (or the internet in this case as this question is the first result for this problem) are testing Mailgun, you may get this error if you're using port 25. Change the port to 587 worked, even though their docs/quick links says 25 is ok to use.
I added these to /etc/gai.conf in CentOS7 and it worked.
label ::1/128 0
label ::/0 1
label 2002::/16 2
label ::/96 3
label ::ffff:0:0/96 4
precedence ::1/128 50
precedence ::/0 40
precedence 2002::/16 30
precedence ::/96 20
precedence ::ffff:0:0/96 100
http://blog.asiantuntijakaveri.fi/2014/12/prefer-ipv4-over-ipv6-on-centos-6.html:title

Rails ActionMailer problems on Mac

I've been working on learning to use Rails the last couple days and I've run into something that I haven't been able to solve with Google.
So I'm just creating a basic contact form that sends an email. Everything seems to be working ok in testing, which tells me that the form is working, and ActionMailer was implemented correctly, however, I'm having trouble configuring ActionMailer. I'm running OSX 10.6.2. I have postfix running and have verified that it's running using telnet localhost 25. When I try to use the form I get a "Connection refused" error.
This is my current configuration:
config.action_mailer.smtp_settings = {
:address => 'localhost',
:port => 25
}
I thought I might need to set :domain but I'm kind of confused on what that should be set to in this situation.
My life has been roughly 100x easier running :sendmail on my mac as a delivery method on my mac rather than :smtp, you might want to try giving that a shot. In this answer, I am assuming that you just want mail delivery on your Mac and don't actually care how it works.
The other thing I do, if I'm going to be connected to the net all the time on a project, is to configure my outgoing ActionMailer-originated mail to go through gmail rather than my local mac.
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
:enable_starttls_auto => true,
:address => "smtp.gmail.com",
:port => 587,
:domain => "example.com",
:authentication => :plain,
:user_name => "address#example.com",
:password => "secret"
}
This is for a custom domain called example.com that is set up on google apps for domains. You can also just create a gmail account and send things through there. (By changing all instances of example.com to gmail.com)
You need to start the postfix daemon. you can tell if your port is open by typing in a terminal
telnet localhost 25
which will try to connect to the 25 port. It wont connect if postfix isnt running, if it does, hit ctl-] to stop the connection and 'quit' to quit telnet.
If it doesn't connect, you need to start the postfix daemon:
sudo launchctl start org.postfix.master
and then try to connect with telnet. it should connect. Now you are ready to send emails from your ActionMailer class.
sudo launchctl stop org.postfix.master
stops the postfix daemon
I followed this guide and everything works correctly. Mainly:
sudo postfix start
then
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => "localhost",
:port => 25
}
Does it work if you substitute '127.0.0.1' for 'localhost' to see if this is an IPv4 vs. IPv6 thing or an issue with your resolver?
Another great way of sending and verifying mails when development is using enter link description here.
Quote from their website:
MailCatcher runs a super simple SMTP server which catches any message sent to it to display in a web interface. Run mailcatcher, set your favourite app to deliver to smtp://localhost:1025 instead of your default SMTP server, then check out http://localhost:1080 to see the mail that's arrived so far.
It intercepts mail to all recipients and hence makes it really easy to check all mail in one place.

Resources