Encode domain parts of all addresses in mailers as punycode

This commit is contained in:
Artur Beljajev 2019-04-13 20:05:07 +03:00 committed by --global
parent 25d5d12cfe
commit 86b7b1d19f
4 changed files with 46 additions and 7 deletions

View file

@ -1,10 +1,4 @@
class ApplicationMailer < ActionMailer::Base
append_view_path Rails.root.join('app', 'views', 'mailers')
layout 'mailer'
def format(email)
local, host = email.split('@')
host = SimpleIDN.to_ascii(host)
"#{local}@#{host}"
end
end

View file

@ -0,0 +1,24 @@
class PunycodeInterceptor
class << self
def delivering_email(message)
message.from = encode_addresses_as_punycode(message.from)
message.to = encode_addresses_as_punycode(message.to)
message.cc = encode_addresses_as_punycode(message.cc) if message.cc
message.bcc = encode_addresses_as_punycode(message.bcc) if message.bcc
end
private
def encode_addresses_as_punycode(addresses)
addresses.map do |address|
local_part, domain_part = address.split('@')
domain_part = encode_domain_part_as_punycode(domain_part)
[local_part, '@', domain_part].join
end
end
def encode_domain_part_as_punycode(domain_part)
SimpleIDN.to_ascii(domain_part)
end
end
end

View file

@ -92,6 +92,9 @@ module DomainNameRegistry
}
config.action_mailer.default_options = { from: ENV['action_mailer_default_from'] }
require "#{Rails.root}/app/mailers/interceptors/punycode_interceptor"
ActionMailer::Base.register_interceptor(PunycodeInterceptor)
config.action_view.default_form_builder = 'DefaultFormBuilder'
config.secret_key_base = Figaro.env.secret_key_base
end

View file

@ -14,4 +14,22 @@ class ApplicationMailerTest < ActiveSupport::TestCase
assert_equal ['no-reply@registry.test'], email.from
end
def test_encodes_address_fields_as_punycode
mailer = Class.new(ApplicationMailer) do
def test
# Empty block to avoid template rendering
mail(from: 'from@münchen.test', to: 'to@münchen.test', cc: 'cc@münchen.test',
bcc: 'bcc@münchen.test') {}
end
end
email = mailer.test
email.deliver_now
assert_equal ['from@xn--mnchen-3ya.test'], email.from
assert_equal ['to@xn--mnchen-3ya.test'], email.to
assert_equal ['cc@xn--mnchen-3ya.test'], email.cc
assert_equal ['bcc@xn--mnchen-3ya.test'], email.bcc
end
end