I have tried all kinds of configurations but still I can't send an email in my development environment from rails.
I installed mailutils to try this from the command line and it worked, I received the email (in spam of course): echo test | mail -s Subject user#example.com
Here's my config:
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = true # still no logs about emails
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true # I can't believe I have to add this option. Does it even exist? I found it on google.
config.action_mailer.smtp_settings = {
:enable_starttls_auto => true,
:address => "smtp.gmail.com",
:port => 587,
:domain => "gmail.com",
:authentication => :login,
:user_name => "some_user#gmail.com",
:password => "abc123",
}
And here's the code in the mailer:
class UserMailer < ActionMailer::Base
default :from => "root#ubuntu"
def test_email
Rails.logger.debug 'test_email'
mail(:to => 'user#example.com', :subject => "testing rails")
end
end
The controller:
class PagesController < ApplicationController
def home
UserMailer.test_email
end
end
development.log:
[2012-03-01 18:26:45.859] DEBUG [bb44dee806d73eb60ab3ae16297f5c02] [127.0.0.1] [GET] [http://myapp:3000/] test_email
[2012-03-01 18:26:45.888] INFO [bb44dee806d73eb60ab3ae16297f5c02] [127.0.0.1] [GET] [http://myapp:3000/] Rendered user_mailer/test_email (1.6ms)
[2012-03-01 18:26:45.898] INFO [bb44dee806d73eb60ab3ae16297f5c02] [127.0.0.1] [GET] [http://myapp:3000/] Rendered pages/home.html.erb within layouts/application (1.1ms)
[2012-03-01 18:26:46.815] INFO [bb44dee806d73eb60ab3ae16297f5c02] [127.0.0.1] [GET] [http://myapp:3000/] Completed 200 OK in 455ms (Views: 112.4ms)
I also tried using the console:
root#ubuntu:/srv/www/myapp# rails c
Loading development environment (Rails 3.2.1)
irb(main):001:0> UserMailer.test_email
=> #<Mail::Message:32110400, Multipart: false, Headers: <To: user#example.com>, <Subject: testing rails>, <Mime-Version: 1.0>, <Content-Type: text/html>>
UserMailer.test_email
Just creates a Mail::Message object. To actually send an email you need to do
UserMailer.test_email.deliver
(or starting with rails 4.2 deliver_now / deliver_later)
Regarding logging errors:
Just figured out by tinkering that a bang method counterpart exists for deliver, which throws an exception. Can be pretty useful to check if you just misspelled your username or password, or you just have some misconfigured settings.
UserMailer.test_email.deliver!
An updated answer for Rails 4.2 would be:
UserMailer.test_email.deliver_now!
The exclamatory mark is to raise an exception if there are any errors.
If you suspect it's your settings, try taking out the :domain. It worked for me a while ago.( Net::SMTPAuthenticationError in rails 3.1.0.rc5 when connecting to gmail )
But I don't see a :body option in the mail function. Perhaps that's the issue. Try sending it from rails console and see what happens. http://api.rubyonrails.org/classes/ActionMailer/Base.html#method-i-mail
Related
Seems to be the opposite problem to a lot of the questions on here. I've not been able to get the mailers working locally but then I deployed my app to Heroku and everything is fine.
No apparent errors when sending locally. Strangely though, I can have incorrect credentials locally and it will still appear to have sent ok. Almost as if it's not trying to deliver through smtp. I get a message like this in the console after sending:
UploadMailer#complete: processed outbound mail in 32.1ms Delivered mail 63ded40c98545_b9cbb90-440#Chriss-MacBook-Pro.local.mail (1238.6ms)
There's nothing in the SendGrid dashboard showing that it has reached their servers.
config/application.rb
...
config.action_mailer.delivery_method :smtp
ActionMailer::Base.smtp_settings = {
:user_name => 'apikey',
:password => ENV['SENDGRID_API_KEY'],
:address => 'smtp.sendgrid.net',
:domain => ENV['SENDGRID_DOMAIN'],
:port => 587,
:authentication => 'plain',
:enable_starttls_auto => true
}
Mailer and mailer view
class UploadMailer < ApplicationMailer
def complete
mail(to: 'me#myemail.com', subject: 'foo')
end
end
# app/views/upload_mailer/complete.html.erb
<h2>
Hello
</h2>
Environment
Ruby: 3.0.2 (rbenv)
Rails: 6.1.7.2
Tried on Mac and Windows(WSL)
Looks like I was just missing
config.action_mailer.perform_deliveries = true
in config/environments/development.rb
I upgraded my Rails app to 5.0.6 from 4.2.5. Now emails are not being sent by the Mail gem. I don't seem to be getting errors. I updated the Mail gem to the latest version with no luck. I am not sure what else to try.
I am running:
Rails 5.0.6
Ruby 2.3.0
Mail 2.7.0
controllers/send_email.rb
class SendEmail < ApplicationController
def initialize(to_address, from_address, email_pass, subject, body)
begin
options = {
:address => 'abc.prod.1234.secureserver.net',
:port => '465',
:domain => 'mydomain.com',
:user_name => from_address,
:password => email_pass,
:authentication => :login,
:ssl => true,
:openssl_verify_mode => 'none'
}
Mail.defaults do
delivery_method :smtp, options
end
Mail.deliver do
to to_address
from from_address
subject subject
body body
end
puts("\nSent message. From: #{from_address} To: #{to_address} \nMessage body: \n#{body}")
return true
rescue Exception => e
puts e.to_s
return false
end
end
end
Update:
I tried sending an email with Action Mailer as well. It says it sent in the console but it never gets delivered. I am using similar settings for Action Mailer as I am for the Mail gem.
config/environments/development.rb
config.action_mailer.smtp_settings = {
:address => 'abc.prod.1234.secureserver.net',
:port => '465',
:domain => 'mydomain.com',
:user_name => ENV['default_username'],
:password => ENV['default_password'],
:authentication => :login,
:ssl => true,
:openssl_verify_mode => 'none'
}
I am running this from the console:
EmailMailer.sample_email(UserEmail.first)
Console output:
Rendering email_mailer/sample_email.html.erb within layouts/mailer
Rendered email_mailer/sample_email.html.erb within layouts/mailer (0.1ms)
Rendering email_mailer/sample_email.text.erb within layouts/mailer
Rendered email_mailer/sample_email.text.erb within layouts/mailer (0.0ms)
EmailMailer#sample_email: processed outbound mail in 9.4ms
Solution:
I have some code that sends an email when there is an unknown error that I need to look at. When I updated Rails that code got caught in a loop that sent a bunch of emails really fast. That caused my server provider to mark the email account as a spam account. I am not sure why my original code was not showing any errors but when I ran EmailMailer.sample_email(UserEmail.first).deliver_now it gave me an error message that helped me track it down.
Well, wild guessing here but try this:
EmailMailer.sample_email(UserEmail.first).deliver_now
If you had Rails version below 4.2.1 it was not necessary to call deliver on the mail object for it to be delivered. From that point on you can operate on the mail object before delivering it, which can be now using
.deliver_now or later, using .deliver_later, which goes along with the use of ActiveJob or other queueing library.
A Rails 3.2.8 application developed with a gmail account as the "sending address".
When mail sending works my environment.rb file contains this:
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:domain => "gmail.com",
:authentication => :login,
:user_name => "accountname",
:password => "123456789"
}
I get this message in my application log:
EOFError (end of file reached):
when the above code is changed to what is shown below:
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
:address => "mail.company.com",
:port => 25,
:domain => "company.com",
:authentication => :login,
:user_name => "accountname",
:password => "123456789"
}
I can tell you I -am- able to send a manual email message to the email address
and see it arrive when using a email client such as ThunderBird, thus I know
the accountname#company.com is functional.
I don't understand how an end of file error comes into play.
I also cannot figure out how to get more information to appear in the log.
I look forward to reading a few suggestions of determining the cause of the End Of File.
Started POST "/sendInvites?locale=en&lot_id=18&user_id=17" for 99.99.99.99 at 2013-10-03 08:52:09 -0700
Processing by WaitingListsController#sendInvites as HTML
Parameters: {"authenticity_token"=>"uwz/6pW1rLPXR4gU3m3OwCmU0O3DSJ/haNM2/ai+OR8=", "locale"=>"en", "lot_id"=>"18", "user_id"=>"17"}
=======>>>> Beginning Send Invitation Process <<<<=======
=======>>>> just before the PassEmailer.requestApprovedWL IS called to send the invitation <<<<=======
>>>> Beginning ::: requestApprovedWL(user_info) <<<<=======
Rendered pass_emailer/requestApprovedWL.erb (0.9ms)
>>>> at the end of ::: requestApprovedWL(user_info) <<<<=======
Completed 500 Internal Server Error in 1718ms
EOFError (end of file reached):
app/controllers/waiting_lists_controller.rb:276:in `sendInvites'
For anyone still experiencing this issue, Whenever appears to default to Production. It is using your Production variables (or looking for them) while in your Development or Staging. Also, per the docs it does not load the Rails environment.
While you are in development or staging you must manually let schedule.rb know this. After finding the File.expand_path method here, the following is how I start my schedule.rb file:
require File.expand_path(File.dirname(__FILE__) + "/environment")
set :environment, Rails.env
set :output, Rails.root.join('log','cron.log')
This provides you the Rails environment and allows you to also set the path for logging.
I'd like to play around with sending mail from Rails in a development environment. My message is getting rendered (I can see it in the terminal I'm running rails console in).
In config/development.rb I have (yes, the port is really 26):
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
ActionMailer::Base.smtp_settings = {
:address => "mail.mydomain.com",
:port => 26,
:user_name => "me#mydomain.com",
:password => "removed",
:authentication => :login
}
I have in mailers/user_mailer:
class UserMailer < ActionMailer::Base
default from: "me#mydomain.com"
def send_an_email
mail(:to => "me#gmail.com", :subject => "Test from Rails")
end
end
I have a view that's getting rendered properly in views/user_mailer/send_an_email.text.erb. I'm calling UserMailer.send_an_email.deliver upon a page request.
Rails doesn't complain about my configuration. I see the message in the rails server console output. However, I never get an e-mail, and I don't see any error messages in the console output (as you can see above, raise_delivery_errors = true!.
Steve, by chance have you made sure you're calling the deliver method?
mail(:to => "me#gmail.com", :subject => "Test from Rails").deliver
I forgot to do that, and was quite confused by the lack of errors. :)
im trying to send a email with action mailer and it gives me a Timeout::Error (execution expired): even though in the console it says that the e mail is sent:
it shows
Sent mail to aldeirm2#gmail.com
then displayes the e mail that was sent then it shows the following error:
Timeout::Error (execution expired):
/usr/lib/ruby/1.8/timeout.rb:60:in `open'
/usr/lib/ruby/1.8/net/smtp.rb:551:in `do_start'
/usr/lib/ruby/1.8/net/smtp.rb:551:in `do_start'
/usr/lib/ruby/1.8/net/smtp.rb:525:in `start'
app/models/appointment.rb:10:in `tomorrows_appointments'
app/models/appointment.rb:8:in `each'
app/models/appointment.rb:8:in `tomorrows_appointments'
app/controllers/show_appointments_controller.rb:11:in `send_email'
-e:2:in `load'
-e:2
Rendered rescues/_trace (35.8ms)
Rendered rescues/_request_and_response (0.3ms)
Rendering rescues/layout (internal_server_error)
here is my settings:
config.cache_classes = false
config.whiny_nils = true
config.action_controller.consider_all_requests_local = true
config.action_view.debug_rjs = true
config.action_controller.perform_caching = false
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:enable_starttls_auto => true,
:address => "smtp.gmail.com",
:port => 587,
:domian => "gmail.com",
:authentication => :login,
:user_name => "username",
:password => "blablabla",
}
i also tried setting authentication to :plain and using username#gmail.com as the user_name with no hope.
any ideas
I saw a typo there: you wrote
:domian => "gmail.com",
instead of
:domain => "gmail.com",
SMTP requests seem to time out occasionally, probably depending on how long you've set for timeouts. The other problem you'll get is a delay in the web-app while the user waits for your server to communicate with Gmail's SMTP server.
I know gmail is a popular option for new rails apps, but I don't think it's a long-term solution since you have to send the mail through a particular gmail account which has daily sending limits. And even with other accounts, I have found that SMTP timeouts are a problem.
Now I am using SendGrid to send emails and have found that using sendgrid as a relayhost via postfix is the favourable option. This means the user gets a response from the web-app faster and the mail is queued through postfix and then sent via sendgrid (so no more timeouts!).
See here for sendgrid's postfix setup instructions:
http://wiki.sendgrid.com/doku.php?id=postfix
Then, in your rails environment, you just need something like the following:
config.action_mailer.delivery_method = :sendmail
config.action_mailer.sendmail_settings = {
:location => '/usr/sbin/sendmail',
:arguments => '-i -t'
}
In case anyone else has the same problem:
make sure that your firewall allows outgoing connections to port 587
For iptables, you can list all existing rules with:
sudo iptables -L
have a look here for the necessary rules.
If you're using an AWS instance, have a look at your security groups.