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 'someone#gmail.com'
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: "someone#yahoo.com"
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.
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.
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.
Related
I am trying to implement sendgrid into my backend api rails system so that when a user signs up I can send them a welcome email. After making a post request and handling user creation, I get this verification:
UserMailer#send_sign_up_email: processed outbound mail in 43.5ms
Sent mail to *******#gmail.com (185.8ms)
Date: Wed, 28 Feb 2018 16:54:05 -0800
From: *******#gmail.com
To: *******#gmail.com
Message-ID: <5a974f2d39c92_c5b2abcd76769fc423e0#albert-VirtualBox.mail>
Subject: Welcome to BottlesTonight albert jin!
Mime-Version: 1.0
Content-Type: text/html;
charset=UTF-8
Content-Transfer-Encoding: quoted-printable
My code looks exactly like in this link https://sendgrid.com/docs/Integrate/Frameworks/rubyonrails.html.
This looks all fine and well, but the email is just not sending (I put stars here for the email but I actually put in my email, and I used another one of emails as the default for sending). There is no email in my outbox or inbox.
However, now that I think about it, I never "logged in" with my email or entered the password, so the application shouldn't have access to send emails with my email. I also never did anything with the api key that I made on my sendgrid account. Furthermore, for the environment.rb file, I wasn't sure what to put in domain, so I put gmail.com. These all seem kinda sketchy to me, I think the tutorial doesn't contain everything. Does anyone know how to configure this? I've been stuck on it for a while.
Edit:
I tried doing it on production and it is not working. Here is more info:
My production.rb looks like this:
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.default_url_options = { :host => ENV['DEFAULT_HOST'] }
ActionMailer::Base.smtp_settings = {
:address => 'smtp.sendgrid.net',
:port => '587',
:authentication => :plain,
:user_name => ENV['SENDGRID_USERNAME'],
:password => ENV['SENDGRID_PASSWORD'],
:domain => 'heroku.com',
:enable_starttls_auto => true
}
I have a heroku sendgrid add on. I have set the heroku config vars. In my registrations controller I merely added the line:
UserMailer.send_sign_up_email(#current_user).deliver
My mailer class looks like:
def send_sign_up_email(user)
#user = user
mail(to: #user.email, subject: "Welcome! #{#user.first_name}")
end
However, when I sign up on my website, the user gets added to the database but the email is not sending. Does anyone know why, or how I can debug?
I would suggest to remove all config for ActionMailer from your environment files (i.e. files under /config/environments), except following ones
# Don't care if the mailer can't send.
config.action_mailer.perform_caching = false
# Reference: http://stackoverflow.com/a/20770131/936494
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
Then create an initializer /config/initializers/mail_config.rb and add following code to it:
TEST_ENVS = %w(test)
FILESYSTEM_ENVS = TEST_ENVS + %w(development)
# =========== DELIVERY METHOD SETTING
delivery_method = case Rails.env.to_sym
when :production, :staging, :experimental
:sendmail
when :test
:test
else
:smtp
end
ActionMailer::Base.delivery_method = delivery_method
# =========== SMTP SETTINGS
ENVS_TO_USE_GMAIL_CONFIG = %w(development test)
gmail_config = {
address: 'smtp.gmail.com',
port: 587,
domain: 'gmail.com',
user_name: ENV['MAIL_USER_NAME'],
password: ENV['MAIL_PASSWORD'],
authentication: :plain,
enable_starttls_auto: true
}
if :smtp == delivery_method
use_gmail_config = ENVS_TO_USE_GMAIL_CONFIG.include?(Rails.env)
smtp_settings = ( use_gmail_config ? gmail_config : {} )
ActionMailer::Base.smtp_settings = smtp_settings
end
# =========== DEFAULT URL OPTIONS
default_url_options_settings = Settings.default_url_options
host = default_url_options_settings.host
port = default_url_options_settings.port
protocol = default_url_options_settings.protocol
default_url_options = {}
default_url_options[:host] = host if host.present?
default_url_options[:port] = port if port.present?
default_url_options[:protocol] = protocol if protocol.present?
ActionMailer::Base.default_url_options = default_url_options
The Settings object is available as part of using config gem. If you do not want to use that gem for configuring env-specific values then you can just hard-code them in the initializer and try it.
My /config/settings.yml looks like
default_url_options:
host: ''
port: ''
protocol: ''
and my /config/settings/development.yml looks like
default_url_options:
host: 'localhost'
port: '3000'
Having a centralized mailer config helps in diagnosing mailer settings related issues in quick manner.
First try it for Gmail account and if it works you can be sure that sending email works. Just make sure in your Gmail account Less Secure Apps setting is enabled.
I'm trying to send an email from rails and capture it using thunderbird.
This is my mailer:
def hello_world
from = 'bruno#localhost'
subject = 'Hello World'
to = 'bruno#localhost'
main to: to, from: from, subject: subject
end
I followed this instructions to configure thunderbird locally and it is working fine.
https://gist.github.com/raelgc/6031274
I'm not sure how to config rails.
What should I put here in development.rb ?
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => "localhost",
:port => 25,
:domain => "localhost"
}
As #aniket-rao suggested: Use Mailcatcher which does all this. No need to install a local postfix server and fiddle with inboxes. From the docs:
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://127.0.0.1:1025 instead of your default SMTP server, then check out http://127.0.0.1:1080 to see the mail that's arrived so far.
In your Rails environment use this configuration to send email to Mailcatcher:
# use Mailcatcher
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = { address: 'localhost', port: 1025 }
Your email will be visible on the local web app running on port 1080.
Try this
mail(to: to, from: from, subject: subject)
I've read all the other SO answers, but I still can't fix this.
Given my RewardMailer has the following email defined:
# A test email to check up on the configurations
def test_mail
#recipients = 'aminshahgilani#gmail.com'
#from = 'postmaster#sandboxXXXXXXXXXXXXXXXXX.mailgun.org'
#subject = 'test from the Rails Console'
#body = 'This is a test email'
end
And that my config/environments/development.rb file contains:
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'smtp.mailgun.org',
port: 587,
domain: 'sandboxXXXXXXXXXXXXXXXXX.mailgun.org',
user_name: 'postmaster#sandboxXXXXXXXXXXXXXXXXX.mailgun.org',
password: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
authentication: :plain
}
And when I check from the Rails console, I confirm the configuration with:
Rails.application.config.action_mailer
=> {:perform_deliveries=>true, :raise_delivery_errors=>true, :delivery_method=>:smtp, :smtp_settings=>{:address=>"smtp.mailgun.org", :port=>587, :domain=>"sandbox0574dfb215d14874ac51fb9f9052131b.mailgun.org", :user_name=>"postmaster#sandboxXXXXXXXXXXXXXXXXX.mailgun.org", :password=>"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", :authentication=>:plain}, :assets_dir=>"/home/gilani/Sandbox/mailman/public", :javascripts_dir=>"/home/gilani/Sandbox/mailman/public/javascripts", :stylesheets_dir=>"/home/gilani/Sandbox/mailman/public/stylesheets", :preview_path=>"/home/gilani/Sandbox/mailman/test/mailers/previews", :asset_host=>nil, :relative_url_root=>nil}
Why does the following not deliver my email? Or show any error for it at all
RewardMailer.test_mail().deliver_now
RewardMailer#test_mail: processed outbound mail in 0.1ms
=> nil
I checked with my Mailgun logs as well, nothing. The logs are empty!
You are not calling mail method in your test_mail.
I would like to use Sendgrid to manage outgoing emails from a 3.2.2 version rails app I am developing with the help of a friend. She has email working from within the app using gmail, on her local/dev build. I need sendgrid up and running.
I cannot even get it to work locally.
From my development.rb file
config.action_mailer.default_url_options = { :host => 'localhost:3030' }
config.action_mailer.smtp_settings = {
:user_name => ENV['EMAIL_USERNAME'],
:password => ENV['EMAIL_PASSWORD'],
:domain => 'myapplicationdomain.com',
:address => 'smtp.sendgrid.net',
:port => 587,
:authentication => 'plain',
:enable_starttls_auto => true
}
config.action_mailer.delivery_method = :smtp
Then I have a variable file in the root of my application that includes the following:
export EMAIL_USERNAME=sendgridusername
export EMAIL_PASSWORD=sendgridpassword
export MAIL_TO=report#myapplicationdomain.com
Here is the code from my mailer
class StatusMailer < ActionMailer::Base
default from: "reports#myapplicationdomain.com"
def status_report(report)
#greeting = "Hello"
#report = report
if ENV['MAIL_TO']
email = ENV['MAIL_TO'] if ENV['MAIL_TO']
else
email = #report.user.email
end
#statuses = #report.statuses
#reviewers = #report.user.reviewers
bcc = []
#reviewers.each do |reviewer|
bcc.append(reviewer.email)
end
#bcc = bcc
mail(to: email, bcc: bcc, subject: 'Status Report')
end
end
Am I missing some other setting? What about the MAIL_TO field in the variable, I am not certain what that should be set to, or if it even needs to be declared.
Is there another file that I should be editing? I had this working several days ago, but functionality somehow slipped away :0
Rails server says that emails were sent, but sendgrid has no record; nor are the emails being received by addresses on the distribution list.
Thank you in advance for any assistance.
Do you have the following settings in your config/environments/development.rb?
config.action_mailer.raise_delivery_errors = true
config.action_mailer.perform_deliveries = true
If not, add them to your config file and restart your server.
Update:
This error suggests that you're not authenticated. Are you sure the values of your ENV['EMAIL_USERNAME'] and ENV['EMAIL_PASSWORD'] variables are present/correct?
This post:
Sendgrid / email sending issues in Ruby on Rails (hosted on Heroku)
Got me up and running. The key being putting the SMTP and sendgrid information in the environment.rb file.
I can't explain exactly why that made the difference, but it did.
I am running a Rails app and using Mailcather gem as an SMTP service. It was said that it can catch all outgoing emails, however I've done making correct settings in config/environments/development.rb, testing it to send email, but no email catched in either 127.0.0.1:1080 and localhost:1080. But the email was sent and received tho. I've tried all of the possible configurations. Here is my config/development.rb
config/development.rb
Ror::Application.configure do
# Mailer
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default_url_options = { :host => '127.0.0.1:3000' }
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = { :address => "127.0.0.1", :port => 1025 }
end
Here is my user_mailer.rb
class UserMailer < ActionMailer::Base
default :from => "aaaaaaaaa#gmail.com"
def registration_confirmation(user)
#user = user
mail(:to => user.email, :subject => "Registered")
end
end
I used the registration_confirmation() method to check whether user is registered or not via email. But none of of the email popped up in mailcatcher. I did install it under rvm. I did test install it both with wrapper and without wrapper but the result still the same. Bottom line is, it is able to send emails outside, but can't receive email inside. Or any notifications. Did I miss something? Any advice or corrections would be appreciated. Thanks
You call the mail method like this:
UserMailer.registration_confirmation(user).deliver