最近需要在服务器上运行一些时间很长的命令,想让服务器自动通知我什么时候命令完成,通过命令结束后发送邮件给我来提醒。

安装 msmtp 和 mail

# RedHat 系
sudo dnf install msmtp mailx
# Debian 系
sudo apt install msmtp mailutils

配置 msmtp

创建或编辑.msmtprc,内容示例如:

# Set default values for all following accounts.
defaults
auth           on
tls            on
tls_trust_file /etc/ssl/certs/ca-certificates.crt
logfile        ~/.msmtp.log

# Gmail example
account        gmail
host           smtp.gmail.com
port           587
from           your_email@gmail.com
user           your_email@gmail.com
password       your_password

# Set a default account
account default : gmail

其中hostport根据不同的邮箱而异,fromuser为发送邮件使用的邮箱账号,password需要在邮箱设置中开启SMTP时创建的专用密码。

设置权限

设置.msmtprc文件的权限,使得只有所有者可以读取或写入:

chmod 600 ~/.msmtprc

测试邮件发送

echo "This is the body of the email" | mail -s "This is the subject line" your_email@example.com

echo的内容是邮件内容,-s后面的字符串为邮箱主题,最后一个参数是收件邮箱,如果用户密码等配置无误的话,登录收件邮箱应该可以看到邮件,找不到的话看看垃圾箱,这类邮件可能会自动放入垃圾箱。