require 'aws-sdk-ses' module Eco module API module Common module Session class Mailer # @param enviro [Eco::API::Common::Session::Environment] def initialize (enviro:) raise "Required Environment object (enviro:). Given: #{enviro}" if enviro && !enviro.is_a?(Eco::API::Common::Session::Environment) @enviro = enviro end # Sends an email # @param to [String] destination email address # @param subject [String] subject of the email # @param body [String] `html` or plain text message def mail(to: nil, subject:, body:, cc: nil, bcc: nil) ses.send_email( destination: fetch_destination(to: to, cc: cc, bcc: bcc), source: fetch_from, message: { subject: { charset: "UTF-8", data: subject, }, body: { # NOTE - html: will let you send html instead # you can use both at once if you like text: { charset: "UTF-8", data: body } } } ).tap do |response| logger.debug("Sent email to #{to} (MessageId: #{response.message_id})") end end private def ses begin @ses ||= Aws::SES::Client.new( access_key_id: fetch_access_key_id, secret_access_key: fetch_secret_access_key, region: fetch_region ) rescue Exception => e logger.error("Trying to send an email with wrong email configuration: #{e}") end @ses end def logger @enviro&.logger || ::Logger.new(IO::NULL) end def config @enviro.config || {} end def fetch_destination(to: nil, cc: nil, bcc: nil) cc_to = [cc].flatten.compact.uniq bcc_to = [bcc].flatten.compact.uniq { to_addresses: [fetch_to(to)].flatten }.tap do |dest| dest.merge!(cc_addresses: cc_to) unless cc_to.empty? dest.merge!(bcc_addresses: bcc_to) unless bcc_to.empty? end end def fetch_to(value = nil) value || config.mailer.to end def fetch_from(value = nil) value || config.mailer.from end def fetch_access_key_id config.mailer.access_key_id || ENV['AWS_ACCESS_KEY_ID'] end def fetch_secret_access_key config.mailer.secret_access_key || ENV['AWS_SECRET_ACCESS_KEY'] end def fetch_region config.mailer.region || ENV['AWS_REGION'] end def fetch_server config.mailer.server end def fetch_message_id_domain config.mailer.message_id_domain end end end end end end