2016-04-24 75 views
0

我一直在實現sendgrid-ruby gem通過SendGrid發送電子郵件。我正在使用專門用於發送消息的模板。我使用TemplateMailer實現了所有工作。如何將unique_args從Ruby on Rails傳遞到SendGrid :: TemplateMailer API

這是代碼:

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) 

我想做的最後一件事是一個唯一的標識符添加到我發送的每條消息。

我讀過兩個SendGrid文檔以及幾個問題和其他物品( 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

我可以告訴大家,我需要unique_args添加到SMTP API。但是我想不出的是如何將它傳遞給SendGrid例程。

我已經試過了諸如:

recipient.add_to_smtpapi(unique_args) 

recipient.add_to_smtpapi(unique_args.to_json) 

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

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

次這些嘗試通常導致這樣的錯誤消息: 「{\」 未定義的方法`的add_filter」 unique_args \ 「:{\」 MyAuditNumber \ 「:\」 9999999 \ 「}}」:字符串

沒有人知道如何在使用TemplateMailer時傳遞unique_args?

回答

1

基於gem documentation,你應該做的是:

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