LoginSignup
14
5

More than 5 years have passed since last update.

SendGrid Web API v3をrubyから使って、複数人にメールを送る方法

Posted at

こちらのgemを使って複数人に同じ内容のメールを送る方法です。
https://github.com/sendgrid/sendgrid-ruby

githubのREADMEには一人に送る例しか書かれていなかったため、以下のサンプルコードを見ながら書いてみました。
https://github.com/sendgrid/sendgrid-ruby/blob/master/examples/helpers/mail/example.rb

mail = SendGrid::Mail.new
mail.from = SendGrid::Email.new(email: 'test@example.com')
mail.subject = 'title'

personalization = SendGrid::Personalization.new
personalization.to = SendGrid::Email.new(email: 'test1@example.com', name: 'test1 user')
personalization.to = SendGrid::Email.new(email: 'test2@example.com', name: 'test2 user')
personalization.to = SendGrid::Email.new(email: 'test3@example.com', name: 'test3 user')

mail.personalizations = personalization

sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'], host: 'https://api.sendgrid.com')
response = sg.client.mail._('send').post(request_body: mail.to_json)

Personalizationオブジェクトを作ってそこにメールアドレスを登録していきます。
ccやbccの登録も同様にPersonalizationオブジェクトに対して行います。

personalization.cc = SendGrid::Email.new(email: 'test_cc@example.com', name: 'test cc user')
personalization.bcc = SendGrid::Email.new(email: 'test_bcc@example.com', name: 'test bcc user')

14
5
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
5