介绍了在 Ubuntu 系统上使用 mailx 和 Postfix 发送 SMTP 邮件的配置方法。步骤包括安装 mailx 和 Postfix,配置 Postfix 通过外部 SMTP 服务器(例如 Amazon SES)发送邮件,设置 TLS 加密和 SASL 认证,生成并保护认证文件,以及如何测试邮件发送。博客还介绍了如何通过 ~/.mailrc 文件设置自定义发件人地址。
Ubuntu 上发送 SMTP 邮件,使用 mailx 和 Postfix 结合是一个常见的方式。以下是如何正确配置并通过 mailx 使用 SMTP 发送邮件的步骤。
- 安装 mailx 和 Postfix
确保你已经安装了 mailx 和 Postfix。
1 2
| sudo apt update sudo apt install mailx postfix
|
- 配置 Postfix
配置 Postfix 为通过外部 SMTP 服务器发送邮件。这里以 Gmail 为例,如果你使用其他 SMTP 服务器(例如 Amazon SES),替换相应的配置信息。
修改 /etc/postfix/main.cf
编辑 Postfix 配置文件 /etc/postfix/main.cf:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)
biff = no
append_dot_mydomain = no
readme_directory = no
compatibility_level = 3.6
smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
smtpd_tls_security_level=may
smtp_tls_CApath=/etc/ssl/certs
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
myhostname = localhost.localdomain
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
myorigin = /etc/mailname
mydestination = $myhostname, toimc.com, localhost.localdomain, localhost.localdomain, localhost
relayhost = [email-smtp.us-east-1.amazonaws.com]:587
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
inet_protocols = all
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
smtp_tls_security_level = encrypt
smtp_tls_note_starttls_offer = yes
smtp_use_tls = yes
smtputf8_enable = no
|
- (可选)创建
~/.mailrc指定发送人:
1
| set from=no-reply@toimc.com
|
- 创建密码文件
vi /etc/postfix/sasl_passwd
类似下面的结构: [smtp.domain]:port username:password
例如:
1
| [email-smtp.us-east-1.amazonaws.com]:587 AKIAT7WPVYWC25C2WBJW:你的SMTP密码
|
权限 sudo chmod 600 /etc/postfix/sasl_passwd
哈希 sudo postmap /etc/postfix/sasl_passwd
重启服务 systemctl restart postfix
- 测试
1
| echo "Test email body" | mail -s "这是一个邮件测试" yourmail@domain.com
|