使用ActionMailer通过电子邮件发送多个用户

时间:2012-01-30 10:52:21

标签: ruby-on-rails ruby-on-rails-3.1 actionmailer

这是一个全新的问题,但我想知道是否有人可以协助设置邮件。我有一个模型'用户'并在其下面嵌套一个'联系人'模型,(与has_many / belongs_to关系)。

我现在正在尝试创建一个邮件程序,该邮件程序将由用户页面上的特定操作(创建帖子)触发,并将通过电子邮件发送属于该用户的所有联系人。但我无法破解邮件程序所需的语法 - 我已尝试将收件人设置为@user.contacts.all,并且我已尝试使用this solution循环访问它们。有人能以最干净的方式提出建议吗?

这是我到目前为止的代码:

Posts controller:

  after_create :send_contact_email

  private

  def send_contact_email
    ContactMailer.contact_email(self).deliver
  end

contact_mailer(这是我最近的尝试,取自RoR网站 - 我怀疑这不是最好的方法......)

class ContactMailer < ActionMailer::Base 

  def contact_email(user)
    recipients    @user.contacts.all
    from          "My Awesome Site Notifications <notifications@example.com>"
    subject       "Welcome to My Awesome Site"
    sent_on       Time.now
    body          {}
  end
end

然后是contact_email.html.erb的基本消息。

目前的错误是:

  

UsersController#create_post

中的NoMethodError      

nil的未定义方法`contacts':NilClass。

非常感谢您提供的任何建议!

*更新*

按照Baldrick的建议,contact_email方法现在是:

class ContactMailer < ActionMailer::Base 
  default :to => Contact.all.map(&:contact_email),
          :from => "notification@example.com"

  def contact_email(user)
    @user = user
    mail(:subject => "Post added")
  end
end

2 个答案:

答案 0 :(得分:1)

有一个错字:您在@user方法中使用的是user而不是contact_email。 它可能不是唯一的问题,但至少它是错误消息"undefined method 'contacts' for nil:NilClass "

的原因

<强>更新

因此,使用正确的语法,从默认选项中删除:to,并使用您的用户的联系人在contact_email方法中进行设置:

class ContactMailer < ActionMailer::Base 
  default :from => "notification@example.com"

  def contact_email(user)
    @user = user
    mail(:subject => "Post added", :to => user.contacts.map(&:contact_email),)
  end
end

答案 1 :(得分:1)

class ContactMailer < ActionMailer::Base 
  default :to => Contact.all.map(&:contact_email),
          :from => "notification@example.com"

  def contact_email(user)
    recipients = user.contacts.collect(&:contact_email).join(',')
    mail(:subject => "Post added", :to => recipients)
  end
end