# rubocop:disable Naming/MethodParameterName module Eco module API module Common module Session class Mailer class SendgridProvider < ProviderBase def send_mail(subject:, body:, to: nil, cc: nil, bcc: nil) return false unless sendgrid data = to_data( subject: subject, body: body, to: to, cc: cc, bcc: bcc ) mailer._("send").post(request_body: data) end def fetch_to(value = nil) emails = [super].flatten.compact to_email_model(emails) end # @return [Boolean] whether or not the mailer is configured for usage. def configured? fetch_secret_access_key end private def credentials @credentials ||= { id: 'SENDGRID_ACCESS_ID', key: 'SENDGRID_ACCESS_KEY' } end def to_data(subject:, body:, to: nil, cc: nil, bcc: nil) { "personalizations" => [ { "to" => fetch_to(to).flatten, "subject" => subject }.tap do |pers| merge_if('cc', cc, target: pers) merge_if('bcc', bcc, target: pers) end ], "from" => fetch_from, "content" => [ { "type" => "text/plain", "value" => body } ] } end def mailer @mailer ||= sendgrid&.client&.mail end def sendgrid require 'sendgrid-ruby' extend(::SendGrid) unless is_a?(SendGrid) @sendgrid ||= SendGrid::API.new( api_key: fetch_secret_access_key ) rescue StandardError => err log(:error) { "Trying to send an email with wrong email configuration: #{err}" } nil end def to_email_model(value) case value when Array value.map do |val| to_email_model(val) end.compact else return if value.to_s.strip.empty? { "email" => value } end end def merge_if(key, data, target: {}) return if data.to_s.strip.empty? key_data = to_email_model(data) return if key_data.nil? return if key_data.empty? target.merge!({key.to_s => key_data}) end def fetch_from(value = nil) email = [super].flatten.compact.first to_email_model(email) end end end end end end end # rubocop:enable Naming/MethodParameterName