Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wrap header values in quotes if they contain characters that are not allowed #190

Merged
merged 2 commits into from
Mar 18, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions lib/mail/renderers/rfc_2822.ex
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ defmodule Mail.Renderers.RFC2822 do

defp render_address({name, email}), do: ~s("#{name}" <#{validate_address(email)}>)
defp render_address(email), do: validate_address(email)

defp render_subtypes([]), do: []

defp render_subtypes([{key, value} | subtypes]) when is_atom(key),
Expand All @@ -152,6 +153,14 @@ defmodule Mail.Renderers.RFC2822 do
defp render_subtypes([{key, value} | subtypes]) do
key = String.replace(key, "_", "-")
value = encode_header_value(value, :quoted_printable)

value =
if value =~ ~r/[\s;]/ do
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should match all the tspecial characters of RFC2045
if Regex.match?(~r/[\s()<>@,;:\\<\/\[\]?=]/, value) do

"\"#{value}\""
else
value
end

["#{key}=#{value}" | render_subtypes(subtypes)]
end

Expand Down
11 changes: 11 additions & 0 deletions test/mail/renderers/rfc_2822_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,17 @@ defmodule Mail.Renderers.RFC2822Test do
assert header == "Foo-Bar: abcd; baz-buzz=qux"
end

test "quotes header parameters if necessary" do
header = Mail.Renderers.RFC2822.render_header("Content-Disposition", ["attachment", filename: "my-test-file"])
assert header == "Content-Disposition: attachment; filename=my-test-file"

header = Mail.Renderers.RFC2822.render_header("Content-Disposition", ["attachment", filename: "my test file"])
assert header == "Content-Disposition: attachment; filename=\"my test file\""

header = Mail.Renderers.RFC2822.render_header("Content-Disposition", ["attachment", filename: "my;test;file"])
assert header == "Content-Disposition: attachment; filename=\"my;test;file\""
end

test "address headers renders list of recipients" do
header = Mail.Renderers.RFC2822.render_header("from", "[email protected]")
assert header == "From: [email protected]"
Expand Down
Loading