require_relative 'mailer/provider_base' require_relative 'mailer/aws_provider' require_relative 'mailer/sendgrid_provider' 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 DEFAULT_PROVIDER = :sendgrid attr_reader :provider def initialize(provider: DEFAULT_PROVIDER) @provider = provider || DEFAULT_PROVIDER 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 # @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 rescue StandardError => err msg = "The mailer generated an exception:\n" msg << err.patch_full_message(trace_count: 15) puts msg 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) return false unless (serv = service) unless serv.configured? msg = "Mailer: You are missing configuration parameters " msg << "for '#{provider}'. Review your .env file" puts msg return false end serv.send_mail( subject: subject, body: body, to: to, cc: cc, bcc: bcc ).tap do |response| next unless response to_addr = serv.fetch_to(to) msg = "Sent email #{ProviderBase.to_desc(to: to_addr, cc: cc, bcc: bcc)}" puts msg end rescue StandardError => err msg = "The mailer generated an exception:\n" msg << err.patch_full_message(trace_count: 15) puts msg end private def service case provider when :aws AwsProvider.new when :sendgrid SendgridProvider.new else puts "Unknown mail provider '#{provider}'" nil end end end end end