Как проверить smtp сервер через telnet
Перейти к содержимому

Как проверить smtp сервер через telnet

  • автор:

Use Telnet to test SMTP communication

This topic explains how to use Telnet to test Simple Mail Transfer Protocol (SMTP) communication between messaging servers. By default, SMTP listens on port 25. If you use Telnet on port 25, you can enter the SMTP commands that are used to connect to an SMTP server and send a message exactly as if your Telnet session was an SMTP messaging server. You can see the success or failure of each step in the connection and message submission process.

Here are the scenarios where you may want to use Telnet to test SMTP communication to or from the transport servers that exist in your Microsoft Exchange organization:

  • Connect to your organization’s Internet-facing Exchange server from a host that is located outside your perimeter network and send a test message.
  • Connect to a remote messaging server from your organization’s Internet-facing Exchange server and send a test message.

The procedure in this topic shows you how to use Telnet Client, which is a component that is included with Microsoft Windows. Third-party Telnet clients may require a syntax that is different from that of the Windows Telnet component.

What do you need to know before you begin?

  • Estimated time to complete: 30 minutes
  • Exchange permissions don’t apply to the procedures in this topic. These procedures are performed in the operating system of the Exchange Server or a client computer.
  • The procedures in this topic are best used to connect to and from Internet-facing servers that allow anonymous connections. Message transmission between internal Exchange servers is encrypted and authenticated. To use Telnet to connect to the Hub Transport service on a Mailbox server, you’ll need to create a Receive connector that’s configured to allow anonymous access or Basic authentication to receive messages. If the connector allows Basic authentication, you need a utility to convert the text strings that are used for the username and password into the Base64 format. Because the username and password are easily discernible when Basic authentication is used, we don’t recommend Basic authentication without encryption.
  • If you connect to a remote messaging server, consider performing the procedures in this topic on your Internet-facing Exchange server. This will help to avoid rejection of the test message by remote messaging servers that are configured to validate the source IP address, the corresponding domain name system (DNS) domain name, and the reverse lookup IP address of any Internet host that tries to send a message to the server.
  • For information about keyboard shortcuts that may apply to the procedures in this topic, see Keyboard shortcuts in the Exchange admin center.

Having problems? Ask for help in the Exchange forums. Visit the forums at Exchange Server.

Step 1: Install the Telnet Client in Windows

By default, the Telnet Client isn’t installed in most client or server versions of the Microsoft Windows operating systems. To install it, see Install Telnet Client.

Step 2: Use Nslookup to find the FQDN or IP address in the MX record of the remote SMTP server

To connect to a destination SMTP server by using Telnet on port 25, you must use the fully qualified domain name (FQDN) or the IP address of the SMTP server. If the FQDN or IP address is unknown, the easiest way to find this information is to use the Nslookup command-line tool to find the MX record for the destination domain.

  1. At a command prompt, type nslookup, and then press ENTER. This command opens the Nslookup session.
  2. Type set type=mx and then press ENTER.
  3. Type set timeout=20 and then press ENTER. By default, Windows DNS servers have a 15-second recursive DNS query time-out limit.
  4. Type the name of the domain for which you want to find the MX record. For example, to find the MX record for the fabrikam.com domain, type fabrikam.com., and then press ENTER.

Note The trailing period ( . ) indicates a FQDN. The use of the trailing period prevents any default DNS suffixes that are configured for your network from being unintentionally added to the domain name.

The output of the command will resemble the following:

fabrikam.com mx preference=10, mail exchanger = mail1.fabrikam.com fabrikam.com mx preference=20, mail exchanger = mail2.fabrikam.com mail1.fabrikam.com internet address = 192.168.1.10 mail2 fabrikam.com internet address = 192.168.1.20 

Firewall or Internet proxy restrictions that are imposed on your organization’s internal network may prevent you from using the Nslookup tool to query public DNS servers on the Internet.

Step 3: Use Telnet on Port 25 to test SMTP communication

In this example, the following values are used:

  • Destination SMTP server: mail1.fabrikam.com
  • Source domain: contoso.com
  • Sender’s e-mail address: chris@contoso.com
  • Recipient’s e-mail address: kate@fabrikam.com
  • Message subject: Test from Contoso
  • Message body: This is a test message
  • The commands in Telnet Client are not case-sensitive. The SMTP command verbs are capitalized for clarity.
  • You can’t use the backspace key after you have connected to the destination SMTP server within the Telnet session. If you make a mistake as you type an SMTP command, you must press ENTER and then type the command again. Unrecognized SMTP commands or syntax errors result in an error message that resembles the following:
