Created
January 31, 2022 16:58
-
-
Save maxigs/7b016a99218f9a6983c86776d28b6892 to your computer and use it in GitHub Desktop.
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
# Parses a URL containing the SMTP Config (Credentials and other options supported) | |
# Use from application.rb or in environments. | |
# | |
# Example: | |
# | |
# if ENV["SMTP_URL"] | |
# config.action_mailer.delivery_method = :smtp | |
# config.action_mailer.smtp_settings = SmtpConfig.from_url(ENV["SMTP_URL"]) | |
# end | |
# | |
# Warning: User & Password in the URL need to be encoded with `CGI.encode` to ensure safe URIs (eg. `@` in User or Password) | |
class SmtpConfig | |
class << self | |
def is_true?(value) | |
value == '1' || value.downcase == 'true' | |
end | |
def from_url(url) | |
uri = URI.parse(url) | |
smtp_config = { | |
address: uri.host, | |
port: uri.port, | |
user_name: CGI.unescape(uri.user), | |
password: CGI.unescape(uri.password), | |
} | |
params = Rack::Utils.parse_nested_query(uri.query) | |
%w(authentication domain openssl_verify_mode).each do |key| | |
unless (value = params[key]).blank? | |
smtp_config[key.to_sym] = value | |
end | |
end | |
%w(open_timeout read_timeout).each do |key| | |
unless (value = params[key]).blank? | |
smtp_config[key.to_sym] = value.to_i | |
end | |
end | |
%w(enable_starttls enable_starttls_auto ssl tls).each do |key| | |
unless (value = params[key]).blank? | |
smtp_config[key.to_sym] = is_true?(value) | |
end | |
end | |
smtp_config | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment