ruby-on-railssendgridsendgrid-ruby

Attempting to send multiple custom_args in SendGrid Ruby mailer


In Rails 7 api, I am attempting to A/B test email subject lines using custom_args object in the header SendGrid seems not to be seeing the custom args. Category is conveyed as expected. Here is the send_email action in the mailer:

  def send_email(daily_content)

    # Get A/B test subject line and metadata
    ab_test = SubjectLineAbTestingService.new(@user).generate_subject_line_test
    daily_content.subject = ab_test[:subject]

    mail(
      to: @user.email,
      subject: ActionView::Base.full_sanitizer.sanitize(daily_content.subject).to_s
    ) do |format|
      format.html

      # Add SendGrid headers
      headers['X-SMTPAPI'] = {
        "category": ["daily_stats"],
        "custom_args": {
          "variation_id": ab_test[:variation],
          "total_variations": ab_test[:total_variations],
          "user_id": @user.id.to_s
        }
      }.to_json
    end
  end

I tried the following but still only categories show as a filter in the SG dashboard.


  def send_email(daily_content)
    puts "daily_stats_mailer: sending email to #{@user.email}"
    @daily_content = daily_content

    # Get A/B test subject line and metadata
    ab_test = SubjectLineAbTestingService.new(@user).generate_subject_line_test
    daily_content.subject = ab_test[:subject]

    mail(
      to: @user.email,
      subject: ActionView::Base.full_sanitizer.sanitize(daily_content.subject).to_s,
      "X-SMTPAPI" => {
        "category": ["daily_stats"],
        "custom_args": {
          "variation_id": ab_test[:variation],
          "total_variations": ab_test[:total_variations],
          "user_id": @user.id.to_s
        }
      }.to_json
    ) do |format|
      format.html
    end
  end

Solution

  • In reading the Docs, I think I now understand what you are trying to accomplish and you are simply using the wrong concept.

    When building the "X-SMTPAPI" header the additional information you are looking for is called unique_args not custom_args

    Please change this to:

    mail(
      to: @user.email,
      subject: ActionView::Base.full_sanitizer.sanitize(daily_content.subject).to_s,
      headers: {"X-SMTPAPI" => {
        category: ["daily_stats"],
        unique_args: {
          variation_id: ab_test[:variation],
          total_variations: ab_test[:total_variations],
          user_id: @user.id.to_s
        }
      }}
    )
    

    If you wanted to send custom_args you would do so outside of the header e.g.

    mail(
      to: @user.email,
      subject: ActionView::Base.full_sanitizer.sanitize(daily_content.subject).to_s,
      headers: {"X-SMTPAPI" => {category: ["daily_stats"]}},
      custom_args: {variation_id: ab_test[:variation]}
    )