enter code here
I have text file which contains the following:
#MailTo ESC BCC ESC Subject ESC Message Body
user1@example.com|||user1@xyz.com|||Subject1|||Message Body1
user2@example.com|||user2@xyz.com|||Subject2 |||Message Body2
user3@example.com|||user3@xyz.com|||Subject3|||Message Body3
user4@example.com|||user4@xyz.com|||Subject4|||Message Body4
user5@example.com|||user5@xyz.com|||Subject5|||Message Body5
user6@example.com|||user6@xyz.com|||Subject6|||Message Body6
user7@example.com|||user7@xyz.com|||Subject7|||Message Body7
usern@example.com|||usern@xyz.com|||Subjectn|||Message Bodyn
Please note that I am using "ESC" pattern as a delimiter between the fields ( I don't use ";" as a delimiter to avoid any conflicts in the Message body if ";" exists in the message body) so i think i can't parse it as a csv file.
please advice, how to create a bash script to parse this file to send emails to different users with different subject, and different message body, please?
Here is my suggested solution for my question (I replaced "ESC" word with "|||" as a delimiter):
#!/bin/bash
# Functions
function is_valid_email
{
pattern='^[a-zA-Z0-9._-]\+@[a-zA-Z0-9]\+\.[a-z]\{2,\}'
echo "$1" | grep "$pattern" > /dev/null
}
# read file line by line
COUNTER=0
while read -r line
do
# check if we are one the first line or not which contains heading
if [ ! $COUNTER -eq 0 ]; then
# we are not in the first line so we may continue
# extract variables from the line
TO=$(echo $line | awk -F '\\|\\|\\|' '{print $3}');
CC=$(echo $line | awk -F '\\|\\|\\|' '{print $4}');
BCC=$(echo $line | awk -F '\\|\\|\\|' '{print $5}');
SUBJECT=$(echo $line | awk -F '\\|\\|\\|' '{print $6}');
BODY=$(echo $line | awk -F '\\|\\|\\|' '{print $7}');
COMMAND="echo \"$BODY\" | mail -s \"$SUBJECT\" "
# check if CC is a valid email
is_valid_email "$CC"
if [ "$?" -ne 0 ]; then
echo "TODO: handle invliad cc email ($CC)"
else
COMMAND_CC=" -c \"$CC\""
COMMAND=$COMMAND$COMMAND_CC
fi
# check if BCC is a valid email
is_valid_email "$BCC"
if [ $? != 0 ]; then
echo "TODO: handle invliad bcc email ($BCC)"
else
COMMAND_BCC=" -b \"$BCC\""
COMMAND=$COMMAND$COMMAND_BCC
fi
# check if TO is a valid email
is_valid_email "$TO"
if [ "$?" -ne 0 ]; then
echo "TODO: handle invliad to email ($TO)"
else
COMMAND_TO=" \"$TO\""
COMMAND=$COMMAND$COMMAND_TO
fi
eval $COMMAND
else
# we are on the first line so increase the counter and continue
COUNTER=$((COUNTER+1))
fi
done < test_file