How to dynamically set unsubscribe link in sendgrid using ruby on rails

匆匆过客 提交于 2019-11-30 23:05:49

You're on the the right track, however to use the SendGrid SMTP API, you'll add the header to each email, rather than to your settings. In your SMTP settings you'll store your (at a minimum) user_name, password, address, the SendGrid Docs, detail configuration further. With ActionMailer you would configure it as follows:

ActionMailer::Base.smtp_settings = {
  :user_name => 'sendgridusername',
  :password => 'sendgridpassword',
  :domain => 'yourdomain.com',
  :address => 'smtp.sendgrid.net',
  :port => 587,
  :authentication => :plain,
  :enable_starttls_auto => true
}

Once you've configured ActionMailer you'll need to set up your UserNotifier class to look something similar to the following. Each individual method will set the X-SMTPAPI header:

class UserNotifier < ActionMailer::Base
  default :from => "bob@example.com"

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

    headers['X-SMTPAPI'] = '{"filters":{"subscriptiontrack":{"settings":{"enable":1,"text/html":"Unsubscribe <%Here%>","text/plain":"Unsubscribe Here: <% %>"}}}}'

    mail(
      :to => 'george@example.com',
      :from => email,
      :subject => 'Example Message'
    )
  end

end

Note that the X-SMTPAPI header is in JSON, if you wish to convert a Ruby object into JSON, you'll need to use the JSON gem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!