从终端发送电子邮件不良行为

从终端发送电子邮件不良行为

我有以下脚本,我从网络上将其放在一起,通过 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!

但是当我发送电子邮件时,我有以下行为:

  • 带/不带附件:如果$subject是“某些随机主题”,则电子邮件将发送至$TO[email protected][email protected]theme@ mipc.localdomain
  • 不带附件:$BODY位于电子邮件正文中
  • 带附件:电子邮件正文为空

编辑:感谢@ilkkachu,第一个问题已修复,新代码:

#!/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!

答案1

那是因为分词。如果SUBJECT包含some random theme,则mail -s $SUBJECT与 相同mail -s some random theme。的内容$subject在空白处被分割成单词。您需要使用引号:mail -s "$SUBJECT"

关于附件,您可能需要为每个文件添加选项,因此您可能需要-A而不是.如果您的文件名不包含空格,您可以通过为每个文件名添加in来做到这一点,例如:然后在命令中单独使用(您不需要在这里使用引号,因为选项和文件名需要分开)。-A file1 file2-A file1 -A file2-AATTACHMENTSATTACHMENTS="$ATTACHMENTS -A $attachment"$ATTACHMENTSmail

正确的方法当然是使用数组来保存命令行参数,但您的for循环已经导致附件上的分词,因此数组无济于事。

所以:

for f in files... ; do
    ATTACHMENTS="-A $f"
done
echo "$BODY" | mail -r "$FROM" -s "$SUBJECT" $ATTACHMENTS "$TO"

我还假设您已经检查了获取附件的mail用途。-A有很多版本mail,我发现的版本都不知道该选项。例如,那个手册页位于 die.net 上用于-a附件,用于-A其他用途。因此,您可能需要仔细检查它是否不起作用。

相关内容