Linux – Centos mailx sending body as attachment

bashcentosemaillinux

I've got a script I'm trying to send emails through. I'm trying to send a string variable as the body, but mailx is adding it as an attachment 'ATT00001.bin'.

Here's a snip of my script:

RESULT=''
for i in "${ARRAY[@]}"
do
    FILE=($(ls /tmp/backup/*$i*.xml -Art | tail -n 1))
    BACKUP_NAME=$(grep 'label' $FILE)
    BACKUP_NAME=${BACKUP_NAME/<label>/}
    BACKUP_NAME=${BACKUP_NAME/<\/label>/}
    RESULT="$RESULT"$'\n'"INFO: $i - $BACKUP_NAME"
done
echo "$RESULT" | mailx -r "mail@example.com" -s "Script Report" user@example.com

I think it's to do with the way I'm building the variable, as sending other single-line variables or files works as expected. I've also attempted to output the variable to a file and cat that to mailx with the same results.

How do I get the contents of the $RESULT variable into the body of the mail message? Installing and using a different utility is not an option in this case.

Best Answer

I resolved my own issue. I found that ^M carriage return characters were being added to the string and either windows/exchange/outlook didn't like it. I found this by sending RESULT to file and editing with vim.

I removed the unwanted characters by outputting to file, running sed against the file and removing via regex, then then sending the email via that file. See adjusted code below:

RESULT=''
for i in "${ARRAY[@]}"
do
    FILE=($(ls /tmp/backup/*$i*.xml -Art | tail -n 1))
    BACKUP_NAME=$(grep 'label' $FILE)
    BACKUP_NAME=${BACKUP_NAME/<label>/}
    BACKUP_NAME=${BACKUP_NAME/<\/label>/}
    RESULT="$RESULT"$'\n'"INFO: $i - $BACKUP_NAME"
done

echo "$RESULT" > /tmp/result.txt
sed -i "s/\r//g" /tmp/result.txt

cat /tmp/result.txt | mailx -r "mail@example.com" -s "Script Report" user@example.com
Related Topic