Rich
Rich

Reputation: 122

How do I pass unique_args to the SendGrid::TemplateMailer API from Ruby on Rails

I've been implementing the sendgrid-ruby gem to send email via SendGrid. I'm using templates exclusively for my messages to send. I've got everything working on the outbound side using the TemplateMailer implementation.

This is the code:

    unique_args = {unique_args: {MyAuditNumber: "9999999"}}

    # Create a sendgid recipient list
    recipients = []

    recipient = SendGrid::Recipient.new(to_email)
    merge_vars.each do |mv|
      Rails.logger.debug(mv)
      recipient.add_substitution('*|' + mv["name"] + '|*', mv["content"])
    end

    recipients << recipient

    # Create a sendgrid template
    template = SendGrid::Template.new(template_id)

    # Create a client
    client = SendGrid::Client.new(api_key:  Rails.configuration.sendgridkey)
    mail_defaults = {
      from: from_email,
      from_name: from_name,
      to: to_email,
      to_name: to_name,
      bcc: bcc,
      html: ' ',
      text: ' ',
      subject: subject
    }

    mailer = SendGrid::TemplateMailer.new(client, template, recipients)        

    # send it
    lres = mailer.mail(mail_defaults)

The last thing I want to do is to add a unique identifier to each message that I send.

I've read both the SendGrid documentation as well as several questions and other articles ( how to get response of email sent using sendgrid in rails app to save in database http://thepugautomatic.com/2012/08/sendgrid-metadata-and-rails/ https://sendgrid.com/docs/Integrate/Code_Examples/SMTP_API_Header_Examples/ruby.html )

I can tell that I need to add unique_args to the smtp API. But what I can't figure out is how to pass that into the SendGrid routines.

I've tried things like:

recipient.add_to_smtpapi( unique_args )

and

recipient.add_to_smtpapi( unique_args.to_json )

and

mail_defaults = {
    smtpapi: unique_args,
    from: from_email,
... 

and

mail_defaults = {
    smtpapi: unique_args.to_json,
    from: from_email,
    ... 

These attempts generally result in an error message like: undefined method `add_filter' for "{\"unique_args\":{\"MyAuditNumber\":\"9999999\"}}":String

Does anyone know how to pass unique_args when using the TemplateMailer?

Upvotes: 0

Views: 1270

Answers (1)

Aguardientico
Aguardientico

Reputation: 7779

Based on gem documentation, what you should do is the following:

header = Smtpapi::Header.new
header.add_unique_arg("MyAuditNumber", "9999999")
mail_defaults = {
   smtpapi: header
   ...

Upvotes: 1

Related Questions