Last active
July 26, 2022 09:12
-
-
Save wmakley/c0d6dae8a013c9657011db1e196767e8 to your computer and use it in GitHub Desktop.
Use AWS SESv2 SDK as an ActionMailer delivery method (API call instead of SMTP)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Why? | |
# * May use same IAM role or account in use for other app features. | |
# * Avoid sharing same SMTP credentials across multiple apps. | |
# | |
# Alternatives: | |
# * https://github.com/aws/aws-sdk-rails (may be overkill) | |
# | |
# Gemfile: | |
# gem 'aws-sdk-sesv2' | |
# | |
# config/initializers/aws_ses_delivery_method.rb: | |
class SESV2DeliveryMethod | |
def initialize(client_params) | |
@client = Aws::SESV2::Client.new(client_params) | |
end | |
# @param [Mail::Message] mail | |
def deliver!(mail) | |
@client.send_email( | |
{ | |
from_email_address: Array(mail.from).first, | |
destination: { | |
to_addresses: mail.destinations, | |
}, | |
content: { | |
raw: { | |
data: mail.encoded, | |
}, | |
} | |
} | |
) | |
end | |
def settings | |
{} | |
end | |
end | |
# Alter to handle credentials how you prefer: | |
ActionMailer::Base.add_delivery_method :ses, SESV2DeliveryMethod, | |
region: ENV['AWS_REGION'] || Rails.application.credentials.dig(Rails.env.to_sym, :aws, :region), | |
credentials: Aws::Credentials.new( | |
ENV['AWS_ACCESS_KEY_ID'] || Rails.application.credentials.dig(Rails.env.to_sym, :aws, :access_key_id), | |
ENV['AWS_SECRET_ACCESS_KEY'] || Rails.application.credentials.dig(Rails.env.to_sym, :aws, :secret_access_key) | |
) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment