diff --git a/lib/mailex.ex b/lib/mailex.ex index fc4f2c7..2586530 100644 --- a/lib/mailex.ex +++ b/lib/mailex.ex @@ -29,4 +29,4 @@ defmodule Mailex do end end -end \ No newline at end of file +end diff --git a/lib/mailex/address.ex b/lib/mailex/address.ex index 1e51e60..9afc2f9 100644 --- a/lib/mailex/address.ex +++ b/lib/mailex/address.ex @@ -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 @@ -34,4 +44,4 @@ defmodule Mailex.Address do end -end \ No newline at end of file +end diff --git a/test/mailex_test.exs b/test/mailex_test.exs index c285108..ad30f58 100644 --- a/test/mailex_test.exs +++ b/test/mailex_test.exs @@ -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