how do you test that Rails mailer credentials are valid?

╄→гoц情女王★ 提交于 2021-02-17 19:46:29

问题


I've got a mailer sending through a GMail account, and I want to test that ActionMailer can actually log in to GMail's SMTP server with the credentials I've given it. What's the best way to test this?


回答1:


It's not a full-stack solution, but you can check that the server authentication happens correctly by using Net::SMTP directly. The Mail gem that Rails 3 uses to send ActionMailer emails uses Mail like so (with your ActionMailer.smtp_settings):

  #line 96 of mail-2.2.7/lib/mail/network/delivery_methods/smtp.rb
  smtp = Net::SMTP.new(settings[:address], settings[:port])
  if settings[:enable_starttls_auto]
    smtp.enable_starttls_auto if smtp.respond_to?(:enable_starttls_auto) 
  end

  smtp.start(settings[:domain], settings[:user_name], settings[:password],
   settings[:authentication]) do |smtp|
     smtp.sendmail(message, envelope_from, destinations)
     # @Mason: this line need not be included in your code. SMTP#start throws
     # a Net::SMTPAuthenticationError if the authentication was not successful.
     # So just putting this call to #start with an empty block in a method and
     # calling assert_no_raise Net::SMTPAuthenticationError should do the trick.
     # The empty block is necessary so that the connection gets closed.
     # Reference #{rubydir}/lib/ruby/1.8/net/smtp.rb for more info.
  end

Looks like ActionMailer::Base.smtp_settings is accessible too:

  settings = ActionMailer::Base.smtp_settings

Putting that in your test and commenting out the line spoken of above should have a working example for you.




回答2:


smtp = Net::SMTP.new settings[:address], settings[:port]
smtp.enable_starttls_auto if settings[:enable_starttls_auto]
smtp.start(settings[:domain]) do
  expect {
    smtp.authenticate settings[:user_name], settings[:password], settings[:authentication]
  }.to_not raise_error
end

Calling authenticate will raise a Net::SMTPAuthenticationError if the authentication fails.

Otherwise, it will return a Net::SMTP::Response, and calling status on the response will return "235".



来源:https://stackoverflow.com/questions/5085974/how-do-you-test-that-rails-mailer-credentials-are-valid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!