Почтовая кухня #1: DNS
Думаю, многим будет интересно наконец-то узнать, как работает почта. В нескольких статьях я попытаюсь максимально простым языком расписать все основные вопросы, связанные с работой электронной почты вообще и нужными настройками — в частности.
Для простоты и сокращения количества букв мы рассмотрим простейшую (и наиболее распространенную) ситуацию:
1 доменное имя (example.com).
1 почтовый домен (*@example.com).
1 почтовый сервер (mail.example.com).
1 IP-адрес (127.127.127.127).
Касательно почты, в DNS нас интересует четыре типа записей.
- A
- MX
- PTR
- TXT
Второй — обязательный, без него почта в 99% случаев не будет ходить вообще. Без остальных, в принципе, можно обойтись, но шансы, что ваше письмо будет отвергнуто как спам возрастают в разы — тот же mail.ru отбрасывает практически всю почту, чьи IP-адреса не имеют PTR, либо PTR относится к dial-up провайдерам. И это правильно.
A-запись
A (Address) — запись, указывающая IP-адрес нужного нам доменного имени. Для корректной работы почты требуется A-запись сервера почты (mail.example.com). Выглядеть, в нашем случае, она будет так:
mail IN A 127.127.127.127
Где:
mail — домен.
IN A — тип записи.
127.127.127.127 — IP нашего почтового сервера.
MX-записи.
MX (Mail eXchange) — основная DNS-запись для электопочты. Она указывает, какими серверами обрабатывается почта для нашего домена.
У нас есть один почтовый домен — example.com. И один почтовый сервер — mail.example.com. Соответственно, запись будет выглядеть так:
example.com. IN MX 10 mail.example.com
Где:
example.com — домен, для которого обробатывается почта.
IN MX — тип записи.
10 — приоритет записи (Подробнее — ниже).
mail.example.com — A-имя почтового сервера.
MX-запись должна указывать именно на A-запись почтового сервера. Ставить MX указателем на IP или CNAME — не правильно.
Приоритет MX-записи нужен тогда, когда существует больше одного почтового сервера для одного домена (например у Google Mail их шесть). Он указывает, к какому серверу идет обращение в первую очередь, во вторую и так далее (если первый (второй, десятый) сервер недоступен или перегружен или по другим причинам не может принять письмо). Логика простая — приоритетнее тот, цифра которого меньше. Порядок цифр — не ограничен, хоть 10-20-30, хоть 1000-2000-3000.
Если у домена нет ни одной MX-записи, либо ни один из MX-серверов не доступен, сервер отправителя попытается доставить почту на IP, указанный в A-записи домена. Это назвается А-доставкой, но в принципе не кошерно и не используется многими серверами — нужно указывать MX, даже если он всего один.
PTR-запись.
PTR (PoinTeR) — так называемая «обратная запись». Она позволяет обратное разрешение (reverse resolving) IP-адреса в FQDN-хост.
Наш IP в виде reverse будет выглядеть так: 127.127.127.127.in-addr.arpa. В данном примере видно плохо, но адрес инвертируется в обратной зоне. Т.е. IP 192.168.0.1 будет выглядеть как 1.0.168.192.in-addr.arpa.
Для корректного распознования хоста, запись IP-адреса, с которого отправляется должна соответсовать hostname почтового сервера, отправляемому в HELO\EHLO.
PTR-запись в нашем случае, соответственно:
127.127.127.127.in-addr.arpa IN PTR mail.example.com.
Прописать эту запись может владелец блока IP-адресов (Читайте мою статью про распределение адресного пространства). Если вы таковым не являетесь и получили адреса от провайдера — обращайтесь к вашему провайдеру или дата-центру, чтобы запись установил он.
TXT-запись и SPF.
TXT (TeXT) — текстовая запись DNS. Нам она интересна только тем, что может (и в современном мире — должна) содержать в себе SPF.
SPF (Sender Policy Framework) — запись, позволяющая вам указать, какие сервера имеют право отправлять почту от имени вашего домена (представившись вашим сервером, либо с обратным адресом в вашем домене).
Если этой записи нет, и кто-то пытается отправить письмо (как правило, спам) с обратным адресом в вашем домене — оно будет отклонено большинством серверов. Или не будет, и вы получите большие проблемы со своим дата-центром или провайдером и репутацию спамера 🙂
SPF-запись выглядит так:
v=spf1 ip4:1.1.1.1 +a +mx -all (пример).
v=spf1 — версия протокола.
(+\-)a — разрешение или запрет отправки почты с IP, соответствующего A-записи домена.
(+\-)mx — разрешение или запрет отправки почты с IP, соответствующего MX-записи домена.
ip4:IP — явное указание IP, с которого можно принимать почту от имени домена.
(
\-all) — отвергать или принимать почту от IP, не перечисленных в списке и не указанных явно.
В нашем случае TXT SPF запись будет такой:
example.com. IN TXT «v=spf1 +mx +a -all»
Таким образом, мы разрешили прием почты от имени домена с IP, соотвествующих A или MX записям и запретили прием от других адресов — никто не сможет наспамить прикинувшись нами или обмануть наших пользователей, отправив фишинговую ссылку от имени тех. поддержки.
Буду рад комментариям, готов ответить на вопросы.
В следующих статьях я напишу об SMTP, Greylisting-е и RBL.
А еще вы можете вступить в блог и тоже о чем-то рассказать.
Add MX Record in Windows DNS Server
MX record is a special type of DNS record that serves for the sole purpose of email communication. MX itself stands for Mail Exchanger and is a prerequisite when configuring email server. In other words, if your organization hosts an email server, then your DNS server should have MX record pointing to that email server. Without MX record, your email server is basically unrecognized by the others and there’s no way for them to be able to email you. In this post, we’re going to cover about how to Add MX Record in Windows DNS Server.
Steps to Add MX Record in Windows DNS Server
Just like the other types of DNS record, administrator can choose to use either DNS Manager or PowerShell to add MX record in Windows DNS server. But before we get to it, there are few things you should know:
- The first thing is that MX recordmust be created in a Forward Lookup zones and should be created under domain name that you are using as the email address suffix. For example, if you have a zone named mustbegeek.com and the email address suffix is “@something.mustbegeek.com” or simply just “@mustbegeek.com” then the MX record should be created under zone mustbegeek.com.
- Secondly, the email server should have a valid A record or CNAME record existing in the DNS server. So before you add the MX record, you have to add A record for the mail server, or it will be even better if you add CNAME record to hide the original mail server hostname.
- Lastly, the same MX record can be created repeatedly for pointing to different email servers. Each MX record will be given priority number and DNS server will lookup to the email server starting from the lowest number.
Now, see the scenario below to help you better understands the case:
You are domain administrator for mustbegeek.com and are required to setup MX record for the domain. AS-DCO001 is both the Domain Controller and DNS server for this network. The email address will be using “@mustbegeek.com” for the suffix address and must be utilizing two email servers in the network (AS-MBX001 as the primary email server and AS-MBX002 as the secondary).
Using DNS Manager to Add MX Record in Windows DNS Server
As the requirement in this scenario is to setup MX record for the domain mustbegeek.com, first you need to browse to the mentioned zone in the DNS Manager.

