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 "somebody@somewhere.com"
from "chad@awesome.com"
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
ActionMailer::Base.default "X-SMTPAPI" => '{"category": "Test Category"}'
This will NOT work:
config.action_mailer.default "X-SMTPAPI" => '{"category": "Test Category"}' # DOES NOT WORK
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.
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.
精彩评论