diff --git a/lib/bamboo/adapters/send_grid_adapter.ex b/lib/bamboo/adapters/send_grid_adapter.ex index 49b21a84..d79c73a3 100644 --- a/lib/bamboo/adapters/send_grid_adapter.ex +++ b/lib/bamboo/adapters/send_grid_adapter.ex @@ -15,7 +15,7 @@ defmodule Bamboo.SendGridAdapter do # In config/config.exs, or config.prod.exs, etc. config :my_app, MyApp.Mailer, adapter: Bamboo.SendGridAdapter, - api_key: "my_api_key" + api_key: "my_api_key" # or {:system, "SENDGRID_API_KEY"} # Define a Mailer. Maybe in lib/my_app/mailer.ex defmodule MyApp.Mailer do @@ -49,20 +49,23 @@ defmodule Bamboo.SendGridAdapter do @doc false def handle_config(config) do - if config[:api_key] in [nil, ""] do - raise_api_key_error(config) - else - config - end + # build the api key - will raise if there are errors + Map.merge(config, %{api_key: get_key(config)}) end @doc false def supports_attachments?, do: true defp get_key(config) do - case Map.get(config, :api_key) do - nil -> raise_api_key_error(config) - key -> key + api_key = case Map.get(config, :api_key) do + {:system, var} -> System.get_env(var) + key -> key + end + + if api_key in [nil, ""] do + raise_api_key_error(config) + else + api_key end end diff --git a/test/lib/bamboo/adapters/send_grid_adapter_test.exs b/test/lib/bamboo/adapters/send_grid_adapter_test.exs index 394e121c..88902171 100644 --- a/test/lib/bamboo/adapters/send_grid_adapter_test.exs +++ b/test/lib/bamboo/adapters/send_grid_adapter_test.exs @@ -5,6 +5,7 @@ defmodule Bamboo.SendGridAdapterTest do @config %{adapter: SendGridAdapter, api_key: "123_abc"} @config_with_bad_key %{adapter: SendGridAdapter, api_key: nil} + @config_with_env_var_key %{adapter: SendGridAdapter, api_key: {:system, "SENDGRID_API"}} defmodule FakeSendgrid do use Plug.Router @@ -69,6 +70,26 @@ defmodule Bamboo.SendGridAdapterTest do end end + test "can read the api key from an ENV var" do + System.put_env("SENDGRID_API", "123_abc") + + config = SendGridAdapter.handle_config(@config_with_env_var_key) + + assert config[:api_key] == "123_abc" + end + + test "raises if an invalid ENV var is used for the API key" do + System.delete_env("SENDGRID_API") + + assert_raise ArgumentError, ~r/no API key set/, fn -> + new_email(from: "foo@bar.com") |> SendGridAdapter.deliver(@config_with_env_var_key) + end + + assert_raise ArgumentError, ~r/no API key set/, fn -> + SendGridAdapter.handle_config(@config_with_env_var_key) + end + end + test "deliver/2 sends the to the right url" do new_email() |> SendGridAdapter.deliver(@config)