500 5.3.3 Unrecognized command 
  1. At a command prompt, type telnet, and then press ENTER. This command opens the Telnet session.
  2. Type set localecho and then press ENTER. This optional command lets you view the characters as you type them. This setting may be required for some SMTP servers.
  3. Type set logfile. This optional command enables logging of the Telnet session to the specified log file. If you only specify a file name, the location of the log file is the current working directory. If you specify a path and a file name, the path must be local to the computer. Both the path and the file name that you specify must be entered in the Microsoft DOS 8.3 format. The path that you specify must already exist. If you specify a log file that doesn’t exist, it will be created for you.
  4. Type open mail1.fabrikam.com 25 and then press ENTER.
  5. Type EHLO contoso.com and then press ENTER.
  6. Type MAIL FROM:chris@contoso.com and then press ENTER.
  7. Type RCPT TO:kate@fabrikam.com NOTIFY=success,failure and then press ENTER. The optional NOTIFY command defines the particular delivery status notification (DSN) messages that the destination SMTP server must provide to the sender. DSN messages are defined in RFC 1891. In this case, you’re requesting a DSN message for successful or failed message delivery.
  8. Type DATA and then press ENTER. You will receive a response that resembles the following:
354 Start mail input; end with .
250 2.6.0 Queued mail for delivery 
221 2.0.0 Service closing transmission channel 

Step 4: Evaluate the Results of the Telnet Session

This section provides information about responses that may be provided to the following commands, which were used in the previous example:

  • Open mail1.fabrikam.com 25
  • EHLO contoso.com
  • MAIL FROM:chris@contoso.com
  • RCPT TO:kate@fabrikam.com NOTIFY=success,failure

Note The 3-digit SMTP response codes that are defined in RFC 2821 are the same for all SMTP messaging servers. The text descriptions may differ slightly for some SMTP messaging servers.

Open mail1.fabrikam.com 25

Successful Response: 220 mail1.fabrikam.com Microsoft ESMTP MAIL Service ready at

Failure Response: Connecting to mail1.fabrikam.com. Could not open connection to the host, on port 25: Connect failed

Possible Reasons for Failure:

  • The destination SMTP service is unavailable.
  • There are restrictions on the destination firewall.
  • There are restrictions on the source firewall.
  • An incorrect FQDN or IP address for the destination SMTP server was specified.
  • An incorrect port number was specified.

EHLO contoso.com

Successful Response: 250 mail1.fabrikam.com Hello []

Failure Response: 501 5.5.4 Invalid domain name

Possible Reasons for Failure: There are invalid characters in the domain name. Alternatively, there are connection restrictions on the destination SMTP server.

EHLO is the Extended Simple Message Transfer Protocol (ESMTP) verb that is defined in RFC 2821. ESMTP servers can advertise their capabilities during the initial connection. These capabilities include their maximum accepted message size and their supported authentication methods. HELO is the older SMTP verb that is defined in RFC 821. Most SMTP messaging servers support ESMTP and EHLO.

MAIL FROM:chris@contoso.com

Successful Response: 250 2.1.0 Sender OK

Failure Response: 550 5.1.7 Invalid address

Possible Reasons for Failure: There is a syntax error in the sender’s e-mail address.

Failure Response: 530 5.7.1 Client was not authenticated

Possible Reasons for Failure: The destination server does not accept anonymous message submissions. You receive this error if you try to use Telnet to submit a message directly to a Hub Transport server.

RCPT TO:kate@fabrikam.com NOTIFY=success,failure

Successful Response: 250 2.1.5 Recipient OK

Failure Response: 550 5.1.1 User unknown

Possible Reasons for Failure: The specified recipient does not exist in the organization.

Записки IT специалиста

Очень часто перед администратором встает необходимость проверить работу почтового сервера по протоколу SMTP, как своего, так и чужого. Обычно это связано с проблемами отправки или получения почты и следует не только убедиться в доступности сервера, но и понять, что происходит с письмом дальше. Несмотря на то, что существуют различные сервисы для диагностики почтовых систем, лучше всего проверить работу сервера подключившись к нему через Telnet и отправив письмо при помощи SMTP-команд, получив необходимую информацию, что называется «из первых рук».

Онлайн-курс по устройству компьютерных сетей
На углубленном курсе «Архитектура современных компьютерных сетей» вы с нуля научитесь работать с Wireshark и «под микроскопом» изучите работу сетевых протоколов. На протяжении курса надо будет выполнить более пятидесяти лабораторных работ в Wireshark.

Несмотря на кажущуюся сложность этого метода, он достаточно прост и необходимость ручного ввода SMTP-команд не должна вас пугать. Зато вы сможете получить всю необходимую для диагностики информацию прямо здесь и сейчас, не оглядываясь на возможности и ограничения сторонних сервисов.

