Skip to content

Commit

Permalink
Add support to Mailgun adapter for using custom vars (#306)
Browse files Browse the repository at this point in the history
  • Loading branch information
jfcalvo authored and paulcsmith committed Oct 18, 2017
1 parent 945fff9 commit 1ccb606
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
15 changes: 12 additions & 3 deletions lib/bamboo/adapters/mailgun_adapter.ex
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ defmodule Bamboo.MailgunAdapter do
|> put_html_body(email)
|> put_text_body(email)
|> put_headers(email)
|> put_custom_vars(email)
|> filter_non_empty_mailgun_fields
end

Expand All @@ -103,16 +104,24 @@ defmodule Bamboo.MailgunAdapter do

defp put_headers(body, %Email{headers: headers}) do
Enum.reduce(headers, body, fn({key, value}, acc) ->
Map.put(acc, :"h:#{key}", value)
Map.put(acc, :"h:#{key}", value)
end)
end

defp put_custom_vars(body, %Email{private: private}) do
custom_vars = Map.get(private, :mailgun_custom_vars, %{})

Enum.reduce(custom_vars, body, fn({key, value}, acc) ->
Map.put(acc, :"v:#{key}", value)
end)
end

@mailgun_message_fields ~w(from to cc bcc subject text html)a

def filter_non_empty_mailgun_fields(map) do
Enum.filter(map, fn({key, value}) ->
# Key is a well known mailgun field or is an header field and its value is not empty
(key in @mailgun_message_fields || String.starts_with?(Atom.to_string(key), "h:")) && !(value in [nil, "", []])
# Key is a well known mailgun field or is an header or custom var field and its value is not empty
(key in @mailgun_message_fields || String.starts_with?(Atom.to_string(key), ["h:", "v:"])) && !(value in [nil, "", []])
end)
end

Expand Down
7 changes: 5 additions & 2 deletions test/lib/bamboo/adapters/mailgun_adapter_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -78,14 +78,15 @@ defmodule Bamboo.MailgunAdapterTest do
assert request_path == "/test.tt/messages"
end

test "deliver/2 sends from, subject, text body, html body and headers" do
test "deliver/2 sends from, subject, text body, html body, headers and custom vars" do
email = new_email(
from: "from@foo.com",
subject: "My Subject",
text_body: "TEXT BODY",
html_body: "HTML BODY",
)
|> Email.put_header("X-My-Header", "my_header_value")
|> Email.put_private(:mailgun_custom_vars, %{my_custom_var: 42, other_custom_var: 43})

MailgunAdapter.deliver(email, @config)

Expand All @@ -95,7 +96,9 @@ defmodule Bamboo.MailgunAdapterTest do
assert params["subject"] == email.subject
assert params["text"] == email.text_body
assert params["html"] == email.html_body
assert params["h:X-My-Header"] == "my_header_value"
assert params["h:X-My-Header"] == "my_header_value"
assert params["v:my_custom_var"] == "42"
assert params["v:other_custom_var"] == "43"

hashed_token = Base.encode64("api:" <> @config.api_key)

Expand Down

0 comments on commit 1ccb606

Please sign in to comment.