Right click on the zone name and select New Mail Exchanger (MX)…

The popup window below should appear.

Now you need to fill in the details in the popup:
- Host or child domain = Fill in this field according to the email address suffix that you want to use. Since the requirement is to use the email suffix “@mustbegeek.com” which is the parent domain itself, we’re going to leave this field blank. In other case you may want to fill in this field using a value, for example: “something”, if the email address suffix is “@something.mustbegeek.com”
- Fully qualified domain name (FQDN) of mail server = Fill in this field with the FQDN of the mail server or click Browse button and select the mail server A or CNAME record. For this scenario the FQDN for the first mail server is AS-MBX001.mustbegeek.com and for the second is AS-MBX002.mustbegeek.com.
- Mail server priority = Fill in the priority number, default is 10 but you can use any number between 0 and 65535 to define the priority. In the scenario, we’re giving priority 10 to the primary server and 20 for the secondary.
Optionally you can tick the option to “Delete this record when it becomes stale to allow aging” on the MX record. Also, you can modify the TTL value if necessary.
The screenshots below shows the two MX records configuration for the scenario:


Using PowerShell to Add MX Record in Windows DNS Server
To add MX record, run PowerShell as administrator then use cmdlets below:
Replace these parameters according to the requirement:
- PREF_NUMBER = Replace with the priority number
- MX_NAME = Replace with value according to the email suffix name. If you’re using parent domain as the suffix, replace this value with a dot (.).
- HOST_FQDN = Replace with the FQDN of the mail server (must be valid A or CNAME record in the DNS)
- ZONE_NAME = Replace with the zone name
Optional keyword
- [-AgeRecord] = Use if you want to allow aging on the MX record
- [-TimeToLive TTL_VALUE] = Use if you want to customize the TTL. Replace TTL_VALUE with value in HH:MM:SS format.
And here’s the PowerShell command for our scenario that matches the previous example:

Understanding the Role of MX Record
When someone sends email to @mustbegeek.com, the sender email server will first lookup for the available MX record for domain mustbegeek.com.

We have added two MX records as shown above. And these two records will point the sender of where to send the email packet. DNS server will resolve to the MX record with the lower priority number first. If for some reason the first email server is unavailable, then DNS will resolve it to the next MX record. With this way, others will be able to send email to mustbegeek.com domain.
Without having MX record, this whole process of sending email cannot be done. And this why it is important to learn to add MX record in Windows DNS server.