Поставим себе некую задачу. Допустим мы хотим проверить доставку почты c некого ящика example@interface31.ru на ящик test@host31.ru, а также проверить работу сервера в некоторых иных ситуациях.

Прежде всего сразу следует выяснить какой узел в указанном домене отвечает за прием почты, это следует сделать даже если вы знаете точный адрес этого сервера, так как позволит выявить возможные ошибки при настройке DNS. Для этого мы будем использовать утилиту nslookup, в Windows она входит в штатный комплект поставки, а в Linux вам возможно потребуется установить пакет dnsutils.

Для получения записей MX-хостов узла (т.е. серверов, принимающих почту) выполним:

nslookup -type=mx host31.ru

В качестве ответа вы должны получить имя одного или нескольких серверов.

smtp-telnet-test-001.png

В нашем случае почта обслуживается серверами Яндекса, а именно mx.yandex.net, с которым мы и будем работать. Для дальнейших действий нам потребуется telnet-клиент, в Linux он есть из коробки, в Windows его следует установить в дополнительных компонентах или использовать любой сторонний клиент, поддерживающий этот протокол, например, PuTTY. В нашем примере будет использоваться telnet-клиент в Debian 10.

Прежде всего запустим самого клиента:

telnet

в ответ мы увидим строку приглашения, куда введем строку соединения с сервером, обычно используется порт 25, но могут также быть 465 или 587:

OPEN mx.yandex.net 25

В ответ мы должны получить сообщение с кодом 220, которое содержит имя узла, работающего с нами.

smtp-telnet-test-002.png

Обратите внимание, что оно отличается от адреса, к которому мы подключались. Это связано с тем, что почту могут обслуживать несколько серверов и при обращении к домену mx.yandex.net каждый раз будет выдаваться разный адрес, для распределения нагрузки между серверами. В этом несложно убедиться, выполнив еще раз команду nslookup, без аргументов она сообщит нам А-записи, которые соответствуют адресам серверов.

nslookup mx.yandex.net

smtp-telnet-test-003.png

Поэтому, если вы испытываете проблемы доставки с одной из таких почтовых систем, то следует проверить все доступные сервера, подключившись к ним уже не по имени, а по IP-адресу, так как проблемы могут быть только с одним из них.

После того как мы подключились к серверу нужно отправить приветствие, которое будет содержать полное доменное имя клиента (либо адрес, если клиент не имеет доменного имени):

EHLO interface31.ru

На приветствие сервер отвечает кодом 250 OK и сообщает поддерживаемые SMTP-расширения, это означает что сервер готов к получению почты.

smtp-telnet-test-004.png

Для начала почтовой сессии введите команду:

MAIL FROM:

Она означает, что мы хотим передать сообщение от отправителя example@interface31.ru, на что сервер должен ответить нам кодом 250 2.1.0 ok.

Теперь укажем получателя:

RCPT TO:

Также мы можем попросить сервер отправить нам отчет о доставке или невозможности это сделать, для этого добавим в команду необязательные параметры:

RCPT TO: NOTIFY=success,failure

Если все хорошо, то сервер должен ответить нам с кодом 250 2.1.5 recipient ok, после чего мы можем перейти к передаче письма.

smtp-telnet-test-005.png

Для этого введем команду:

DATA

В ответ мы получим сообщение с кодом 354, которое разрешит нам ввод письма, которое следует закончить точкой с новой строки.

В первую очередь следует указать тему:

Subject: TEST

Затем вводим пустую строку, по правилам тему письма следует отделять от тела пустой строкой, и далее пишем текст сообщения. Количество символов и строк не ограничено, главное — не превысить допустимый размер письма. Закончив, ставим точку в новой строке и нажимаем Enter.

 TEST TEST TEST
.

После чего сервер выполнит попытку отправки нашего письма и сообщит нам результат.

smtp-telnet-test-006.png

В нашем случае письмо принято к доставке, о чем говорит код 250 2.0.0 Ok, также сервер сообщает нам присвоенный письму идентификатор. Его можно использовать при дальнейшем поиске сообщения в недрах самой почтовой системы. Обратите внимание, что этот код не говорит о том, что письмо успешно доставлено получателю, в дальнейшем оно может попасть под фильтры и оказаться в спаме, но это уже находится за рамками работы протокола SMTP, свою работу в данном случае он выполнил.

С какими ошибками доставки мы можем столкнуться? Одна из самых распространенных — неверный получатель. Попробуем указать в качестве получателя несуществующий ящик test@mail.ru, здесь мы также указали необслуживаемый данным сервером домен, что позволят дополнительно проверить сервер на открытый релей. В подавляющем большинстве случаев нормально работающий сервер не должен пересылать не предназначенную ему почту из публичных сетей.

В данном случае все закончилось быстро, сервер сообщил нам с кодом 550 5.7.1 No such user! , что такого пользователя не существует, а когда мы попытались упорствовать, сообщил с кодом 503 5.5.4 Bad sequence of commands о неверной последовательности команд.

smtp-telnet-test-007.png

Еще одна часто встречающаяся ситуация — это технология серых списков. Ее суть заключается в том, что если отправитель первый раз присылает почту и в его отношении есть некоторые сомнения, то данные о нем вносятся в серый список, а ему выдается сообщение о временной недоступности сервера. Смысл такого поведения заключается в том, что нормальный сервер повторит отправку, в то время как спамерские скрипты этого обычно не делают. Кроме того, согласно требованиям протокола SMTP, повторную отправку следует производить не ранее, чем через полчаса.

Для проверки мы отправили сообщение с подделанным отправителем и сразу же получили ошибку 451 4.7.1 Sorry, the service is currently unavailable. Please come back later.

smtp-telnet-test-008.png

Чтобы убедиться, что вы действительно имеете дело с серыми списками, а не временными неполадками на сервере, повторите отправку спустя полчаса, она должна увенчаться успехом.

Для окончания сессии с сервером введите команду

QUIT 

Как видим, работа с почтовым сервером по протоколу SMTP через Telnet не сложна, но в тоже время предоставляет широкие возможности по диагностике сервера и позволяет быстро найти и выявить причины возможных проблем с доставкой почты.

Онлайн-курс по устройству компьютерных сетей
На углубленном курсе «Архитектура современных компьютерных сетей» вы с нуля научитесь работать с Wireshark и «под микроскопом» изучите работу сетевых протоколов. На протяжении курса надо будет выполнить более пятидесяти лабораторных работ в Wireshark.

Дополнительные материалы:

  1. Почтовый сервер для начинающих. Структура и принцип работы
  2. Почтовый сервер для начинающих. Настраиваем DNS зону
  3. Почтовый сервер для начинающих. PTR и SPF записи как средство борьбы со спамом
  4. Онлайн инструменты для проверки почтового сервера
  5. Проверка связи по протоколу SMTP с помощью Telnet

Помогла статья? Поддержи автора и новые статьи будут выходить чаще:

Поддержи проект!

Подпишись на наш Telegram-канал

Или подпишись на наш Телеграм-канал:

Тестирование связи по протоколу SMTP с помощью Telnet

В этом разделе объясняется, как использовать Telnet для проверки связи по протоколу SMTP (Simple Mail Transfer Protocol) между серверами обмена сообщениями. По умолчанию протокол SMTP осуществляет прослушивает на порту 25. При использовании Telnet на порту 25 можно ввести команды SMTP, используемые для подключения к SMTP-серверу и отправить сообщение так, как будто сеанс Telnet является SMTP-сервером обмена сообщениями. При этом можно видеть успешный или неудачный результат каждого действия в процессе подключения и отправки сообщения.

Ниже представлены сценарии, в которых Telnet используется для проверки связи по протоколу SMTP с имеющимися в организации Microsoft Exchange транспортными серверами.

  • Подключение к вашему серверу Exchange с выходом в Интернет с узла, расположенного за пределами сети периметра, и отправка тестового сообщения.
  • Подключение к удаленному серверу обмена сообщениями с вашего сервера Exchange с выходом в Интернет и отправка тестового сообщения.

Процедура, приведенная в данном разделе, показывает, как использовать клиент Telnet, являющийся компонентом Microsoft Windows. Для клиентов Telnet сторонних разработчиков может требоваться синтаксис, отличный от синтаксиса компонента Telnet Windows.

Что нужно знать перед началом работы

  • Предполагаемое время для завершения: 30 минут.
  • Разрешения Exchange не применяются к процедурам, описанным в этом разделе. Эти процедуры выполняются в операционной системе сервера Exchange или клиентского компьютера.
  • Процедуры, описанные в этом разделе, лучше всего использовать для подключения к серверам с доступом в Интернет, которые поддерживают анонимные подключения. Обмен сообщениями между внутренними серверами Exchange шифруется и проходит проверку подлинности. Чтобы использовать Telnet для подключения к службе транспортного сервера-концентратора на сервере почтовых ящиков, нужно создать соединитель получения, настроенный на поддержку анонимного доступа или обычную проверку подлинности для получения сообщений. Если соединитель поддерживает обычную проверку подлинности, необходима служебная программа для преобразования текстовых строк, используемых для имени пользователя и пароля, в формат Base64. Так как имя пользователя и пароль легко распознаются при использовании обычной проверки подлинности, мы не рекомендуем обычную проверку подлинности без шифрования.
  • Если вы подключаетесь к удаленному серверу обмена сообщениями, рекомендуется выполнить описанные в этом разделе процедуры на сервере Exchange с выходом в Интернет. Это позволит избежать отклонения тестового сообщения удаленными серверами обмена сообщениями, настроенными на проверку IP-адреса источника, соответствующего DNS-имени домена и IP-адреса обратного просмотра любого узла в Интернете, который пытается отправить сообщение на сервер.
  • Сочетания клавиш для процедур, описанных в этой статье, приведены в статье Сочетания клавиш в Центре администрирования Exchange.

