class EcoRake module Utils # Mailer helper that uses `aws-sdk-ses` **gem** (`Aws::SES::Client`) # Several ENV vars should be configured for it to work (i.e. in the `.env` file): # 1. `MAILER_REGION` # 2. `MAILER_KEY_ID` # 3. `MAILER_ACCESS_KEY` # 4. `MAILER_FROM` class Mailer # Sends an email # @param to [String] destination email address # @param subject [String] subject of the email # @param body [String] `html` or plain text message # @param from [String] the email address this is send **from** def mail(to:, subject:, body:, from: nil, cc: nil, bcc: nil) unless configured? puts "Mailer: You are missing configuration parameters. Review your .env file" return false end ses.send_email( destination: fetch_to(to: to, cc: cc, bcc: bcc), source: fetch_from(from), message: { subject: { charset: "UTF-8", data: subject }, body: { # NOTEL: `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| puts "Sent email to #{to} (MessageId: #{response.message_id})" end end # @return [Boolean] whether or not the mailer is configured for usage. def configured? fetch_access_key_id && fetch_secret_access_key && fetch_region 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 => e puts "Trying to send an email with wrong email configuration: #{e}" end @ses end def fetch_to(to: nil, cc: nil, bcc: nil) { to_addresses: [to].flatten.compact.uniq }.tap do |dest| cc = [cc].flatten.compact.uniq bcc = [bcc].flatten.compact.uniq dest.merge!(cc_addresses: cc) unless cc.empty? dest.merge!(bcc_addresses: bcc) unless bcc.empty? end end def fetch_from(value = nil) value || ENV['MAILER_FROM'] end def fetch_access_key_id ENV['MAILER_KEY_ID'] end def fetch_secret_access_key ENV['MAILER_ACCESS_KEY'] end def fetch_region ENV['MAILER_REGION'] end end end end