Hi,
I’ve been struggling with my Rails app that cannot send an email. The monitoring log says it can’t connect to port 25.
2023-03-31T03:19:25.975 app[3287454ea55785] sin [info] [e77a58a2-f629-4544-8c7b-1724ed63f663] Errno::ECONNREFUSED (Connection refused - connect(2) for 127.0.0.1:25):
2023-03-31T03:19:25.975 app[3287454ea55785] sin [info] [e77a58a2-f629-4544-8c7b-1724ed63f663]
2023-03-31T03:19:25.975 app[3287454ea55785] sin [info] [e77a58a2-f629-4544-8c7b-1724ed63f663] app/mailers/user_mailer.rb:13:in `welcome_email'
2023-03-31T03:19:25.975 app[3287454ea55785] sin [info] [e77a58a2-f629-4544-8c7b-1724ed63f663] app/controllers/root_controller.rb:10:in `create'
Inside root_controller.rb
class RootController < ApplicationController
def create
# Get the email parameters from the request parameters
to = params[:to]
subject = params[:subject]
body = params[:body]
# Use ActionMailer to create and send the email
email = UserMailer.welcome_email.deliver_now
# Check if the email was successfully sent or not
if email.delivered?
flash[:notice] = "Email sent successfully to #{to}"
else
flash[:alert] = "Failed to send email to #{to}"
end
# Redirect to the root URL
redirect_to root_url
end
end
Inside the user_mailer.rb
class UserMailer < ApplicationMailer
default from: 'notifications@example.com'
def welcome_email
recipient_email = 'mytest_xxx@gmail.com'
# Use the `mail` gem to send the email
mail = Mail.new do
from 'your_email@example.com'
to recipient_email
subject 'Test email'
body 'This is a test email sent from my Rails app.'
end
mail.deliver!
redirect_to root_path, notice: 'Email sent successfully!'
end
end
I checked these threads and they said fly.io already allowed SMTP port 25:
This is what’s inside my fly.toml:
[[services]]
internal_port = 25
protocol = "tcp"
[[services.ports]]
port = 25
[[services.ports]]
handlers = ["tls"]
port = 465
[[services.ports]]
port = 587
[[services]]
internal_port = 3000
processes = ["app"]
protocol = "tcp"
[services.concurrency]
hard_limit = 25
soft_limit = 20
type = "connections"
[[services.ports]]
force_https = true
handlers = ["http"]
port = 80
[[services.ports]]
handlers = ["tls", "http"]
port = 443
[[statics]]
guest_path = "/rails/public"
url_prefix = "/"
I even tried to use sendgrid, edited the production.rb but nothing helps so I reverted it.
I also inserted the MAIL_HOST env:
# env | grep -i mail
MAIL_HOST=smtp.sendgrid.net