Возникли проблемы? Обратитесь за помощью к участникам форумов Exchange. Посетите форумы по адресу Exchange Server.

Действие 1. Установка клиента Telnet в Windows.

По умолчанию клиент Telnet не устанавливается в большинстве клиентских или серверных версий операционных систем Microsoft Windows. Сведения об установке см. в статье Установка клиента Telnet.

Действие 2. Поиск полного доменного имени или IP-адреса в записи MX удаленного сервера SMTP с помощью средства командной строки Nslookup.

Для подключения к конечному серверу SMTP с помощью протокола Telnet на порте 25 необходимо использовать полное доменное имя или IP-адрес сервера SMTP. Если полное доменное имя или IP-адрес неизвестны, самым простым способом получения этих сведений является использование средства командной строки Nslookup для поиска записи MX конечного домена.

  1. В командной строке введите nslookup и нажмите клавишу ВВОД. Эта команда открывает сеанс Nslookup.
  2. Введите set type=mx и нажмите клавишу ВВОД.
  3. Введите set timeout=20 и нажмите клавишу ВВОД. По умолчанию DNS-серверы Windows отводят 15-секундный интервал для выполнения рекурсивного DNS-запроса.
  4. Введите имя домена, для которого требуется найти запись MX. Например, чтобы найти запись MX для домена fabrikam.com, введите fabrikam.com., а затем нажмите клавишу ВВОД.

Примечание. Конечный период ( . ) указывает полное доменное имя. Использование завершающей точки препятствует непреднамеренному добавлению к имени домена каких-либо DNS-суффиксов по умолчанию, настроенных для сети.

Выходные данные команды выглядят следующим образом:

fabrikam.com mx preference=10, mail exchanger = mail1.fabrikam.com fabrikam.com mx preference=20, mail exchanger = mail2.fabrikam.com mail1.fabrikam.com internet address = 192.168.1.10 mail2 fabrikam.com internet address = 192.168.1.20 

Ограничения брандмауэра и прокси-сервера Интернета, установленные для внутренней сети организации, могут препятствовать использованию средства Nslookup для опроса публичных DNS-серверов в Интернете.

Действие 3. Использование протокола Telnet на порте 25 для проверки связи по протоколу SMTP.

В этом примере используются следующие значения.

  • Smtp-сервер назначения: mail1.fabrikam.com
  • Исходный домен: contoso.com
  • Адрес электронной почты отправителя: chris@contoso.com
  • Адрес электронной почты получателя: kate@fabrikam.com
  • Тема сообщения: Тестирование из Contoso
  • Текст сообщения: это тестовое сообщение
  • Команды клиента Telnet вводятся без учета регистра. Команды SMTP набраны заглавными буквами для большей ясности.
  • Ключ backspace нельзя использовать после подключения к целевому SMTP-серверу в сеансе Telnet. Если при вводе команды SMTP допущена ошибка, следует нажать клавишу ВВОД и повторно ввести команду. Неизвестные команды SMTP или синтаксические ошибки приведут к появлению сообщения об ошибке следующего вида:
500 5.3.3 Unrecognized command 
  1. В командной строке введите telnet и нажмите клавишу ВВОД. Эта команда открывает сеанс Telnet.
  2. Введите set localecho и нажмите клавишу ВВОД. Эта необязательная команда позволяет видеть вводимые знаки. Этот параметр может быть необходим для некоторых SMTP-серверов.
  3. Введите параметр logfile. Это необязательная команда включает ведение журнала сеанса Telnet в указанный файл журнала. Если указать только имя файла, местоположением файла журнала будет текущий рабочий каталог. При указании пути и имени файла путь должен быть локальным для компьютера. Путь и имя файла необходимо вводить в формате Microsoft DOS 8.3. Указанный путь должен уже существовать. Если указать файл журнала, который не существует, он будет создан.
  4. Введите open mail1.fabrikam.com 25 и нажмите клавишу ВВОД.
  5. Введите EHLO contoso.com и нажмите клавишу ВВОД.
  6. Введите MAIL FROM:chris@contoso.com и нажмите клавишу ВВОД.
  7. Введите RCPT TO:kate@fabrikam.com NOTIFY=success,failure и нажмите клавишу ВВОД. Необязательная команда NOTIFY определяет конкретные уведомления о доставке, которые SMTP-сервер назначения должен предоставить отправителю. Уведомления о доставке определены в стандарте RFC 1891. В данном случае запрашивается уведомление об успешной доставке или невозможности доставки сообщения.
  8. Введите DATA и нажмите клавишу ВВОД. Появится отклик, подобный приведенному ниже:
