Ubuntu Linux自動發郵件配置及郵件發送腳本
測試環境:Ubuntu 11.10
1. 安裝mutt及msmtp軟件
[plain]
sudo apt-get install mutt
sudo apt-get install msmtp
2. 編輯配置文件vi ~/.muttrc
[plain]
set sendmail="/usr/bin/msmtp"
set use_from=yes
set realname="Guobao Jiang"
set
[email protected]
set envelope_from=yes
3.編輯配置文件vi ~/.msmtprc (賬號和密碼相應改動,最好把該文件屬性改為:
[plain]
chmod 700 ~/.msmtprc
其他人不能修改和查看)
[plain]
account default
host smtp.163.com
from
[email protected]
auth plain
user loveaborn
password ####
logfile ~/.msmtp.log
4.編寫自動發送郵件腳本,如下:
[plain]
#!/bin/bash
######################################################################################
# this shell script is used to send mail automatically
# the root structure is
# .
# ./autosend.sh -- this shell script
# ./attach/ -- this folder stored mail's all attachment.
# ./bak/ -- for backup
# ./log/ -- send & unsend log files
# ./mail/ -- mail text content, default file name './mail/mail.md'
# ./readme.md -- readme file (not mandatory)
# version: v0.1 @Aug. 4, 2013, by Guobao Jiang
######################################################################################
dateInfo="$(date +%Y-%m-%d-%H-%M-%S)"
attachName="attach_$dateInfo.tar.gz";
contentFile="./mail/mail.md"
toName="
[email protected]"
ccName="
[email protected]"
if [ -f ./mail/mail.md ]; then
if [ ! -f ./log/send.log ];then
touch ./log/send.log
fi
sendLog="./log/send.log"
tar zcvf $attachName ./attach
sleep 2
rm -rf ./attach/*
mkdir -p "./bak/mail_$dateInfo"
cp $attachName "./bak/mail_$dateInfo"
cp ./mail/mail.md "./bak/mail_$dateInfo"
echo -e " " >>$contentFile
echo -e "------------------" >> $contentFile
echo -e "Note: This mail is automaticall by my server." >> $contentFile
echo -e "BR// Guobao Jiang (
[email protected])" >> $contentFile
echo -e "DateRecord: $dateInfo" >> $contentFile
echo -e " " >>"$sendLog"
echo -e "-----------------------------------" >>"$sendLog"
echo -e "Sending mail..." >>"$sendLog"
mutt -s "Update Experiments Result $dateInfo" -c $ccName $toName \
-a $attachName< "$contentFile"
if [ $? -eq 0 ]; then
rm -rf $attachName
rm -rf ./mail/mail.md
#rm -rf ./attach/* # if success, delete all attachment files.
echo -e "mail was sent to $toName and cc to $ccName successully!" >> \
"$sendLog"
else
rm -rf $attachName
rm -rf "./bak/mail_$dateInfo"
echo -e "mail sent failed! Please try again!" >>"$sendLog"
fi
echo -e "RecordTime:$dateInfo" >>"$sendLog"
else
if [ ! -f ./log/record.log ]; then
touch ./log/nosend.log
fi
echo -e "No mail contents to send! RecordTime: $dateInfo" >>./log/nosend.log
fi
注意0: 文件autosend.sh,添加可執行屬性
[plain]
chmod u+x autosend.sh
注意1:附近 -a $attachName 放在最後,不然會出現如下錯誤:
[html]
Can’t stat
[email protected]: No such file or directory
[email protected]: unable to attach file.
注意2:我的郵件內容是放在./mail/mail.md文件裡的,發送完會備注到./bak下並刪除原來的文件。
目錄結構如下: