MKK
MKK

Reputation: 2753

How can I use ActionMailer correctly when I want to use BCC?

I've spent time for research, and this is what I could think of.
But, I'm pretty sure there's something wrong with this part @users_emails += user.email

Can anyone fix my code to make it work?

controllers/users_controller.rb

def send_all_at_once

    @notification_users = User.where("users.country_id=?", 36)

    @notification_users.each do |user|
        @users_emails += user.email
    end

    @subject = "Test subject"
    @body = "Test body"

    CallMailer.call_email(@users_emails, @subject, @body).deliver

end

app/mailers/call_mailer.rb

class CallMailer < ActionMailer::Base

    default :from => "[email protected]"

    def call_email(@users_emails, @subject, @body)
        mail(:to => "[email protected]",
            :bcc => @users_emails,
            :subject => @subject,
            :body => @body) do |format|
            format.html
            format.text
        end
    end 

end

views/call_mailer/call_email.html.erb

<html>
    <head>
        <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
    </head>
    <body>
        <p>
            You received a message.
        </p>
        <p>
            Subject: <%= raw @subject %>
        </p>
        <blockquote>
            <p>
                <%= simple_format(@body) %> 
            </p>
        </blockquote>
        <p>
            From: <%= link_to root_url,root_url %>
        </p>
    </body>
</html>

Upvotes: 0

Views: 527

Answers (1)

zeantsoi
zeantsoi

Reputation: 26193

Normally, you'd pass your bcc'ed email addresses as an array:

mail(:to => "[email protected]",
    :bcc => ['[email protected]', '[email protected]', '[email protected]'],
    :subject => @subject,
    :body => @body)

However, since @user_emails is already an array of emails, you should forgo the enclosing brackets and pass the instance variable directly:

mail(:to => "[email protected]",
    :bcc => @users_emails,
    :subject => @subject,
    :body => @body)

The following depicts the correct syntax for creating an array of user emails:

@notification_users.each do |user|
    @users_emails << user.email
end

UPDATE:

As commenter mbratch astutely points out, the shovel operator in the above example can be substituted by the plus-equals (+=) operator in the following manner:

@user_emails = []
@notification_users.each do |user|
    @users_emails += [user.email]
end

UPDATE 2:

You can bypass the controller loop altogether by mapping user emails directly within your invocation of the mail function:

mail(:to => "[email protected]",
    :bcc => User.where("users.country_id=?", 36).map(&:email),
    :subject => @subject,
    :body => @body)

Upvotes: 1

Related Questions