354 Start mail input; end with .
250 2.6.0 Queued mail for delivery 
221 2.0.0 Service closing transmission channel 

Действие 4. Оценка результатов сеанса Telnet.

В этом разделе приведены подробные сведения о возможных откликах на команды, введенные в предыдущем примере.

  • Open mail1.fabrikam.com 25
  • EHLO contoso.com
  • MAIL FROM:chris@contoso.com
  • RCPT TO:kate@fabrikam.com NOTIFY=success,failure

Примечание. Трехзначные коды отклика SMTP, определенные в RFC 2821, одинаковы для всех SMTP-серверов обмена сообщениями. Текстовые описания могут слегка отличаться для некоторых SMTP-серверов обмена сообщениями.

Open mail1.fabrikam.com 25

Успешный ответ: 220 mail1.fabrikam.com Microsoft ESMTP MAIL Service ready at

Ответ на сбой: Connecting to mail1.fabrikam.com. Could not open connection to the host, on port 25: Connect failed

Возможные причины сбоя:

  • SMTP-служба назначения недоступна.
  • На брандмауэре назначения установлены ограничения.
  • На брандмауэре источника установлены ограничения.
  • Указано неверное полное доменное имя или IP-адрес для SMTP-сервера назначения.
  • Указан неверный номер порта.

EHLO contoso.com

Успешный ответ: 250 mail1.fabrikam.com Hello []

Ответ на сбой: 501 5.5.4 Invalid domain name

Возможные причины сбоя: в доменном имени есть недопустимые символы. Кроме того, на SMTP-сервере назначения установлены ограничения на подключение.

EHLO — это команда протокола ESMTP (Extended Simple Message Transfer Protocol), определенная в RFC 2821. ESMTP-серверы могут объявлять о своих возможностях в процессе начального подключения. Эти возможности включают максимально допустимый размер сообщения и поддерживаемые методы проверки подлинности. HELO — это более старая команда SMTP, определенная в RFC 821. Большинство SMTP-серверов обмена сообщениями поддерживают ESMTP и EHLO.

MAIL FROM:chris@contoso.com

Успешный ответ: 250 2.1.0 Sender OK

Ответ на сбой: 550 5.1.7 Invalid address

Возможные причины сбоя. В адресе электронной почты отправителя возникла синтаксическая ошибка.

Ответ на сбой: 530 5.7.1 Client was not authenticated

Возможные причины сбоя: целевой сервер не принимает отправки анонимных сообщений. Эта ошибка возникает при попытке использовать Telnet для отправки сообщения напрямую на транспортный сервер-концентратор.

RCPT TO:kate@fabrikam.com NOTIFY=success,failure

Успешный ответ: 250 2.1.5 Recipient OK

Ответ на сбой: 550 5.1.1 User unknown

Возможные причины сбоя: указанный получатель не существует в организации.

Use Telnet to test SMTP communication on Exchange servers

You can use Telnet to test Simple Mail Transfer Protocol (SMTP) communication between messaging servers. SMTP is the protocol that’s used to send email messages from one messaging server to another. Using Telnet can be helpful if you’re having trouble sending or receiving messages because you can manually send SMTP commands to a messaging server. In return, the server will reply with responses that would be returned in a typical connection. These results can sometimes help you to figure out why you can’t send or receive messages.

You can use Telnet to test SMTP communication to:

  • Test mail flow from the Internet into your Exchange organization.
  • Test mail flow from your Exchange to another messaging server on the Internet.

Did you know that, instead of using Telnet to test SMTP connectivity, you can use the Microsoft Remote Connectivity Analyzer at https://testconnectivity.microsoft.com/? With the Remote Connectivity Analyzer, you can choose the connectivity test you want to do, in this case Inbound SMTP Email, and follow the instructions shown. It’ll step you through the information you need to enter, run the test for you, and then give you the results. Give it a try!

