hotdang
hotdang

Reputation: 11

Send one and not multiple emails with bash script

I have taken over a script from someone, and the bash script works generally well, but it's not completely polished. So, generally and simplistically speaking, it sends an email report to people, which it takes from a text file. So, the problem is this. Each line in that text file represents the data that should be sent to a user via email. The script formats the data, so it's easy to read, and sends the email. When the email is sent, it will have 3 lines in the email for user 1 and 2 lines in the email for user2. Fine good, works well. However, instead of sending one email each to user 1 and user 2, it sends 3 of the same emails to user 1 and 2 of the same email to user 2. Essentially duplicates the email. I guess it's not a huge problem if they only get 2 emails, however, what if they have 20-30 lines? They can receive 20-30 of the same emails.

     Line1:   User 1  UnitCost Total Cost RemainingBalance
     Line2:   User 1  UnitCost Total Cost RemainingBalance
     Line3:   User 1  UnitCost Total Cost RemainingBalance
     Line4:   User 2  UnitCost Total Cost RemainingBalance
     Line5:   User 2  UnitCost Total Cost RemainingBalance

So, what I like to know is, here's the line to send out the email:

printf "$USER\n$MESSAGE\n\n$DETAIL" | mailx -r [email protected] -s 
"Email for balance" "$EMAIL"

So, is there a way without re-writing the script to have mailx send out one email per recipient? Not sure what's the best method here. Any input would be appreciated!

Upvotes: 1

Views: 1131

Answers (1)

Nahuel Fouilleul
Nahuel Fouilleul

Reputation: 19305

create a temporary directory

TMPDIR=xxx
mkdir "${TMPDIR}" || { echo "failed to create temporary dir ${TMPDIR}";exit 1;}

redirect output to a file in temporary directory

printf "$USER\n$MESSAGE\n\n$DETAIL"  >>"${TMPDIR}/${EMAIL}.txt"

then retrieve email from file name and send the temporary file content

for FILE in "${TMPDIR}"/*.txt; do
  mailx -r [email protected] -s "Email for balance" "${FILE%.txt}" <"${FILE}"
done
rm -r "${TMPDIR}"

Upvotes: 1

Related Questions