如何在Rails中发送给多个收件人?

时间:2015-07-18 23:18:11

标签: ruby-on-rails ruby email

我正在学习如何使用Ruby on Rails,我在向多个用户发送电子邮件时遇到了困难。我创建了一个简单的rails应用程序我实际发送的电子邮件代码,但这两封电子邮件不会复制到同一封电子邮件中。换句话说,User1不会看到User2电子邮件,反之亦然。我的问题是

“如何让User1和User2在收到电子邮件时互相看到对方?”

以下是我的user_mailer.rb文件中的代码:

def email1(user1, user2)
    @user1 = User.find_by(email: "myyahooemail@yahoo.com")
    @user2 = User.find_by(email: "mygmailemail@gmail.com")
    mail(to: "#{@user1.email}, #{@user2.email}",
        subject: 'Testing sending emails to 2 people',
        body: 'The email should have both users in the TO field')
end

以下是我的users_controller.rb文件中的代码:

def send_email1
   UserMailer.email1(@user1, @user2).deliver
   redirect_to users_path
end

以下是我的routes.rb文件中的代码:

get 'sendemail1' => 'users#send_email1'

2 个答案:

答案 0 :(得分:2)

实际上,您只需将电子邮件列表设置为:to密钥。

mail(to: [@user1.email, @user2.email],
      subject: 'Testing sending emails to 2 people',
      body: 'The email should have both users in the TO field')

http://guides.rubyonrails.org/action_mailer_basics.html#complete-list-of-action-mailer-methods

答案 1 :(得分:0)

您可以使用cc:键来实现您想要的效果。 As explained here

 mail(to: "#{@user1.email}",
      cc: "#{@user2.email}"
      subject: 'Testing sending emails to 2 people',
      body: 'The email should have both users in the TO field')

obs: cc:可以使用字符串或地址数组。