Skip to content

Commit

Permalink
Add Content-ID header when needed
Browse files Browse the repository at this point in the history
  • Loading branch information
arnaudmorisset committed Nov 10, 2020
1 parent c301cbd commit 97e1dbd
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 2 deletions.
16 changes: 14 additions & 2 deletions lib/bamboo/adapters/smtp_adapter.ex
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,19 @@ defmodule Bamboo.SMTPAdapter do
|> add_smtp_line(text_body)
end

defp add_attachment_header(body, %{content_type: content_type} = attachment)
defp add_attachment_header(body, attachment) do
case attachment.content_id do
nil ->
add_common_attachment_header(body, attachment)

cid ->
body
|> add_common_attachment_header(attachment)
|> add_smtp_line("Content-ID: <#{cid}>")
end
end

defp add_common_attachment_header(body, %{content_type: content_type} = attachment)
when content_type == "message/rfc822" do
<<random::size(32)>> = :crypto.strong_rand_bytes(4)

Expand All @@ -235,7 +247,7 @@ defmodule Bamboo.SMTPAdapter do
|> add_smtp_line("X-Attachment-Id: #{random}")
end

defp add_attachment_header(body, attachment) do
defp add_common_attachment_header(body, attachment) do
<<random::size(32)>> = :crypto.strong_rand_bytes(4)

body
Expand Down
1 change: 1 addition & 0 deletions test/attachments/attachment_one.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Attachment One.
1 change: 1 addition & 0 deletions test/attachments/attachment_two.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Attachment Two.
22 changes: 22 additions & 0 deletions test/lib/bamboo/adapters/smtp_adapter_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -730,6 +730,28 @@ defmodule Bamboo.SMTPAdapterTest do
assert_configuration(bamboo_config, gen_smtp_config)
end

test "email have a Content-ID properly set when attaching files with content_id" do
bamboo_email =
new_email()
|> Bamboo.Email.put_attachment(Path.absname("test/attachments/attachment_one.txt"),
content_id: "12345"
)
|> Bamboo.Email.put_attachment(Path.absname("test/attachments/attachment_two.txt"),
content_id: "54321"
)

bamboo_config = configuration()

{:ok, "200 Ok 1234567890"} = SMTPAdapter.deliver(bamboo_email, bamboo_config)

assert 1 = length(FakeGenSMTP.fetch_sent_emails())

[{{_from, _to, raw_email}, _gen_smtp_config}] = FakeGenSMTP.fetch_sent_emails()

assert Regex.run(~r{Content-ID: <12345>\r\n}, raw_email, capture: :all_but_first)
assert Regex.run(~r{Content-ID: <54321>\r\n}, raw_email, capture: :all_but_first)
end

test "check rfc822 encoding for subject" do
bamboo_email =
@email_in_utf8
Expand Down

0 comments on commit 97e1dbd

Please sign in to comment.