使用 Postfix 从 Fedora 系统中获取电子邮件
Postfix 邮件
![](/data/attachment/album/201908/14/103600ommpur23nmmmmurz.jpg)


交流是非常重要的。你的电脑可能正试图告诉你一些重要的事情。但是，如果你没有正确配置邮件传输代理（[MTA](https://en.wikipedia.org/wiki/Message_transfer_agent)），那么你可能不会收到通知。Postfix 是一个[易于配置且以强大的安全记录而闻名](https://en.wikipedia.org/wiki/Postfix_(software))的 MTA。遵循以下步骤，以确保从本地服务发送的电子邮件通知将通过 Postfix MTA 路由到你的互联网电子邮件账户中。


### 安装软件包


使用 `dnf` 来安装一些必须软件包（[你应该配置了 sudo，对吧？](https://fedoramagazine.org/howto-use-sudo/)）：



```
$ sudo -i
# dnf install postfix mailx
```

如果以前配置了不同的 MTA，那么你可能需要将 Postfix 设置为系统默认。使用 `alternatives` 命令设置系统默认 MTA：



```
$ sudo alternatives --config mta
There are 2 programs which provide 'mta'.
  Selection    Command
*+ 1           /usr/sbin/sendmail.sendmail
   2           /usr/sbin/sendmail.postfix
Enter to keep the current selection[+], or type selection number: 2
```

### 创建一个 password\_maps 文件


你需要创建一个 Postfix 查询表条目，其中包含你要用于发送电子邮件账户的地址和密码：



```
# MY_EMAIL_ADDRESS=glb@gmail.com
# MY_EMAIL_PASSWORD=abcdefghijklmnop
# MY_SMTP_SERVER=smtp.gmail.com
# MY_SMTP_SERVER_PORT=587
# echo "[$MY_SMTP_SERVER]:$MY_SMTP_SERVER_PORT $MY_EMAIL_ADDRESS:$MY_EMAIL_PASSWORD" >> /etc/postfix/password_maps
# chmod 600 /etc/postfix/password_maps
# unset MY_EMAIL_PASSWORD
# history -c
```

如果你使用的是 Gmail 账户，那么你需要为 Postfix 配置一个“应用程序密码”而不是使用你的 Gmail 密码。有关配置应用程序密码的说明，参阅“[使用应用程序密码登录](https://support.google.com/accounts/answer/185833)”。


接下来，你必须对 Postfix 查询表运行 `postmap` 命令，以创建或更新 Postfix 实际使用的文件的散列版本：



```
# postmap /etc/postfix/password_maps
```

散列后的版本将具有相同的文件名，但后缀为 `.db`。


### 更新 main.cf 文件


更新 Postfix 的 `main.cf` 配置文件，以引用刚刚创建 Postfix 查询表。编辑该文件并添加以下行：



```
relayhost = smtp.gmail.com:587
smtp_tls_security_level = verify
smtp_tls_mandatory_ciphers = high
smtp_tls_verify_cert_match = hostname
smtp_sasl_auth_enable = yes
smtp_sasl_security_options = noanonymous
smtp_sasl_password_maps = hash:/etc/postfix/password_maps
```

这里假设你使用 Gmail 作为 `relayhost` 设置，但是你可以用正确的主机名和端口替换系统应该将邮件发送到的邮件主机。


有关上述配置选项的最新详细信息，参考 man 帮助：



```
$ man postconf.5
```

### 启用、启动和测试 Postfix


更新 `main.cf` 文件后，启用并启动 Postfix 服务：



```
# systemctl enable --now postfix.service
```

然后，你可以使用 `exit` 命令或 `Ctrl+D` 以 root 身份退出 `sudo` 会话。你现在应该能够使用 `mail` 命令测试你的配置：



```
$ echo 'It worked!' | mail -s "Test: $(date)" glb@gmail.com
```

### 更新服务


如果你安装了像 [logwatch](https://src.fedoraproject.org/rpms/logwatch)、[mdadm](https://fedoramagazine.org/mirror-your-system-drive-using-software-raid/)、[fail2ban](https://fedoraproject.org/wiki/Fail2ban_with_FirewallD)、[apcupsd](https://src.fedoraproject.org/rpms/apcupsd) 或 [certwatch](https://www.linux.com/learn/automated-certificate-expiration-checks-centos) 这样的服务，你现在可以更新它们的配置，以便它们的电子邮件通知转到你的 Internet 电子邮件地址。


另外，你可能希望将发送到本地系统 root 账户的所有电子邮件都转到互联网电子邮件地址中，将以下行添加到系统的 `/etc/alises` 文件中（你需要使用 `sudo` 编辑此文件，或首先切换到 `root` 账户）：



```
root: glb+root@gmail.com
```

现在运行此命令重新读取别名：



```
# newaliases
```

* 提示: 如果你使用的是 Gmail，那么你可以在用户名和 `@` 符号之间[添加字母数字标记](https://gmail.googleblog.com/2008/03/2-hidden-ways-to-get-more-from-your.html)，如上所示，以便更轻松地识别和过滤从计算机收到的电子邮件。


### 常用命令


**查看邮件队列：**



```
$ mailq
```

**清除队列中的所有电子邮件：**



```
# postsuper -d ALL
```

**过滤设置，以获得感兴趣的值：**



```
$ postconf | grep "^relayhost\|^smtp_"
```

**查看 `postfix/smtp` 日志：**



```
$ journalctl --no-pager -t postfix/smtp
```

**进行配置更改后重新加载 postfix：**



```
$ systemctl reload postfix
```



---


via: <https://fedoramagazine.org/use-postfix-to-get-email-from-your-fedora-system/>


作者：[Gregory Bartholomew](https://fedoramagazine.org/author/glb/) 选题：[lujun9972](https://github.com/lujun9972) 译者：[MjSeven](https://github.com/MjSeven) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
Communication is key. Your computer might be trying to tell you something important. But if your mail transport agent ([MTA](https://en.wikipedia.org/wiki/Message_transfer_agent)) isn’t properly configured, you might not be getting the notifications. Postfix is a MTA [that’s easy to configure and known for a strong security record](https://en.wikipedia.org/wiki/Postfix_(software)). Follow these steps to ensure that email notifications sent from local services will get routed to your internet email account through the Postfix MTA.

## Install packages

Use *dnf *to install the required packages ([you configured ](https://fedoramagazine.org/howto-use-sudo/)[sudo](https://fedoramagazine.org/howto-use-sudo/)[, right?](https://fedoramagazine.org/howto-use-sudo/)):

$ sudo -i # dnf install postfix mailx

If you previously had a different MTA configured, you may need to set Postfix to be the system default. Use the *alternatives* command to set your system default MTA:

$sudo alternatives --config mtaThere are 2 programs which provide 'mta'. Selection Command *+ 1 /usr/sbin/sendmail.sendmail 2 /usr/sbin/sendmail.postfix Enter to keep the current selection[+], or type selection number: 2

## Create a *password_maps* file

You will need to create a Postfix lookup table entry containing the email address and password of the account that you want to use to for sending email:

# MY_EMAIL_ADDRESS=glb@gmail.com # MY_EMAIL_PASSWORD=abcdefghijklmnop # MY_SMTP_SERVER=smtp.gmail.com # MY_SMTP_SERVER_PORT=587 # echo "[$MY_SMTP_SERVER]:$MY_SMTP_SERVER_PORT $MY_EMAIL_ADDRESS:$MY_EMAIL_PASSWORD" >> /etc/postfix/password_maps # chmod 600 /etc/postfix/password_maps # unset MY_EMAIL_PASSWORD # history -c

If you are using a Gmail account, you’ll need to configure an “app password” for Postfix, rather than using your gmail password. See “[Sign in using App Passwords](https://support.google.com/accounts/answer/185833)” for instructions on configuring an app password.

Next, you must run the *postmap* command against the Postfix lookup table to create or update the hashed version of the file that Postfix actually uses:

# postmap /etc/postfix/password_maps

The hashed version will have the same file name but it will be suffixed with *.db*.

## Update the *main.cf* file

Update Postfix’s *main.cf* configuration file to reference the Postfix lookup table you just created. Edit the file and add these lines.

relayhost = [smtp.gmail.com]:587 smtp_tls_security_level = verify smtp_tls_mandatory_ciphers = high smtp_tls_verify_cert_match = hostname smtp_sasl_auth_enable = yes smtp_sasl_security_options = noanonymous smtp_sasl_password_maps = hash:/etc/postfix/password_maps

The example assumes you’re using Gmail for the *relayhost* setting, but you can substitute the correct hostname and port for the mail host to which your system should hand off mail for sending.

For the most up-to-date details about the above configuration options, see the man page:

$ man postconf.5

## Enable, start, and test Postfix

After you have updated the main.cf file, enable and start the Postfix service:

# systemctl enable --now postfix.service

You can then exit your *sudo* session as root using the *exit* command or **Ctrl+D**. You should now be able to test your configuration with the *mail* command:

$ echo 'It worked!' | mail -s "Test: $(date)" glb@gmail.com

## Update services

If you have services like [logwatch](https://src.fedoraproject.org/rpms/logwatch), [mdadm](https://fedoramagazine.org/mirror-your-system-drive-using-software-raid/), [fail2ban](https://fedoraproject.org/wiki/Fail2ban_with_FirewallD), [apcupsd](https://src.fedoraproject.org/rpms/apcupsd) or [certwatch](https://www.linux.com/learn/automated-certificate-expiration-checks-centos) installed, you can now update their configurations so that their email notifications will go to your internet email address.

Optionally, you may want to configure all email that is sent to your local system’s root account to go to your internet email address. Add this line to the */etc/aliases* file on your system (you’ll need to use *sudo* to edit this file, or switch to the *root* account first):

root: glb+root@gmail.com

Now run this command to re-read the aliases:

# newaliases

- TIP: If you are using Gmail, you can
[add an alpha-numeric mark](https://gmail.googleblog.com/2008/03/2-hidden-ways-to-get-more-from-your.html)between your username and the**@**symbol as demonstrated above to make it easier to identify and filter the email that you will receive from your computer(s).

## Troubleshooting

**View the mail queue:**

$ mailq

**Clear all email from the queues:**

# postsuper -d ALL

**Filter the configuration settings for interesting values:**

$ postconf | grep "^relayhost\|^smtp_"

**View the postfix/smtp logs:**

$ journalctl --no-pager -t postfix/smtp

**Reload postfix after making configuration changes:**

$ systemctl reload postfix

*Photo by **Sharon McCutcheon** on Unsplash*.

## Caaaaarrrrlll

sSMTP is an easier alternative. https://wiki.archlinux.org/index.php/SSMTP

## Paul W. Frields

@Carl: When you’re talking about email, though, security is a real concern. It’s especially important if the system you’re using could trigger blacklisting or other side effects. Postfix has a good security stance and record (as well as longevity).

## Daniel

If security is the goal then OpenSMTPD is the go-to option.

## Dave Kimble

Configuring postfix is NOT easy. The only people that should attempt it are experts who know it all.

## Paul W. Frields

It’s not too hard to set up the simple configurations like this one. As a proof point, Greg figured it out for this article! You can do very complex things too, of course. Saying no one should do it sounds a lot like “no one should do Linux.” 😉

## Dokter

Are there ways to do this? Not using postfix.

Right now I get a message via Pushover that triggers a script in sshrc when I ssh into my box.

Beyond that I’ve failed to find a good solution, or optional solution that passes system messages via other means, such as the mentioned solution, triggering a script that might send the information via an API.

The solution above wasn’t easy to find might I add.

For system messages Pushover might not be well suited, but I’d consider using Mailgun and their API.

## Gregory Bartholomew

Hi Dokter:

Sorry, I haven’t really looked into alternatives beyond sendmail/postfix. The only alternative that comes to mind would be to use a sms gateway. I’ve never tried it though, so I really can’t vouch for how reliable it is.

## Guus Bonnema

When running the commands you suggested, I got a warning from postmap:

postmap: warning: /etc/postfix/password_maps, line 2: expected format: key whitespace value

So I changed the layout to servername space emailname followed by the same line for password with the “:” replaced by a space. Of course this did not work (I should have used a keyword-value stuff as the message indicated). So when I used exactly what you said it worked.

What is it with this message? Why do I get it? Why do I use a different layout (with [] and 🙂 to get it working?

## Paul W. Frields

This was a problem in the initial version but should be fixed now. Something got goofed up in the edits, because Greg’s original version was correct.

## Gregory Bartholomew

Hi Guus:

Glad you figured it out and sorry that the directions weren’t exactly correct initially.

The “key” in the password_maps file should match the value for “relayhost” in main.cf exactly (brackets and all).

If you are still seeing warnings about the formatting of the password_maps file, you might want to open the file with a text editor and delete any extra lines that might be left over from previous attempts.

The brackets around the relayhost address indicate that the address is for an SMTP server. Without the brackets the address is taken to be a domain name against which a MX record lookup should be done to find the address of the SMTP server. I think Google has patched their server in such a way that it might work without the brackets, but the MX mechanism has some limitations and you should probably use the brackets to get the best/nearest SMTP server. Google uses DNS to load balance their SMTP servers. You might be able to see it in action by running “nslookup smtp.gmail.com” several times consecutively.

As for

whythe syntax is what it is, I doubt there is a really good reason for it. A separate setting like “do_mx_lookup = false” would certainly be easier to understand.## GiP

I don’t understand…

I wanted to be able to use mail from my PC to send the results or errors from cron jobs and I did two things:

install postfix

enable postfix

And it just works! I can use a

mail -s “Cron job Log” myaddress <job.log

from the script.

Is all the other stuff really necessary?

G

## Gregory Bartholomew

Hi GiP:

That sort of auto-configuration is possible but, as I understand it, a couple of things are required that probably aren’t available in most people’s environment.

In order for MTA auto-configuration to work, you need:

A network administrator (or possibly a spambot) to configure option 69 on your DHCP server (or home router).

A open mail relay on your network (a SMTP server that requires neither authentication nor encryption).

If you are lucky enough that both the above conditions are met, then just turning the postfix service on will work. Unfortunately, I don’t think that is the case for most people, so they will have to explicitly configure Postfix to route their email through a mail server that they trust.

## GiP

Hi,

Thanks for the answer!

I see, but I don’t have either… On the other hand, as I said, I don’t want to receive mail, just send, and for this it seems that postfix can act as SMTP and (at least) Gmail and my own provider accept the messages without problems.

Well, Gmail has in the headers:

” best guess record for domain of gip@ designates as permitted sender)”.

But it just works….

Thanks again,

GiP

## GiP

Hi,

my reply was somehow mangled by the system…

The GM header should have been ” best guess record for domain of gip@ MYHOST designates MYIPADDRESS as permitted sender)”