I have the following script that i put togheter from the web, to send emails from terminal trough gmail.
#!/bin/bash
#sendGmail "FROM" "TO" "SUBJECT" "BODY" "ATTACHMENTS (optional)"
FROM=$1
TO=$2
SUBJECT=$3
BODY=$4
# Function to check if entered file names are really files
function check_files()
{
output_files=""
for file in $1; do
if [ -s $file ]; then
output_files="${output_files}${file} "
fi
done
echo $output_files
}
if [ "$FROM" == "" ]; then
FROM="[email protected]"
else
if [[ "$FROM" =~ "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$" ]]; then
echo error in FROM
exit
fi
fi
if [[ "$TO" =~ "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$" ]]; then
echo error in TO
exit
fi
if [ -z "$5" ]; then
echo $BODY | mail -r $FROM -s $SUBJECT $TO
else
ATT=$5
ATTACHMENTS=""
attachments=$(check_files "$ATT")
for attachment in $attachments; do
ATTACHMENTS="$ATTACHMENTS $attachment"
done
echo $ATTACHMENTS
echo $BODY | mail -r $FROM -s $SUBJECT -A $ATTACHMENTS $TO
fi
echo email sent!
But when i send emails, i have the following behaviours:
- with/without attachments: If
$subjectis "some random theme", then the email is sent to$TOand[email protected],[email protected]andtheme@ mipc.localdomain. - without attachments:
$BODYis in the email body - with attachments: email body is empty
EDIT: thanks to @ilkkachu, first issue was fixed, new code:
#!/bin/bash
#sendGmail "FROM" "TO" "SUBJECT" "BODY" "ATTACHMENTS (optional)"
FROM=$1
TO=$2
SUBJECT=$3
BODY=$4
if [ "$FROM" == "" ]; then
FROM="[email protected]"
else
if [[ "$FROM" =~ "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$" ]]; then
echo error in FROM
exit
fi
fi
if [[ "$TO" =~ "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$" ]]; then
echo error in TO
exit
fi
if [ -z "$5" ]; then
echo "$BODY" | mail -r "$FROM" -s "$SUBJECT" "$TO"
else
ATT=$5
ATTACHMENTS=""
for attachment in $ATT; do
if [ -f $attachment ]; then
ATTACHMENTS="$ATTACHMENTS-A $attachment "
else
echo something wrong with $attachment, therefore not attached
fi
done
echo "$BODY" | mail -r "$FROM" -s "$SUBJECT" $ATTACHMENTS "$TO"
fi
echo email sent!