handle special characters in names

This commit is contained in:
Dejan Strbac 2016-05-05 22:32:03 +02:00
parent bb9abe2cdf
commit ee242ca92a
3 changed files with 24 additions and 6 deletions

View File

@ -8,18 +8,28 @@ defmodule Mailex.Address do
def rfc_822_format(email) when is_map(email) do
email_address = Map.get(email, "address", Map.get(email, :address))
email_name = Map.get(email, "name", Map.get(email, :name))
email_name = email
|> Map.get("name", Map.get(email, :name))
|> prepare_name(email_address)
"#{email_name} <#{email_address}>"
end
defp prepare_name(email_name, address) do
if email_name do
"#{email_name} <#{email_address}>"
email_name = String.strip(email_name)
else
name = email_address |>
email_name = address |>
String.split("@") |>
List.first |>
String.split(~r/([^\w\s]|_)/) |>
Enum.map(&String.capitalize/1) |>
Enum.join(" ")
"#{name} <#{email_address}>"
end
if String.match?(email_name, ~r/[\(\)\<\>\@\,\;\:\"\.\[\]\\]/) do
"\"\\\"" <> String.replace(email_name, "\"", "\\\"") <> "\\\"\""
else
email_name
end
end

View File

@ -38,11 +38,19 @@ defmodule MailexTest do
}
end
defp email_with_special_chars_in_names do
%Mailex.Email{
from: %Mailex.Address{ name: ", Test", address: "test_a@gmail.com" },
to: [%Mailex.Address{ name: ":,<>[]()'\"Whatever", address: "test_b@gmail.com" }]
}
end
test "Messages render" do
assert email_minimal |> Mailex.Render.render
assert email_with_reply_to |> Mailex.Render.render
assert email_without_attachments |> Mailex.Render.render
assert email_with_attachments |> Mailex.Render.render
assert email_with_special_chars_in_names |> Mailex.Render.render
end
end