What do you need to know before you begin?

  • Estimated time to complete: 15 minutes
  • Exchange permissions don’t apply to the procedures in this topic. These procedures are performed in the operating system of the Exchange server or a client computer.
  • This topic shows you how to use Telnet Client, which is included with Windows. Third-party Telnet clients might require syntax that’s different from what’s shown in this topic.
  • The steps in this topic show you how to connect to an Internet-facing server that allows anonymous connections using TCP port 25. If you’re trying to connect to this server from the Internet, you need to ensure your Exchange server is reachable from the Internet on TCP port 25. Similarly, if you’re trying to reach a server on the Internet from your Exchange server, you need to ensure your Exchange server can open a connection to the Internet on TCP port 25.
  • You might notice some Receive connectors that use TCP port 2525. These are internal Receive connectors and aren’t used to accept anonymous SMTP connections.
  • If you’re testing a connection on a remote messaging server, you should run the steps in this topic on your Exchange server. Remote messaging servers are often set up to make sure the IP address where the SMTP connection is coming from matches the domain in the sender’s email address.
  • For information about keyboard shortcuts that may apply to the procedures in this topic, see Keyboard shortcuts in the Exchange admin center.

Having problems? Ask for help in the Exchange forums. Visit the forums at: Exchange Server, Exchange Online, or Exchange Online Protection.

Step 1: Install the Telnet Client on your computer

On most versions of Windows, you’ll need to install the Telnet client before you can use it. To install it, see Install Telnet Client.

Step 2: Find the FQDN or IP address of the destination SMTP server

To connect to an SMTP server by using Telnet on port 25, you need to use the fully qualified domain name (FQDN) (for example, mail.contoso.com) or the IP address of the SMTP server. If you don’t know the FQDN or IP address, you can use the Nslookup command-line tool to find the MX record for the destination domain.

Network policies might prevent you from using the Nslookup tool to query public DNS servers on the Internet. As an alternative, you can use one of the freely-available DNS lookup or MX record lookup web sites on the Internet.

  1. At a command prompt, type nslookup , and then press Enter. This command opens the Nslookup session.
  2. Type set type=mx , and then press Enter.
  3. Type the name of the domain for which you want to find the MX record. For example, to find the MX record for the fabrikam.com domain, type fabrikam.com. , and then press Enter.

Note When you use a trailing period ( . ), you prevent any default DNS suffixes from being unintentionally added to the domain name.

The output of the command looks like this:

fabrikam.com mx preference=10, mail exchanger = mail1.fabrikam.com fabrikam.com mx preference=20, mail exchanger = mail2.fabrikam.com mail1.fabrikam.com internet address = 192.168.1.10 mail2 fabrikam.com internet address = 192.168.1.20 

Step 3: Use Telnet on Port 25 to test SMTP communication

In this example, we’re going to use the following values. When you run the commands on your server, replace these values with ones for your organization’s SMTP server, domain, etc.

  • Destination SMTP server: mail1.fabrikam.com
  • Source domain: contoso.com
  • Sender’s e-mail address: chris@contoso.com
  • Recipient’s e-mail address: kate@fabrikam.com
  • Message subject: Test from Contoso
  • Message body: This is a test message

The commands in the Telnet Client aren’t case-sensitive. The SMTP command verbs in this example are capitalized for clarity. You can’t use the backspace key in the Telnet session after you connect to the destination SMTP server. If you make a mistake as you type an SMTP command, you need to press Enter, and then type the command again. Unrecognized SMTP commands or syntax errors result in an error message that looks like this: 500 5.3.3 Unrecognized command .

  1. Open a Command Prompt window, type telnet , and then press Enter. This command opens the Telnet session.
  2. Type set localecho , and then press Enter. This optional command lets you view the characters as you type them, and it might be required for some SMTP servers.
  3. Type set logfile , and then press Enter. This optional command enables logging and specifies the log file for the Telnet session. If you only specify a file name, the log file is located in the current folder. If you specify a path and file name, the path needs to be on the local computer, and you might need to enter the path and file name in the Windows DOS 8.3 format (short name with no spaces). The path needs to exist, but the log file is created automatically.
  4. Type OPEN mail1.fabrikam.com 25 , and then press Enter.
  5. Type EHLO contoso.com , and then press Enter.
  6. Type MAIL FROM: , and then press Enter.
  7. Type RCPT TO: NOTIFY=success,failure , and then press Enter. The optional NOTIFY command specifies the particular delivery status notification (DSN) messages (also known as bounce messages, nondelivery reports, or NDRs) that the SMTP is required to provide. In this example, you’re requesting a DSN message for successful or failed message delivery.
  8. Type DATA , and then press Enter.
  9. Type Subject: Test from Contoso , and then press Enter.
  10. Press Enter again. A blank line is needed between the Subject: field and the message body.
  11. Type This is a test message , and then press Enter.
  12. Type a period ( . ), and then press Enter.
  13. To disconnect from the SMTP server, type QUIT , and then press Enter.
  14. To close the Telnet session, type quit , and then press Enter.

Here’s what a successful session using the steps above looks like:

