Skip to content

Instantly share code, notes, and snippets.

@mjbellantoni
Created March 5, 2022 18:53
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 mjbellantoni/deb1625182d0942ac47ee0405cb2f061 to your computer and use it in GitHub Desktop.
Save mjbellantoni/deb1625182d0942ac47ee0405cb2f061 to your computer and use it in GitHub Desktop.
Rails Email Setup for Development, Staging, and Production
# config/initializers/action_mailer.rb
Rails.application.config_for(:mailer).keys.each do |option_name|
Rails.configuration.action_mailer[option_name] = Rails.application.config_for(:mailer)[option_name]
end
# lib/tasks/mail.rake
namespace :mail do
desc "Send a couple of test emails"
task send_tests: :environment do
%w[ a@example.com b@example.com ].each do |recipient|
puts "Mailing #{recipient}..."
TestMailer.with(recipient: recipient).test_mail.deliver_later
rescue => exception
log_data = { task: "mail:send_tests", recipient: recipient, exception: exception }
Rails.logger.error(log_data)
end
end
end
# config/mailer.yml
development:
asset_host: "http://www.railsgigs.test:3000"
default_url_options:
host: "www.railsgigs.test"
port: 3000
smtp_settings:
address: "localhost"
port: 1025
production:
asset_host: <%= "https://#{ENV["URL_HOST"]}" %>
default_url_options:
host: <%= ENV["URL_HOST"] %>
smtp_settings:
user_name: <%= ENV["SMTP_USER_NAME"] %>
password: <%= ENV["SMTP_PASSWORD"] %>
domain: <%= ENV["SMTP_DOMAIN"] %>
address: <%= ENV["SMTP_ADDRESS"] %>
port: <%= ENV["SMTP_PORT"] %>
authentication: <%= ENV["SMTP_AUTHENTICATION"]&.to_sym %>
enable_starttls_auto: true
test:
default_url_options:
host: "www.railsgigs.test"
port: 3000
@mhw
Copy link

mhw commented Mar 16, 2022

Hi!

I was just adding your config into a Rails 5.2 app and ran into an issue with the initializer, because back in those days the result from config_for was a hash with String keys rather than symbols. As a result the SMTP settings don't get picked up correctly by ActionMailer. Here's an initializer that works on 5.2:

Rails
  .application
  .config_for(:mailer)
  .deep_symbolize_keys
  .each { |key, value| Rails.configuration.action_mailer[key] = value }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment