【问题标题】:How to send multiple emails with SendGrid?如何使用 SendGrid 发送多封电子邮件?
【发布时间】:2012-09-07 00:39:48
【问题描述】:

如果只有一个用户,以下代码似乎可以工作,但会为多个用户截断电子邮件:

users.each do |user|
  mail(
    :to => user.email,
    :subject => 'Hi',
    :template_name => 'notification'
  ).deliver

这是发送几封电子邮件的正确方式吗?

  • Ruby on Rails 3.2.2
  • Heroku
  • 发送网格

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 heroku sendgrid


    【解决方案1】:

    向多个用户发送电子邮件:传递一个数组

    替换

    :to => user.email
    

    :to => users.map(&:email)
    

    更多 > rails guide

    【讨论】:

      【解决方案2】:

      如果对彼此隐藏电子邮件地址并不重要,您可以在逗号分隔的字符串中指定收件人。

      【讨论】:

        【解决方案3】:

        我想这就是你要找的东西:

        def my_mailer_method
          users = User.find({ ... })
        
          headers['X-SMTPAPI'] = { :to => users.to_a }.to_json
        
          mail(
           :to => "this.will@be.ignored.com",
           :subject => "Hi",
           :template_name => "notification"
          ).deliver
        end
        

        这会使用 SendGrid 的 SMTP API 向任意数量的收件人发送消息。您可以在the docs page 上找到更多信息。

        您可能还想看看sendgrid rails gem

        【讨论】:

        • 我得到的headers 未定义。
        • 您使用的是什么版本的导轨?查看 Action Mailer 文档了解详细信息guides.rubyonrails.org/…
        • 您确定您是从邮件程序而不是控制器中调用它吗?只要您使用 ActionMailer,它就可以工作
        • 是的。这是文件的顶部:class NotificationMailer < ActionMailer::Base default :from => 'Foobar <foo@example.com>' def send_notification user_id ... "
        • 对不起,我不这么认为。这是生产代码,我不拥有它。
        【解决方案4】:

        似乎问题在于Mailer的每个实例只能发送一封电子邮件。也许邮件对象超出范围并被垃圾收集器清理...

        有效的解决方案是在 Mailer 之外迭代用户,并为每个用户调用一次。它可能很慢,但无论如何它都应该在后台发生,所以没关系。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-11-08
          • 1970-01-01
          • 2011-02-08
          • 2016-02-28
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多