How to send multiple emails with SendGrid?

谁说我不能喝 提交于 2019-12-11 07:50:03

问题


The following code seems to work if there is one user, but truncate the email for multiple users:

users.each do |user|
  mail(
    :to => user.email,
    :subject => 'Hi',
    :template_name => 'notification'
  ).deliver

Is this the proper way to send a few emails?

  • Ruby on Rails 3.2.2
  • Heroku
  • SendGrid

回答1:


I think this is what you're looking for:

def my_mailer_method
  users = User.find({ ... })

  headers['X-SMTPAPI'] = { :to => users.to_a }.to_json

  mail(
   :to => "this.will@be.ignored.com",
   :subject => "Hi",
   :template_name => "notification"
  ).deliver
end

This sends a message to any number of recipients use the SendGrid's SMTP API. You can find further information on the docs page.

You might also want to take a look at the sendgrid rails gem




回答2:


To send email to multiple users: pass an array

Replace

:to => user.email

with

:to => users.map(&:email)

more > rails guide




回答3:


If it is not important for you to hide email addresses from each other, you can specify recipients in a comma delimited string.




回答4:


It seems that the problem is that each instance of the Mailer can only send one email. Perhaps the mail object is falling out of scope and getting cleaned up by the garbage collector...

The solution that worked was to iterate over the users outside of the Mailer, and call it once for each user. It may be slow but it should happen in the background anyway so it's fine.



来源:https://stackoverflow.com/questions/12414506/how-to-send-multiple-emails-with-sendgrid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!