Skip to content

Instantly share code, notes, and snippets.

@wmakley
Last active July 26, 2022 09:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wmakley/c0d6dae8a013c9657011db1e196767e8 to your computer and use it in GitHub Desktop.
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)
# 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