- Установка и настройка SMTP сервера на Windows Server 2016 / 2012 R2
- Установка службы SMTP на Windows Server 2016/2012 R2
- Настройка SMTP сервера на Windows Server
- Автозапуск службы SMTPSVC
- Проверка работы SMTP сервера на Windows Server
- Adam the Automator
- How to Build an IIS SMTP Relay Server
- June Castillote
- Prerequisites
- Install the IIS SMTP Server Windows Feature
- Using Server Manager
- Using PowerShell
- Import a certificate (for TLS only)
- Validate the Certificate
- Configure the IIS SMTP Server
- Add Allowed IPs in the IIS SMTP Server
- Confirm Certificate is Detected by the SMTP Server and Enable TLS Encryption
- Test the IIS SMTP Mail Relay Server
- Test with the Pickup Directory
- Test with PowerShell
- Summary
Установка и настройка SMTP сервера на Windows Server 2016 / 2012 R2
Вы можете установить SMTP сервер с помощью встроенных средств во всех версиях Windows Server. Такой SMTP сервер внутри организации может работать в качестве почтового релея, который должен принимать и пересылать через себя SMTP сообщения от различных устройств (к примеру, сендеров, сканеров, устройств СКД и пр.) и приложений (веб приложения, SQL Reporting Services, SharePoint), которым необходимо иметь возможность отправлять почту через SMTP сервер. Такой релей может пересылать сообщения на полноценные Exchange сервер или на публичные почтовые сервисы в Интернет типа Gmail, Mail.ru, Office 365 и т.д (ведь не всегда целесообразно разворачивать полноценную внутреннюю почтовую инфраструктуру на базе Microsoft Exchange Server или других почтовых служб).
В этой статье мы покажем, как установить, настроить и протестировать работу SMTP сервера на Windows Server 2012 R2, 2016 и 2019, который будет функционировать в качестве mail релея. Такой SMTP сервер не хранит почтовые сообщения и на нем отсутствуют почтовые ящики, он сможет только отправлять или пересылать почту.
Установка службы SMTP на Windows Server 2016/2012 R2
SMTP сервер – это один из компонентов Windows Server, который можно установить через Server Manager. Для этого откройте консоль Server Manager Dashboard (servermanager.exe), перейдите в режим Add roles and features и на этапе выбора функций отметьте чекбокс у пункта SMTP Server. Для управления службой SMTP нужно установить консоли управления, которые входят в комплект роли Web Server IIS (вам будет предложено установить IIS Management Tools).
Оставьте все предлагаемые опции роли Web Server (IIS) и запустите установку.
Также вы можете установить компонент SMTP сервера с помощью одной команды PowerShell:
После окончания установки компонентов может потребоваться перезагрузка системы.
Настройка SMTP сервера на Windows Server
Управляется SMTP сервер консоль управления Internet Information Services (IIS) Manager 6. Открыть эту консоль можно через Server Manager: Tools-> Internet Information Services (IIS) 6.0 Manager или командой inetmgr6.exe.
В консоли IIS 6 Manager разверните ветку с именем сервера, щёлкните ПКМ по SMTP Virtual Server и откройте его свойства.
На вкладке General, если необходимо, выберите IP адрес, на котором должен отвечать SMTP сервер (если у сервера несколько IP адресов), и включите ведение логов Enable logging (чтобы сохранялась информация обо всех полученных письмах).
Затем перейдите на вкладку Access.
Здесь нажмите на кнопку Authentication и убедитесь, что разрешен анонимный доступ (Anonymous access).
Вернитесь на вкладку Access и нажмите кнопку Connection. Здесь вы можете указать IP адреса устройств, которым разрешено отправлять почту через наш SMTP релей. Нужно выбрать опцию Only the list below и указать список IP адресов, не забыв самого себя (127.0.0.1).
Аналогичным образом настройте список разрешенных IP в настройках Relay (нажмите соответствующую кнопку). В этой секции указано каким IP адресам (или подсетям) можно пересылать почту через ваш SMTP сервер.
Перейдите на вкладку Messages. Здесь указывается email, на который будут отправляться копии всех NDR отчетов (Send copy of Non-Delivery Report to:). Также здесь можно указать ограничения на максимальный размер писем (Limit message size KB) и количество получателей (Limit number of recepients per message).
Перейдите на вкладку Delivery:
Затем нажмите на кнопку Outbound Security. Здесь указывается, как нужно авторизоваться на почтовом сервере, на который ваш SMTP-сервере будет пересылать (relay) всю почту. К примеру, если вся почта будет отправляться на почтовый сервер Gmail и уже с него пересылаться адресатам, вам нужно выбрать тип аутентификации Basic authentication, указав в качестве пользователя и пароля данные для доступа к почтовому ящику на сервисе Gmail (в настройках аккаунта Google нужно разрешить отправку через smtp сервера gmail).
Затем нажмите на кнопку Advanced.
Здесь указывается FQDN имя вашего SMTP сервера. Нажмите кнопку Check DNS, чтобы проверить корректность записи в DNS.
Если сервер должен пересылать почту внешнему smtp серверу, нужно указать его имя в поле Smart host (к примеру smtp.gmail.com или smtp.office365.com).
Сохраните настройки SMTP сервера и перезапустите ваш виртуальный SMTP сервер для применения изменений.
- Настройки DNS критичны с точки зрения работоспособности почтовой системы. Если ваш SMTP сервер не может корректно разрешить DNS имена доменов, на которые он пытается отправить письма, доставка не удастся.
- Если ваш сервер сам будет отправлять почту в другие домены, важно, чтобы для вашего адреса была сформирована правильная PTR запись для разрешения обратных DNS запросов. PTR запись для белого IP адреса должна указывать на FQDN имя. В противном случае большинство внешних smtp серверов не будут принимать от вас почту, считая ваш сервер спамерским.
Автозапуск службы SMTPSVC
Осталось настроить автозапуск службы SMTP сервера. Быстрее всего это сделать из командной строки PowerShell:
set-service smtpsvc -StartupType Automatic
Проверим, что запущена служба SMTPSVC :
Проверка работы SMTP сервера на Windows Server
Ну и последнее, что осталось сделать, проверить работу созданного SMTP сервера. Проще всего это сделать, создав на рабочем столе текстовый файл smtp-test-email.txt и скопировав в него следующий текст, заменив имя отправителя и получателя на ваши.
From: server@localdomain.com
To: admin@localdomain.com
Subject: Email test
This is the test email
Скопируйте файл smtp-test-email.txt в каталог C:\inetpub\mailroot\Pickup. SMTP сервер следит за появлением файлов в этой каталоге и при обнаружении файла прочтет его содержимое и попытается отправить письмо с данной темой и текстом адресату, указанному в разделе To:.
Проверьте ящик получателя, в него должно прийти такое письмо.
Send-MailMessage -SMTPServer localhost -To admin@localdomain.com -From server@localdomain.com -Subject «Email test» -Body «This is the test email sent via PowerShell»
Если вы хотите, чтобы вы включили Basic Authentication (Обычная проверка подлинности) для авторизации всех ваших SMTP клиентов (вместо анонимной аутентификации), вы можете отправить письмо с smtp-аутентификацией через telnet следующим образом.
Также убедитесь, что на вашем SMTP сервере не блокируется порт TCP 25 при удаленном подключении (локальным файерволом, антивирусом или межсетевым экраном). Проще всего это сделать с компьютера Windows, IP адрес которого добавлен в разрешенные. Проверку доступности порта можно выполнить с помощью командлета Test-NetConnection:
Test-NetConnection smtpsrv1.name.local –port 25
Если 25 порт блокируется, проверьте настройки Windows Firewall, антивируса и аппаратных межсетевых экранов.
Итак, вы настроили собственный почтовый SMTP релей на Windows Server 2016/2012 R2 и протестировали отправку писем через него.
Adam the Automator
How to Build an IIS SMTP Relay Server
June Castillote
Read more posts by this author.
Microsoft IIS can serve the role of an SMTP quite nicely but requires quite a few steps to get set up. Lucky for you, I’ve set up an IIS SMTP relay server and documented all of the steps!
In this article, we will cover all of the steps needed to successfully set up an SMTP relay server to send an outgoing email with Office 365. Technically, we will use this SMTP relay to relay email to Office 365; it can just as quickly work for any general SMTP relay mail delivery purposes.
Table of Contents
Prerequisites
To get IIS set up and follow along with me, be sure you have a Windows Server 2016 machine available. I’ll also be assuming you are logged into the server as an administrator.
Install the IIS SMTP Server Windows Feature
The first task you’ll need to do to get an IIS SMTP relay set up is to install the IIS SMTP Server. You’ll need to install the SMTP Server Windows feature.
Using Server Manager
If you’re unfamiliar with installing Windows features via Server Manager, check out this article entitled Install or Uninstall Roles, Role Services or Features.
Using PowerShell
Installing the SMTP Server feature removes a lot of point and clicking. Open up a PowerShell console as administrator and run the line below:
Wait for the installation to finish. You should see an output similar to this.
Import a certificate (for TLS only)
If you’ll be sending e-mail via TLS (Office 365), you need to import an SSL certificate in the server’s local machine personal certificate store before you configure the IIS SMTP Server. You can skip this step if your Office 365 SMTP relay is non-TLS.
If you don’t have a certificate, you can get one via your internal PKI (if you have that) or a public certificate using services like LetsEncrypt, Digicert, etc.
Once you have the certificate, you’ll need to import it into the local machine personal certificate store. If you’re unfamiliar with how to import certificates using the Certificates MMC, check out Import and Export Certificate – Microsoft Windows.
When successful, you should get a confirmation window like this. Click OK (1) to confirm.
Back in the main console window, refresh the Personal > Certificates folder and you should be able to see the imported certificate.
Validate the Certificate
Once imported, be sure to verify that the certificate chain is complete and that there are no errors. If all is well, you should be able to open the certificate and see the Valid From field is current and there is a private key associated with the certificate. An example is shown below.
On the Certification Path tab, you should also see a Certificate status stating that the certificate is OK as shown below.
Configure the IIS SMTP Server
You have successfully installed the SMTP server at this point. But before you can use it, the server settings must be configured first.
The SMTP server is running on IIS6 Compatibility mode and it does not come with built-in PowerShell support. This means that you will configure the settings manually using the IIS6 Management Console.
Go to Start –> Run and type in inetmgr6 and hit Enter. This will open the IIS 6 console.
Once the console is open, right-click on [SMTP Virtual Server #1] (1), then select Properties (2).
In the Properties window, check Enable logging (1), then click Properties (2).
Go to the Advanced tab, and check all the boxes in the list (1), then click OK (2).
Back in the Properties window, go to the Delivery tab and click on Advanced (1).
In the Advanced Delivery window, type in the Fully-qualified domain name (1) you’d like to use for the destination SMTP mail server. It does not have to be the same as the FQDN of the computer itself. If you’re configuring this SMTP server to use with Office 365, in the Smart host (2) field, define your Office 365 MX endpoint. and click OK (3).
Add Allowed IPs in the IIS SMTP Server
Now if you have a device that you want to test, you must add its IP address to the relay restrictions first. For this example, the IP address 192.168.0.3 will be added to the relay restrictions. This IP address belongs to a computer that is within the same network as the server.
To add an allowed IP in the relay restrictions, go to the Access tab and click on Relay (1).
Inside the Relay Restrictions window, click Add (1).
Then type in the IP address (1) you’d like to allow then click OK (2).
Back in the Relay Restrictions window, confirm that the IP address is added to the list, then click OK (1) and OK out of the properties window.
Confirm Certificate is Detected by the SMTP Server and Enable TLS Encryption
If your relay server will be sending outbound email via TLS, you’ll need to confirm the certificate is seen by the IIS SMTP Server and enable TLS encryption.
On the Access tab of the SMTP Server properties, you should see a message stating “A TLS certificate is found with expiration date: XXXXXX”. If so, you’re good to go.
Next, click on the Delivery tab, click on Outbound Security (1), check the TLS encryption (2) box, click OK (3).
This concludes the IIS SMTP Server configuration steps.
Test the IIS SMTP Mail Relay Server
At this point, your SMTP Server should be configured and ready to begin relaying mail. The next step is to test it. You should now test sending email through the SMTP relay to confirm the receiving SMTP server gets the message.
Test with the Pickup Directory
When IIS SMTP Server is installed, it will create a folder on the server at C:\inetpub\mailroot\Pickup. This directory is where the SMTP service picks up newly submitted emails for processing before moving them to the Queue directory.
To test using this method, create a plain text file with content similar to this:
Do not forget to change the From and To values to your own.
Now save this file somewhere other than the pickup directory as mail.txt.
Once you’ve saved the file, copy and paste the file into the C:\inetpub\mailroot\Pickup folder. If successful, the file should quickly disappear. This means that the SMTP service has picked it up and has started processing the message.
After a few seconds to a minute, you should receive the email sent to the specified recipient email address defined in mail.txt.
Test with PowerShell
In this test, you will use PowerShell from the computer whose IP address you added in the Add Allowed IPs in the IIS SMTP Server section.
Open up a PowerShell console and copy/paste the code below. Be sure to edit the values for the From , To and SmtpServer parameters. Depending on how you configured the relay server above, you can use either example below to test a non-TLS or TLS setup.
Summary
In this article, you’ve learned how to set up an IIS SMTP relay server for recipient email delivery from Office 365. We covered setting up both a non-TLS and TLS SMTP server using a combination of the GUI and PowerShell. We then tested our setup using PowerShell to confirm all is well.