如何使用 ruby​​ on Rails 在 sendgrid 中动态设置取消订阅链接

2023-11-24

我正在使用 sendgrid 发送邮件。大约有 20 个邮件模板。

我已经在 sendgrid 应用程序的设置中设置了取消订阅模板“订阅跟踪”.

我的要求是不同的邮件模板的取消订阅链接有不同的文本。

目前只有一项静态unsubscribe link按照 sendgrid 应用程序中的设置“订阅跟踪”来了。

任何人都可以帮助我如何动态设置我的取消订阅链接user_mailer class.

我点击了这个链接使用 sendgrid XSMTPAPI 标头在邮件中提供取消订阅链接。但我不知道如何在 ruby​​ 中实现它。

下面是我在我的代码中尝试过的代码user_mailer class yet.

    def abuse_notification(post,current_user,eventid)
     headers['X-SMTPAPI'] = '{"filters":{"subscriptiontrack":{"settings":{"enable":1,"text/html":"Unsubscribe <%Here%>","text/plain":"Unsubscribe Here: <% %>"}}}}'.to_json()
  UserNotifier.smtp_settings.merge!({:user_name => "[email protected]"})

    @recipients  = "[email protected]"
    @from        = "xxxx"
    @subject     = "Report Abuse Notification"
    @sent_on     = Time.now
    @body[:user] = current_user
    @body[:event] = post

  end

您的方向是正确的,但是要使用 SendGrid SMTP API,您需要将标头添加到每封电子邮件中,而不是添加到您的设置中。在您的 SMTP 设置中,您将(至少)存储您的user_name, password, address, the 发送网格文档,进一步详细配置。和ActionMailer您可以按如下方式配置它:

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

配置 ActionMailer 后,您需要设置您的UserNotifier类看起来类似于以下内容。每个单独的方法都会设置X-SMTPAPI header:

class UserNotifier < ActionMailer::Base
  default :from => "[email protected]"

  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 => '[email protected]',
      :from => email,
      :subject => 'Example Message'
    )
  end

end

请注意,X-SMTPAPI标头采用 JSON 格式,如果您希望将 Ruby 对象转换为 JSON,则需要使用JSON gem.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 ruby​​ on Rails 在 sendgrid 中动态设置取消订阅链接 的相关文章

随机推荐