Skip to content

Commit 29cb805

Browse files
committed
add parsing of sender header
1 parent 6e9d1df commit 29cb805

2 files changed

Lines changed: 31 additions & 5 deletions

File tree

lib/mail/parsers/rfc_2822.ex

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -445,6 +445,11 @@ defmodule Mail.Parsers.RFC2822 do
445445
defp parse_header_value("from", value),
446446
do: parse_recipient_value(value)
447447

448+
# If present, the Sender header always contains only one recipient
449+
# If not present, the Sender will be nil
450+
defp parse_header_value("sender", value),
451+
do: parse_recipient_value(value) |> List.first()
452+
448453
defp parse_header_value("reply-to", value),
449454
do: parse_recipient_value(value)
450455

@@ -475,7 +480,7 @@ defmodule Mail.Parsers.RFC2822 do
475480
do: datetime
476481

477482
defp decode_header_value(key, addresses, opts)
478-
when key in ["to", "cc", "bcc", "from", "reply-to"] and is_list(addresses) do
483+
when key in ["to", "cc", "bcc", "from", "sender", "reply-to"] and is_list(addresses) do
479484
addresses =
480485
Enum.map(addresses, fn
481486
{name, email} ->
@@ -489,12 +494,12 @@ defmodule Mail.Parsers.RFC2822 do
489494
addresses
490495
end
491496

492-
defp decode_header_value("from", {_name, _address} = value, opts) do
493-
[from] = decode_header_value("from", [value], opts)
494-
from
497+
defp decode_header_value("sender", {_name, _address} = value, opts) do
498+
[sender] = decode_header_value("sender", [value], opts)
499+
sender
495500
end
496501

497-
defp decode_header_value("from", value, _opts), do: value
502+
defp decode_header_value("sender", value, _opts), do: value
498503

499504
defp decode_header_value("received", value, _opts),
500505
do: value

test/mail/parsers/rfc_2822_test.exs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,27 @@ defmodule Mail.Parsers.RFC2822Test do
196196
assert Mail.get_html(message) == html_part2
197197
end
198198

199+
describe "parses a message with a sender" do
200+
# The sender field, if present, can only contain a single recipient
201+
test "single sender" do
202+
message =
203+
parse_email("""
204+
Sender: "John Doe" <other@example.com>
205+
""")
206+
207+
assert message.headers["sender"] == {"John Doe", "other@example.com"}
208+
end
209+
210+
test "multiple senders return only the first sender" do
211+
message =
212+
parse_email("""
213+
Sender: user@example.com, "John Doe" <other@example.com>
214+
""")
215+
216+
assert message.headers["sender"] == "user@example.com"
217+
end
218+
end
219+
199220
describe "parses a message with multiple recipients" do
200221
test "multiple recipients in To header" do
201222
# Multiple recipients where some have names can be interpreted as a header value with params if not handled correctly.

0 commit comments

Comments
 (0)