如何以适当的格式发送邮件

时间:2016-05-26 10:50:00

标签: bash email ubuntu

我有一个简单的脚本来执行系统更新并发送有关状态的邮件:

echo '===============================\n' > mylog.log
sudo apt-get update -y >> mylog.log
if [ $? -eq 0 ]; then
    echo 'completed successfully\n' >> mylog.log
else
    echo 'FAILED\n' >> mylog.log
fi
echo '===============================' >> mylog.log
sudo apt-get dist-upgrade -y >> mylog.log
if [ $? -eq 0 ]; then
    echo 'completed successfully\n' >> mylog.log
else
    echo 'FAILED\n' >> mylog.log
fi
echo 'sending mail\n' >> mylog.log 
mailx -aFrom:test@mymail.com -a 'Content-Type: text/html' -s "Updates @`date`" chaitanya@mymail.com < mylog.log

该程序运行正常,我收到邮件。但邮件没有任何新的行。这是邮件的内容:

=============================== Hit http://security.ubuntu.com precise-security/multiverse Translation-en Hit http://security.ubuntu.com precise-security/restricted Translation-en Hit http://security.ubuntu.com precise-security/universe Translation-en Reading package lists... completed successfully =============================== Reading package lists... Building dependency tree... Reading state information... 0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded. completed successfully sending mail

邮件以单行显示,不是可读格式。如果我打开日志文件mylog.log,它的格式是正确的新行。

=============================== 
Hit http://security.ubuntu.com precise-security/multiverse Translation-en 
Hit http://security.ubuntu.com precise-security/restricted Translation-en 
Hit http://security.ubuntu.com precise-security/universe Translation-en 
Reading package lists... 
completed successfully 
=============================== 
Reading package lists... 
Building dependency tree... 
Reading state information... 0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded. 
completed successfully 
sending mail

如何以正确的可读格式发送邮件?

更新 在代码中使用了printf,但问题相同。

printf '%b' '===============================\r\n' > mylog.log
    sudo apt-get update -y >> mylog.log
    if [ $? -eq 0 ]; then
        printf '%b' 'completed successfully\r\n' >> mylog.log
    else
        printf '%b' 'FAILED\n' >> mylog.log
    fi
    printf '%b' '===============================' >> mylog.log
    sudo apt-get dist-upgrade -y >> mylog.log
    if [ $? -eq 0 ]; then
        printf '%b' 'completed successfully\r\n' >> mylog.log
    else
        printf '%b' 'FAILED\n' >> mylog.log
    fi
    printf '%b' 'sending mail\n' >> mylog.log 
    mailx -aFrom:test@mymail.com -a 'Content-Type: text/html' -s "Updates @`date`" chaitanya@mymail.com < mylog.log

3 个答案:

答案 0 :(得分:1)

我建议使用:

printf '%b' 'text\r\n'

答案 1 :(得分:1)

您声明内容是HTML,但显然您发送的内容是一个简单的文本文件。添加HTML格式以使其按预期显示,或者将其作为text/plain发送。 (就个人而言,我会强烈建议后者。)

答案 2 :(得分:0)

待办事项

echo -e '===============================\n'

默认情况下,bash不会解释反斜杠。