Linux 发送邮件
Postfix
Postfix 是最常用的 MTA(Mail Transport Agent)。
- 
安装 Postfix 和必要组件: sudo apt update sudo apt install postfix mailutils libsasl2-modules安装过程中选择 "Internet Site",并设置系统邮件名称。 
- 
生成应用专用密码: 
- 
编辑 Postfix 主配置文件: sudoedit /etc/postfix/main.cf# 中继服务器 relayhost = [smtp.gmail.com]:587 # SASL 配置 smtp_sasl_auth_enable = yes smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd smtp_sasl_security_options = noanonymous smtp_sasl_tls_security_options = noanonymous # TLS 配置 smtp_use_tls = yes smtp_tls_security_level = encrypt smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt # 发件人映射 sender_canonical_maps = hash:/etc/postfix/sender_canonical
- 
创建 SASL 认证密码文件: sudoedit /etc/postfix/sasl_passwd[smtp.gmail.com]:587 gmail_address@gmail.com:app_password- 替换 gmail_address@gmail.com为你的 Gmail 地址
- 替换 app_password为应用专用密码
 保存后,设置权限: sudo chmod 600 /etc/postfix/sasl_passwd
- 替换 
- 
创建发件人地址重写规则文件: sudoedit /etc/postfix/sender_canonicalUSER@HOST gmail_address@gmail.com- 替换 USER为你的系统用户名
- 替换 HOST为你的系统主机名
 
- 替换 
- 
生成数据库文件: sudo postmap /etc/postfix/sasl_passwd sudo postmap /etc/postfix/sender_canonical
- 
重启 Postfix sudo systemctl restart postfix
- 
测试发送邮件 echo "Content" | mail -s "Subject" target_email@example.com # 发送邮件 mailq # 查看发件队列
msmtp
msmtp 是一个轻量级的 SMTP 客户端。对于只需使用外部 SMTP 服务器发送的邮件,msmtp 是最好的选择。
- 
安装: sudo apt install msmtp msmtp-mta # Ubuntu brew install msmtp # macOS
- 
编辑配置文件: vim ~/.msmtprc# 默认设置 defaults auth on tls on tls_trust_file /etc/ssl/certs/ca-certificates.crt logfile ~/.msmtp.log # Gmail 配置 account gmail host smtp.gmail.com port 587 tls_starttls on from your-email@gmail.com user your-email@gmail.com password your-app-password # 设置默认账户 account default : gmail设置配置文件权限: chmod 600 ~/.msmtprc
- 
发送简单邮件 echo "Content" | msmtp recipient@example.com
- 
配置 mail 默认使用 msmtp 发送邮件: vim ~/.mailrcset sendmail="/usr/bin/msmtp -t"
高级用法
发送 HTML 邮件:
cat << EOF | msmtp recipient@example.com
Subject: HTML 邮件
From: sender@example.com
To: recipient@example.com
Content-Type: text/html; charset=UTF-8
<html>
<body>
<h1>标题</h1>
<p>这是 HTML 邮件</p>
</body>
</html>
EOF
发送附件:
cat << EOF | msmtp recipient@example.com
Subject: 带附件的邮件
From: sender@example.com
To: recipient@example.com
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="boundary123"
--boundary123
Content-Type: text/plain; charset=UTF-8
邮件正文
--boundary123
Content-Type: application/octet-stream
Content-Disposition: attachment; filename="file.txt"
Content-Transfer-Encoding: base64
[base64 编码的文件内容]
--boundary123--
EOF
 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号