首页 > 解决方案 > 使用 mime 和 postfix 的多个电子邮件附件

问题描述

我有一个使用 mime 的电子邮件模板,其中包含 2 个附件占位符:

--MixedBoundaryString
Content-Type: text/plain
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="${filename1}"

${attachment1}

--MixedBoundaryString
Content-Type: text/plain
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="${filename2}"

${attachment2}
--MixedBoundaryString--

并创建 bash 脚本以在发送之前替换电子邮件内容和附件占位符。bash 脚本假设在当月的最后一天发送每日电子邮件的 1 个附件和 2 个附件。

以下是我的脚本的一部分,我在执行时设置了FILENAME2=""和,但得到了一个名为 ATT00001.txt 的附件。ATTACHMENT2=""sed

SUBJECT="TESTING"
FILENAME1="something"
FILENAME2=""
ATTACHMENT1=$(base64 attachment | tr -d '\n')
ATTACHMENT2=""

sed -e "s/\${subject}/$SUBJECT/" \
    -e "s/\${filename1}/$FILENAME1/" \
    -e "s/\${attachment1}/$ATTACHMENT1/" \
    -e "s/\${filename2}/$FILENAME2/" \
    -e "s/\${attachment2}/$ATTACHMENT2/"temp > email
    `sendmail -f $SENDER $RECIPIENTS < email`

我该如何解决?

提前致谢

标签: bashsedmime

解决方案


包 gettext 中可用的“envsubst”命令可能会有所帮助。基本上,您可以创建一个包含变量作为占位符的模板文本文件。我没有使用它,因为我不会像这样使用 bash,但我使用了一种叫做 twig 的东西,它的作用类似。

#!/bin/bash
#  sudo yum install gettext
mssg="This is a message"
filename="FILENAME"
ls /tmp/ > /tmp/result.txt
attach=$(base64 /tmp/result.txt)
email_file="/tmp/sendemail.txt"
template_email="/tmp/template-email.eml"

function build_email_temp() {

    > "${template_email}"
    echo "$mssg"  >> "${template_email}"
    echo "--MixedBoundaryString" >> "${template_email}"
    echo "Content-Type: text/plain" >> "${template_email}"
    echo "Content-Transfer-Encoding: base64" >> "${template_email}"
    echo "Content-Disposition: attachment; filename=${filename}" >> "${template_email}"
    echo "\${attachment}" >> "${template_email}"
    echo "--MixedBoundaryString-- " >> "${template_email}"
    echo ""  >> "${template_email}"

}

build_email_temp
export from='$from' to="$to" mssg='${mssg}' filename='$filename' attachment="$(echo $attach)"
MYVARS='$mssg:$filename:$result:$attachment'

envsubst "$MYVARS" < $template_email > $email_file
cat "$email_file"
mail -s "test" "email@address.com" < $email_file

推荐阅读