I am using Curl to send simple email alerts:
curl smtp://mail.example.com --mail-from [email protected] --mail-rcpt \
[email protected] --upload-file email.txt
email.txt content:
From: John <[email protected]>
To: Joe <[email protected]>
Subject: Example email
Date: Wed, 26 Oct 2022 08:45:16
Welcome to this example email.
Is it possible to have variables inside email.txt
(e.g., make the date dynamic date
or include bash user who
)?
CodePudding user response:
There is a GNU gettext utility called envsubst
, which replaces variables on its standard input with their values. For example:
$ export DATE=$(date '%F %T')
$ echo '$DATE' | envsubst
2022-10-25 13:17:51
Notice that echo '$DATE'
prints $DATE
, literally, as the variable isn't expanded by the shell due to the single quotes.
To use that for your example, you could set the desired values in the environment:
export FROM='[email protected]'
export TO='[email protected]'
export DATE=$(date '%F %T')
then update the email to use the variables:
From: John <$FROM>
To: Joe <$TO>
Subject: Example email
Date: $DATE
Welcome to this example email.
and then use envsubst
and a process substitution in your command:
curl smtp://mail.example.com \
--mail-from "$FROM" \
--mail-rcpt "$TO" \
--upload-file <(envsubst < email.txt)
where the output of envsubst < email.txt
is
From: John <[email protected]>
To: Joe <[email protected]>
Subject: Example email
Date: 2022-10-25 13:23:44
Welcome to this example email.
Instead of process substitution, you could also use a pipeline and the special -
file to read from standard input:
envsubst < email.txt \
| curl smtp://mail.example.com \
--mail-from "$FROM" \
--mail-rcpt "$TO" \
--upload-file -
CodePudding user response:
Maybe it will help you (see man envsubst):
$ cat test.txt
current date is ${CURRENT_DATE}
$ export CURRENT_DATE=$(date); cat test.txt | envsubst | curl bla-bla