25

I'm trying to create a custom email header to use the SendGrid api.

Here's what I'm doing - but its not working:

class Mailman < ActionMailer::Base
  default :from => "info@sample.com"

  def send_message(name, email, message)
    @name = name
    @email = email
    @message = message

    mail(:to => 'info@sample.com',
     :from => email,
     :subject => "Message from the site",
     :headers['X-SMTPAPI'] => "category: Drip Email"
    )
  end

end

Any help appreciated.

Thanks, Adam

Bohdan
  • 8,298
  • 6
  • 41
  • 51
Northband
  • 433
  • 1
  • 6
  • 11

4 Answers4

60

You can use the #headers method of ActionMailer, I've edited your example to show how:

class Mailman < ActionMailer::Base
  default :from => "info@sample.com"

  def send_message(name, email, message)
    @name = name
    @email = email
    @message = message

    headers['X-SMTPAPI'] = '{"category": "Drip Email"}'

    mail(
     :to => 'info@sample.com',
     :from => email,
     :subject => "Message from the site"
    )
  end

end

Alternatively, you can pass a hash as an argument (to the method #headers) too:

headers {"SPECIFIC-HEADER-1" => "value", "ANOTHER-HEADER" => "and so..."}

I hope this can help you, and if not you always can check the rails guides: http://edgeguides.rubyonrails.org/action_mailer_basics.html.

Rimian
  • 36,864
  • 16
  • 117
  • 117
Ricardo Valeriano
  • 7,533
  • 1
  • 24
  • 34
  • Thanks Ricardo - the answer was in front of my face. I had tried this and got it working. Then you posted which confirmed my solution. Thanks again. – Northband Aug 15 '11 at 15:24
5

I am using below code and works fine, just convert the hash to json with to_json

headers['X-SMTPAPI'] = { 
  category: "Weekly Newsletter",
  unique_args: { user_id: user.id } 
}.to_json
overallduka
  • 1,520
  • 19
  • 27
3

To use the unsubscribe groups in the suppression group functionality within sendgrid, I used the following syntax which worked.

headers['X-SMTPAPI'] = '{"asm_group_id": 1111}'
Pang
  • 9,564
  • 146
  • 81
  • 122
calilonghorn
  • 83
  • 10
2

The headers method requires valid JSON. So Ricardo's solution requires this line instead:

headers['X-SMTPAPI'] = '{"category": "Drip Email"}'
rnevius
  • 26,578
  • 10
  • 58
  • 86
Evan Moran
  • 3,825
  • 34
  • 20