开发者

Rails 3 mail to users

开发者 https://www.devze.com 2023-02-11 18:05 出处:网络
I want send newsletter to all registered开发者_如何学Go users, but only the last user (in database) receive the mail.

I want send newsletter to all registered开发者_如何学Go users, but only the last user (in database) receive the mail.

 def letter(nletter)
   @nletter = nletter
   @users=Newsletter.all
   @users.each do |users|
    mail(:to => users.email, :subject => @nletter.subject)
   end
  end

Whats wrong?


If the code you showed us is in your Mailer class, it's because the mail method just sets various attributes on a Mail object. When you loop through all your users and call mail for each one, you're just resetting the subject and (more importantly) the recipient on a single Mail object. So when the function finishes and the Mail is sent out, the current recipient is the last user you set it to - the last user in your database.

You can get around this in two different ways. If it's a generic e-mail (everybody gets the same exact message), you can just pass an array of e-mail addresses as :to:

Note: As Josh points out in the comments, you'll pretty much always want to use :bcc instead of :to, so you don't end up broadcasting your entire mailing list.

def letter(nletter)
    @nletter = nletter
    @users=Newsletter.all
    mail(:to => @users.map(&:email), :subject => @nletter.subject)
end

But if each user gets a custom e-mail ("Hi, #{username}!" or somesuch), you'll have to create a new Mail object for each user. You can do this by calling Mailer.deliver_letter(nletter, user) for each user:

# Somewhere outside of your Mailer:
nletter = "...whatever..."
Newsletter.all.each do |user|
    Mailer.deliver_letter(nletter, user)
end

# And your mailer function would look like:
def letter(nletter, user)
    @nletter = nletter
    mail(:to => user.email, :subject => @nletter.subject)
end

Hope this helps!

0

精彩评论

暂无评论...
验证码 换一张
取 消