简体   繁体   English

Rails Actionmailer发送多个收件人

[英]Rails Actionmailer Sending Multiple Recipients

I'm having trouble getting Rails to send an email to multiple users at once. 我无法让Rails立即向多个用户发送电子邮件。 I am trying to send a notification to multiple venues signed up to my site when an Enquiry that matches them is approved. 我正在尝试向与我们网站签名的多个场所发送通知,以便与其匹配的查询获得批准。

A pending Enquiry has to be approved by admin. 待定查询必须由管理员批准。 The mailer is passed the @enquiry , which is when the email is triggered. 邮件通过@enquiry ,即触发电子邮件时。 Shown here in my Enquiries controller : 在我的Enquiries controller

def approve
    @enquiry.approve
    redirect_to [:admin, @enquiry], notice: 'Enquiry is approved.'
    SupplierMailer.new_enquiry(@enquiry).deliver
 end

In my Supplier_mailer.rb , I have this method: 在我的Supplier_mailer.rb ,我有这个方法:

    def new_enquiry(enquiry)
      @enquiry = enquiry
      @enquiry.venues.each do |venue|
        mail(to: venue.supplier.user.email, subject: 'You have a new enquiry')
      end
    end

Currently, it is only sending to 1 email address, so not looping properly. 目前,它只发送到1个电子邮件地址,因此不能正常循环。

Models: 楷模:

Enquiry 
  has_and_belongs_to_many :venues

Supplier
  has_many :venues
  has_one :user

What have I done wrong? 我做错了什么?

Thanks 谢谢

The new_enquiry method is supposed to build one email, which is then being send with deliver method. new_enquiry方法应该构建一个电子邮件,然后使用deliver方法发送。 The loop work correctly, however every time you're calling mail, you override its previous call, and the method returns the last call. 循环正常工作,但每次调用邮件时,都会覆盖其先前的调用,并且该方法返回最后一次调用。

Instead, first get the list of recipients, and use it as a to attribute 相反,首先获取收件人列表,并将其用作to属性

emails = @enquiry.venues.map {|venue| venue.supplier.user.email}
mail(to: emails, subject: 'You have a new enquiry')

If you are not happy with sending other emails to each other, you will need place Mailer action inside the loop: 如果您不喜欢彼此发送其他电子邮件,则需要在循环中放置Mailer操作:

def approve
  @enquiry.approve
  redirect_to [:admin, @enquiry], notice: 'Enquiry is approved.' 
  @enquiry.venues.each do |venue|
    SupplierMailer.new_enquiry(@enquiry, venue).deliver
  end
end

def new_enquiry(enquiry, venue)
  @enquiry = enquiry
  mail(to: venue.supplier.user.email, subject: 'You have a new enquiry')
end

Final option is pretty hacky, but provides best interface: 最终选项非常hacky,但提供最佳界面:

class SupplierMailer << ActionMailer::Base

  def self.new_enquiry(enquiry)
    @enquiry = enquiry
    mails = @enquiry.venues.map do |venue|
      mail(to: venue.supplier.user.email, subject: 'You have a new enquiry')
    end
    class << mails
      def deliver
        each(&:deliver)
      end
    end
    mails
  end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM