Finding an email server

Consider the email address bob@example.com. In this case, bob identifies the user, while example.com identifies the domain name of the service provider. These parts are delineated by the @ symbol.

One domain name can potentially use multiple mail servers. Likewise, one mail server can provide service for many domain names. For this reason, identifying the mail server or servers responsible for receiving mail for bob@example.com isn't as easy as connecting to example.com. Instead, the mail server must be identified by performing a DNS lookup for an MX record.

DNS was covered in depth back in Chapter 5Hostname Resolution and DNS. The program we developed in that chapter can be used to query MX records.

Otherwise, most operating systems provide a command-line tool for DNS lookup. Windows provides nslookup, while Linux and macOS provide dig.

On Windows, we can find the mail servers responsible for accepting mail @gmail.com using the following command:

nslookup -type=mx gmail.com

This lookup is shown in the following screenshot:

On Linux or macOS, an MX record lookup for a @gmail.com account is done with the following command:

dig mx gmail.com

The use of dig is shown in the following screenshot:

As you can see in the preceding two screenshots, Gmail uses five mail servers. When multiple MX records are found, mail should be delivered to the server having the lowest MX preference first. If mail delivery fails to that server, then an attempt should be made to deliver to the server having the next lowest preference, and so on. At the time of this writing, Gmail's primary mail server, having a preference of 5, is gmail-smtp-in.l.google.com. That is the SMTP server you would connect to in order to send mail to an @gmail.com address.

It is also possible for MX records to have the same preference. Yahoo! uses mail servers having the same preference. The following screenshot shows the MX records for yahoo.com:

In the preceding screenshot, we see that Yahoo! uses three mail servers. Each server has a preference of 1. This means that mail can be delivered to any one of them with no special preference. If mail delivery fails to the first chosen server, then another server should be chosen at random to retry.

Programmatically getting the MX record in a cross-platform manner can be difficult. Please see Chapter 5, Hostname Resolution and DNS, where this topic was covered in some depth. The SMTP client we develop in this present chapter assumes that the mail server is known in advance.

Now that we know which server to connect to, let's consider the SMTP protocol itself in more detail.