Send multiple emails with Sendgrid not working with X-SMTPAPI headers

883 Views Asked by At

I have been sending emails as follows:

def send
    ActionMailer::Base.mail(content_type: "text/html", from: "\"name\" <[email protected]>", to: "[email protected]", subject: "subject", body: "<h1>Hi</h1>" , priority: 2).deliver
end

And has been working well but now I want to send multiple emails because I need to handle 1000+ users. So I have been reading that I can accomplish this with X-SMTPAPI header so I tried this

  def send_all
    recipients = ["[email protected]", "[email protected]"]
    ActionMailer::Base.headers["X-SMTPAPI"] = { :to => recipients }.to_json
    ActionMailer::Base.mail(content_type: "text/html", from: "\"name\" <[email protected]>", to: "[email protected]", subject: "subject", body: "<h1>Hi</h1>" , priority: 2).deliver
  end

But Sendgrid just emails to [email protected] and not the headers. How can I fix this?

1

There are 1 best solutions below

0
On BEST ANSWER

I did it as follows, I don't think is the best solution because I'm loading Sendgrid config again but it worked

def send
    Mail.defaults do
      delivery_method :smtp, { :address   => 'smtp.sendgrid.net',
                               :port      => 587,
                               :domain    => 'sendgrid.com',
                               :user_name => 'yourSendGridUsername',
                               :password  => 'yourSendGridPassword',
                               :authentication => 'plain',
                               :enable_starttls_auto => true }
    end

        recipients = ["[email protected]", "[email protected]"]

        mail = Mail.deliver do
          header['X-SMTPAPI'] =  { :to => recipients }.to_json
          to "[email protected]"
          from '[email protected]'
          subject 'Ruby Example using X-SMTPAPI header'
          text_part do
            body 'You would put your content here, but I am going to say: Hello world!'
          end
          html_part do
            content_type 'text/html; charset=UTF-8'
            body '<b>Hello world!</b><br>Glad to have you here!'
          end
        end

end

Also I needed to require 'mail' in the class