C:\Windows\System32> telnet Microsoft Telnet> set localecho Microsoft Telnet> set logfile c:\TelnetTest.txt Microsoft Telnet> OPEN mail1.fabrikam.com 25 220 mail1.fabrikam.com Microsoft ESMTP MAIL Service ready at Fri, 5 Aug 2016 16:24:41 -0700 EHLO contoso.com 250-mail1.fabrikam.com Hello [172.16.0.5] 250-SIZE 37748736 250-PIPELINING 250-DSN 250-ENHANCEDSTATUSCODES 250-STARTTLS 250-X-ANONYMOUSTLS 250-AUTH NTLM 250-X-EXPS GSSAPI NTLM 250-8BITMIME 250-BINARYMIME 250-CHUNKING 250 XRDST MAIL FROM: 250 2.1.0 Sender OK RCPT TO: NOTIFY=success,failure 250 2.1.5 Recipient OK DATA 354 Start mail input; end with . Subject: test This is a test message. . 250 2.6.0 [InternalId=5111011082268, Hostname=mail1.fabrikam.com] Queued mail for delivery QUIT 221 2.0.0 Service closing transmission channel 

Step 4: Success and error messages in the Telnet Session

This section provides information about the success and failure responses to the commands that were used in the previous example.

The three-digit SMTP response codes that are defined in RFC 5321 are the same for all SMTP messaging servers, but the text descriptions in the responses might be slightly different.

SMTP reply codes

SMTP servers respond to commands with a variety of numerical reply codes in the format of x.y.z where:

  • X indicates whether the command was good, bad, or incomplete.
  • Y indicates the kind of response that was sent.
  • Z provides additional information about the command

When a response is received by the server that opened the connection, it can tell whether the remote server accepted the command and is ready for the next one, or if an error occurred.

The first digit (X) is particularly important to understand because it indicates the success or failure of the command that was sent. Here are its possible values, and their meanings.

Reply code Meaning
2.y.z The command that was sent was successfully completed on the remote server. The remote server is ready for the next command.
3.y.z The command was accepted but the remote server needs more information before the operation can be completed. The sending server needs to send a new command with the needed information.
4.y.z The command wasn’t accepted by the remote server for a reason that might be temporary. The sending server should try to connect again later to see if the remote server can successfully accept the command. The sending server will continue to retry the connection until either a successful connection is completed (indicated by a 2.y.z code) or fails permanently (indicated by a 5.y.z code).
An example of a temporary error is low storage space on the remote server. Once more space is made available, the remote server should be able to successfully accept the command.
5.y.z The command wasn’t accepted by the remote server for a reason that’s not recoverable. The sending server won’t retry the connection and will send a non-delivery report back to the user who sent the message.
An example of an unrecoverable error is a message that’s sent to an email address that doesn’t exist.

The table above is based on information provided by RFC 5321 (Simple Mail Transfer Protocol), section 4.2.1. Additional information, including descriptions of the second (Y) and third (Z) digits of SMTP reply codes is included in this section, and in sections 4.2.2 and 4.2.3.

OPEN command

Successful response: 220 mail1.fabrikam.com Microsoft ESMTP MAIL Service ready at

Failure response: Connecting to mail1.fabrikam.com. Could not open connection to the host, on port 25: Connect failed

Possible reasons for failure:

  • The destination SMTP service is unavailable.
  • Restrictions on the destination firewall.
  • Restrictions on the source firewall.
  • Incorrect FQDN or IP address for the destination SMTP server.
  • Incorrect port number.

EHLO command

Successful response: 250 mail1.fabrikam.com Hello []

Failure response: 501 5.5.4 Invalid domain name

Possible reasons for failure:

  • Invalid characters in the domain name.
  • Connection restrictions on the destination SMTP server.

EHLO is the Extended Simple Message Transfer Protocol (ESMTP) verb that’s defined in RFC 5321. ESMTP servers can advertise their capabilities during the initial connection. These capabilities include the maximum accepted message size and supported authentication methods. HELO is the older SMTP verb that is defined in RFC 821. Most SMTP messaging servers support ESMTP and EHLO. If the non-Exchange server that you’re trying to connect to doesn’t support EHLO, you can use HELO instead.

MAIL FROM command

Successful response: 250 2.1.0 Sender OK

Failure response: 550 5.1.7 Invalid address

Possible reasons for failure: A syntax error in the sender’s e-mail address.

Failure response: 530 5.7.1 Client was not authenticated

Possible reasons for failure: The destination server doesn’t accept anonymous message submissions. You receive this error if you try to use Telnet to submit a message directly to a Mailbox server that doesn’t have a Receive connector that’s configured to accept anonymous connections.

RCPT TO command

Successful response: 250 2.1.5 Recipient OK

Failure response: 550 5.1.1 User unknown

Possible reasons for failure: The specified recipient doesn’t exist.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *