Search code examples
elixirphoenix-framework

How do I load environment variables for a phoenix framework project


I created a Phoenix app then added the bamboo module for sending email, and I successfully sent my first email using Elixir this afternoon, but I had to hard code the username and password into the config.exs.

I read this article and set up a .env file in the root of my phoenix project, and I am trying to load the environment variables using the following statement(s), within the config.exs file.

username: System.get_env("SMTP_USERNAME"),
password: System.get_env("SMTP_PASSWORD"),

However, the emails are not being sent, and bamboo is giving me a rather cryptic error message.

I am building the phoenix app using the following command from the terminal,

iex -S mix

and I'm manually sending the emails within a iex session with a command similar to the one below,

CrjApi.Email.hello_text_email("me@example.com") |> CrjApi.Mailer.deliver_now

but the emails are only being sent when the username / password are hard coded into the config.exs file. How can I use the .env file I setup so I don't have to hard code the username / password into the config.exs?

Note: I'm running OS X, and using the fish shell.


Solution

  • I ended up creating a smtp.exs file within config directory which looks like the following,

    smtp.exs

    use Mix.Config
    
    config :crj_api, CrjApi.Mailer,
      username: "foo",
      password: "secret_password"
    

    and then added the following to config.exs

    import_config "smtp.exs"

    Now when I load the application with iex -S mix it loads in these application variables everytime, and I don't have source an environment variable for each terminal session.