Ubuntu Linux自动发邮件配置及邮件发送脚本
测试环境:Ubuntu 11.10
1. 安装mutt及msmtp软件
sudo apt-get install mutt sudo apt-get install msmtp
2. 编辑配置文件vi ~/.muttrc
set sendmail="/usr/bin/msmtp" set use_from=yes set realname="Guobao Jiang" set from=loveaborn@163.com set envelope_from=yes
3.编辑配置文件vi ~/.msmtprc (账号和密码相应改动,最好把该文件属性改为:
chmod 700 ~/.msmtprc
其他人不能修改和查看)
account default host smtp.163.com from loveaborn@163.com auth plain user loveaborn password #### logfile ~/.msmtp.log
4.编写自动发送邮件脚本,如下:
#!/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="loveaborn@foxmail.com" ccName="loveaborn@163.com" 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 (loveaborn@foxmail.com)" >> $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,添加可执行属性
chmod u+x autosend.sh
注意1:附近 -a $attachName 放在最后,不然会出现如下错误:
Can’t stat loveaborn@foxmail.com: No such file or directory loveaborn@foxmail.com: unable to attach file.
注意2:我的邮件内容是放在./mail/mail.md文件里的,发送完会备注到./bak下并删除原来的文件。
目录结构如下:
参考链接:点击