10

When sending mail through actionmailer, the actionmailer gets a response from the SMTP server, when its ok, or when its wrong. Is there a way to retrieve this response after sending a mail? Also when no errors are thrown by the SMTP server?

Our qmail mail server throws a handler id which we want to use for tracing e-mails.

As an example, the server response is this :

250 ok 1308235825 qp 17832

Steve Smith
  • 5,146
  • 1
  • 30
  • 31
Martijn Bakker
  • 138
  • 1
  • 8

2 Answers2

8

Set return_response: true in the smtp settings and call message.deliver! instead of deliver. This returns the SMTP server response, a Net::SMTP::Response, which contains the server response you're looking for.

If you need a log of all responses from the connection with the server, not just the final result, you'll need to dig into Net::SMTP.

tribalvibes
  • 2,097
  • 3
  • 25
  • 30
  • This break some test for me, because it change the class of returned object. How should be change/override the returning value in tests when return_response is true ? – duleorlovic Jun 09 '14 at 16:42
  • @duleorlovic that depends on the purpose of your tests doesn't it. basically if you call the bang form `deliver!` you should handle a `Net::SMTP::Response` as the result. `result.success?` is a bult-in you could use. See http://ruby-doc.org/stdlib-2.0.0/libdoc/net/smtp/rdoc/Net/SMTP/Response.html – tribalvibes Jun 10 '14 at 19:48
  • Why isn't `return_response` on by default? – mwfearnley Nov 24 '16 at 08:21
2

Looking at the the source you can define an observer:

in base.rb

  # Register an Observer which will be notified when mail is delivered.
  # Either a class or a string can be passed in as the Observer. If a string is passed in
  # it will be <tt>constantize</tt>d.
  def register_observer(observer)
    delivery_observer = (observer.is_a?(String) ? observer.constantize : observer)
    Mail.register_observer(delivery_observer)
  end

So you could use some code like this in an initialization file:

class MailObserver
  def self.delivered_email(message)
    logger_info "Sent Message: #{message}"
  end
end

ActionMailer::Base.register_observer(MailObserver)

That will log sent mail and you can see if you can get the headers or response from the sent mail object.

Devin M
  • 9,636
  • 2
  • 33
  • 46
  • Well i want all responses from the server, even when there is no error. Our qmail mail server throws a handler id which we want to use for tracing e-mails. – Martijn Bakker Jun 17 '11 at 07:34