diff --git a/app/lib/send_grid_client.rb b/app/lib/send_grid_client.rb index 2fcb4b62..b67c67d8 100644 --- a/app/lib/send_grid_client.rb +++ b/app/lib/send_grid_client.rb @@ -17,6 +17,56 @@ def add_user(user) Rails.logger.error e.backtrace.join("\n") end + # Sends a transactional email with a template, based on the passed in options hash. + # + # @param options [Hash] Sample options hash: + # { + # to: 'tom@gmail.com', + # from: 'frank@oc.com', + # subject: 'Hello', + # user_count: '5', + # body: 'Hello world!', + # template_id: 'asdfas-123123-asdfasf-2qwerqwe' + # } + # @return [SendGrid::Response] Includes a body and status_code + # @see https://github.com/sendgrid/sendgrid-ruby/blob/7c8973f7b8de51a98dce73a52138791b19434573/USE_CASES.md#with-mail-helper-class + # + def send_email_with_template(options={}) + Rails.logger.info("Sending email to #{options[:to]} at #{Time.current} re: #{options[:subject]}") + + mail = { + "personalizations" => [ + { + "to" => [ + { + "email" => options[:to] + } + ], + "subject" => options[:subject], + "substitutions" => { + "-user_count-" => options[:user_count].to_s + }, + "template_id" => options[:transactional_template_id] + } + ], + "from" => { + "email" => options[:from] + }, + "content" => [ + { + "type" => "text/plain", + "value" => options[:body] + } + ] + } + + @sendgrid.client.mail._("send").post(request_body: mail) + rescue => e + Rails.logger.error "Failed to send email to #{options[:to]} re: #{options[:subject]} due to: #{e}" + Rails.logger.error e.backtrace.join("\n") + raise "Failed to send email to #{options[:to]} re: #{options[:subject]} due to: #{e}" + end + private def add_recipient(data)