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("[email protected]") |> 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.
Set Environment Variables using PowerShellAfter $Env , add a colon, followed by the environment variable's name, followed by the equals sign, followed by the value you want to use. This will set the environment variable for the current process, and will be inherited by any child process you start from this shell.
On the Windows taskbar, right-click the Windows icon and select System. In the Settings window, under Related Settings, click Advanced system settings. On the Advanced tab, click Environment Variables. Click New to create a new environment variable.
You can put all your environment variables in a file named for example .env.dev
or .env.prod
(don't forget to add .env.*
to .gitignore file):
export SMTP_DOMAIN=smtp.trumpy.xyz
export [email protected]
export SMTP_PASSWORD=donny123
export SMTP_PORT=587
...
Load that file and run Phoenix server:
source .env.dev && mix phx.server
Remember to use this syntax
port: {:system, "SMTP_PORT"},
username: {:system, "SMTP_USERNAME"},
In place of this
port: System.get_env("SMTP_PORT"),
username: System.get_env("SMTP_USERNAME"),
in order to load ENV variables at runtime.
You can use confex module in your project. https://github.com/Nebo15/confex
This is a helper module that provides you with the option to read env configuration at runtime.
config.exs example
config :app_name,
smtp_username: {:system, "SMTP_USERNAME", "default_user_name"},
smtp_password: {:system, "SMTP_PASSWORD", "default_password"}
In your module
username = Confex.get(:app_name, :smtp_username)
password = Confex.get(:app_name, :smtp_password)
Into your iex type
System.put_env("SMTP_USERNAME", "real_username")
System.put_env("SMTP_PASSWORD", "real_password")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With