Chad
Chad

Reputation: 1888

Rails3 Global Header Inclusion

I've got a few ActionMailer classes that send out a number of emails.... I want to globally include a header across every single email sent from this Rails app:

Here is a method with the header manually included:

class GeneralNotification < ActionMailer::Base

    def test_email(emails)
        subject "Welcome to my email!"
        recipients "[email protected]"
        from "[email protected]"

        headers(
            "X-SMTPAPI" => '{"category": "Test Category"}'
        )
    end

end

I want that X-SMTPAPI header globally included without modifying every mailer method..

What's the best way to do this?

Thanks!

Chad

Upvotes: 1

Views: 1373

Answers (3)

nicholaides
nicholaides

Reputation: 19489

ActionMailer::Base.default "X-SMTPAPI" => '{"category": "Test Category"}'

This will NOT work:

config.action_mailer.default "X-SMTPAPI" => '{"category": "Test Category"}' # DOES NOT WORK

Upvotes: 2

idlefingers
idlefingers

Reputation: 32037

It's a shame it looks like you're not using Rails 3 which has a new ActionMailer::Base.default method which you could use to set this in application.rb. Edit: I didn't notice you said it was rails 3 in the title. In that case, add this to your config block in config/application.rb:

config.action_mailer.default "X-SMTPAPI" => '{"category": "Test Category"}'

For Rails 2.x, you've got two options; use a plugin such as action_mailer_callbacks to define a before_filter style call in an initializer to set the headers, or monkey-path actionmailer to get it to do what you want. Neither are particularly elegant solutions, I'm afraid.

Here's a good example of someone wanting to do the same thing, and how you could monkey-patch AM, but with the from address rather than headers.

Upvotes: 1

Ryan Bigg
Ryan Bigg

Reputation: 107718

You could define a superclass which defines this method to simply set the headers:

class MailBase < ActionMailer::Base
  def test_email
    # sendgrid headers go here
  end
end

Then you make your classes inherit from this class:

class MailSub < MailBase
  def test_email
    # email stuff goes here
    super
  end
 end

The super method call here will call the test_email method in the superclass, thereby adding the Sendgrid headers.

Upvotes: 0

Related Questions