# rubocop:disable Naming/MethodParameterName module Eco module API module Common module Session class Mailer include Eco::Language::AuxiliarLogger # @param enviro [Eco::API::Common::Session::Environment] def initialize(enviro:) msg = "Required Environment object (enviro:). Given: #{enviro.class}" raise msg 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(subject:, body:, to: nil, 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| msg = "Sent email (MessageId: #{response.message_id}) to #{fetch_destination(to: to, cc: cc, bcc: bcc)}" puts msg log(:debug) { msg } end end private def ses require 'aws-sdk-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 StandardError => err log(:error) { "Trying to send an email with wrong email configuration: #{err}" } end @ses end def logger @enviro&.logger || super 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 # rubocop:enable Naming/MethodParameterName