Code

What is the SMTP protocol and how does it send emails?

What is the SMTP protocol and how does it send emails?

Practical course: "The DevOps Engineer Profession"

Learn more

Despite the growing popularity of instant messengers, billions of emails continue to be sent daily around the world. The SMTP protocol, which is responsible for transferring messages between mail servers, plays a key role in this process. In this article, we'll take a detailed look at the SMTP protocol and offer practical examples of its use. This material will be useful for anyone interested in system administration and desiring a deeper understanding of email and network technologies in general. Understanding SMTP is essential for successfully setting up mail servers and managing email. A table of contents is an important element of any document, as it helps organize information and facilitates navigation. A properly structured table of contents improves the user experience and facilitates better comprehension of the material. It's important that the table of contents reflects key topics and sections of the text, allowing readers to quickly find the information they need. Optimizing content for search engines also plays a significant role in increasing page visibility. Using keywords and phrases related to the main topic can help improve search engine rankings. Effective content is not only a way to organize text, but also a way to attract the attention of the audience.

  • What is the SMTP protocol
  • How secure is it
  • How the SMTP protocol works
  • SMTP codes, errors, and ports
  • Practice: sending an email via SMTP using Mailtrap and Python

What is the SMTP protocol

SMTP, or Simple Mail Transfer Protocol, is a standardized protocol used for sending and routing emails between mail servers and clients. It governs the process of message delivery from sender to recipient, starting from the moment the user clicks the «Send» button in their email client until the actual delivery of the email to the recipient's server. SMTP ensures reliable data transfer, making it a key element in the email system and an essential tool for business and personal communications. Understanding how SMTP works allows you to effectively utilize the power of email and ensure that messages are delivered on time and without errors. SMTP, or Simple Mail Transfer Protocol, is a protocol designed exclusively for sending emails. It is important to note that it is not designed to receive messages. It is similar to the work of a postman: he delivers letters to the recipient's inbox, but the recipient is responsible for receiving and reading them. SMTP ensures the reliable and efficient transfer of letters from the sender to the server, which then relays them to the recipients' inboxes. Using this protocol is a key element in the functioning of email, ensuring fast and secure delivery of information. IMAP and POP are used to read emails. When you open services like Gmail or Yandex Mail, the email client uses one of these protocols to retrieve messages from the server. IMAP (Internet Message Access Protocol) provides access to emails stored on a server and enables synchronization across different devices. In contrast, POP (Post Office Protocol) downloads emails directly to your device, allowing you to work with them offline. In the next article, we will take a closer look at the features and benefits of each of these protocols.

Infographics: pixelbazaar / SVG Repo / Skillbox Media

How secure is it?The SMTP protocol was developed in the early 1980s as A text-based protocol for transmitting data. Initially, it did not provide encryption or data security, making it vulnerable to attack. When entering a username and password for authentication, attackers could easily intercept this data using network traffic analysis tools. As a result, the security of email transmission became a serious concern, leading to the development of additional encryption and authentication technologies to protect data in transit. As the number of email users increased, the SMTP protocol underwent many improvements. Today, the key specifications of this protocol are recorded in two main documents: RFC 5321 and RFC 5322. RFC 5321 covers the technical aspects of SMTP, including the connection establishment process, the command set, and the transfer of messages between servers. RFC 5322 standardizes the email format, including the structure of headers, the organization of content, and other message elements. These documents provide the foundation for reliable and efficient email operations, making them essential for email system developers and administrators.

In 1995, the SMTP protocol was enhanced with the introduction of ESMTP (Extended Simple Mail Transfer Protocol). This update provided full compatibility with the original SMTP while adding commands for more efficient interaction between clients and servers. ESMTP also supports the transmission of multimedia messages, including video, attachments, and images. In addition, the new ESMTP architecture paved the way for the implementation of modern security mechanisms, making it more reliable for use in various network environments.

Modern SMTP differs from earlier versions by its integration with a number of technologies that provide a high degree of security and reliability. In particular, TLS encryption is used to protect connections, effectively preventing the interception of email content. Mechanisms such as SMTP AUTH, SPF, DKIM, and DMARC have been implemented to confirm the authenticity of senders and combat spam. These technologies not only ensure security but also trust in electronic correspondence, making modern messaging systems more efficient and secure.

Reading is an important part of our lives, contributing to the development of thinking and broadening our horizons. Books, articles and various sources of information enrich our inner world and help us better understand the surrounding reality. Reading not only improves vocabulary, but also promotes the development of analytical thinking and creativity. It is important to choose a variety of materials to get the most complete understanding of the world. Pay attention to new literature and scientific research that may be interesting and useful. Remember that reading should not only be useful but also a pleasant, enjoyable process. Thus, regular reading becomes the key to personal and intellectual growth.

Information security threats are risks that can compromise the confidentiality, integrity, and availability of data. They can arise from a variety of factors, including malware, phishing, data leaks, and network attacks. To effectively combat these threats, it is necessary to implement comprehensive security measures, such as regularly updating software, using antivirus software, training employees in cybersecurity basics, and creating data backups. It is also important to conduct vulnerability analysis and penetration testing to identify weaknesses in the infrastructure. Using a multi-level security system will significantly reduce risks and protect information from potential threats.

How the SMTP Protocol Works

When a user clicks the "Send" button, their email client initiates a connection to a pre-configured SMTP server. This starts the email transmission process, which includes several key stages: establishing a connection, transferring data, determining the recipient's server, and terminating the session. Let's look at each of these stages in more detail.

Establishing a connection is the first step in which the email client and SMTP server interact to set up the communication channel. During the data transfer stage, the message is formed and sent, including its content and headers. Then, a search for the recipient's server is performed, which includes using DNS to determine the IP address. Terminating the session involves gracefully closing the connection after the message has been successfully transmitted.

These stages ensure the secure and efficient sending of emails over the Internet. Understanding how an SMTP server works and the entire data transfer process helps users better navigate email and resolve potential issues that may arise when sending messages.

Establishing an SMTP connection is an essential step in the email sending process. SMTP (Simple Mail Transfer Protocol) uses TCP (Transmission Control Protocol) to create a reliable connection between the email client and the server. A TCP connection is first established, after which the email client sends a greeting command to the server. This command initiates data exchange and allows the supported protocol extensions to be determined, which facilitates the correct operation of the email transmission system. Properly configuring an SMTP connection ensures reliable message delivery and compatibility with various email services.

Email data transfer begins with establishing a connection between the client and the server. The client sends SMTP commands to the server, containing the sender and recipient addresses, as well as the message body. This process is managed on the server by the MSA (mail submission agent), a program that accepts incoming messages, checks them for compliance with technical standards, and prepares them for further routing. This stage is critical to ensuring the correct delivery of the email and its secure processing.

The process of finding the recipient's server begins with interaction with the MTA (mail transfer agent), which plays a vital role in routing emails. The MTA checks whether the sender and recipient addresses belong to the same domain, for example, @skillbox.by. If so, the email is forwarded directly within the system, ensuring fast and efficient delivery without the need to access external resources. This approach minimizes delays and reduces the likelihood of errors when sending email.

When the domains differ, the server consults the DNS system to determine the recipient's server address, which is necessary to send the email. The sender's SMTP server then establishes a connection with the recipient's SMTP server and transmits the message according to the established data transfer algorithm. This process ensures reliable and efficient delivery of email between different domains.

Closing a connection in the SMTP protocol occurs after all data has been transferred. The client sends a command to the server to terminate the session. Upon receiving this command, the SMTP server acknowledges its execution, and as a result, the TCP connection is closed. This process ensures the correct completion of data transfer and the release of resources.

Diagram of the process of sending a letter between different mail servers of the sender and recipient Infographics: pixelbazaar / SVG Repo / Skillbox Media

Read also:

The TCP/IP Model: What It Is and How It Works

The TCP/IP model, or Transmission Control Protocol/Internet Protocol, is the fundamental architecture upon which the Internet is built. This model serves as a standard for exchanging data between devices on the network. It consists of several layers, each of which performs its own functions.

At the lowest layer is the network access layer, which is responsible for transmitting data over physical media such as Ethernet or Wi-Fi. The next layer is the Internet layer, which manages the routing of data packets between different networks. The Internet Protocol (IP) is a key component of this layer, providing addressing and delivery of data.

At the top layer of the TCP/IP model is the transport layer, where the TCP (Transmission Control Protocol) and UDP (User Datagram Protocol) protocols ensure reliable and fast data transfer. TCP guarantees packet delivery by establishing a connection between the sender and receiver, while UDP provides faster but less reliable connectionless transfer.

Finally, the application layer contains protocols such as HTTP, FTP, and SMTP, which define how applications interact with the network. The TCP/IP model provides versatility and interoperability across different devices and platforms, making it the foundation for the global Internet.

Understanding the TCP/IP model is critical for IT professionals, developers, and network administrators, as this knowledge helps optimize network solutions and improve application performance.

SMTP Codes, Errors, and Ports

To ensure efficient communication between mail servers, the SMTP protocol uses a number of service mechanisms. These include commands for exchanging information, error codes that signal problems, and special ports for establishing connections. Let's consider each of these elements in more detail.

SMTP commands play a key role in the email transmission process, allowing servers to send and receive messages. Error codes provide important information about the connection status and possible failures, making it easier to diagnose and troubleshoot problems. Special ports, such as 25, 587, and 465, ensure secure and stable connections between mail servers. Understanding these mechanisms helps manage email more effectively and improve user experience. SMTP protocol commands are the key instructions that govern the process of transferring emails between a mail client and a server. These commands can be thought of as a kind of dialogue established between the mail client and the server to efficiently send and receive messages. SMTP (Simple Mail Transfer Protocol) ensures reliable and fast mail transfer, making it an essential component in the world of electronic communication. Proper use of SMTP commands helps minimize errors and ensure successful delivery of emails. HELO / EHLO (Hello). This command begins sending an email. The mail client "introduces itself" to the server and provides its domain name or IP address. The server sends a greeting message and confirms the connection. MAIL FROM. After identification, the sender specifies the email address from which the message is sent. This command marks the beginning of a new transaction. The server confirms its readiness to accept the message with the 250 OK code.

  • RCPT TO (Recipient To). The next step is to specify the recipient of the message. If the message needs to be delivered to multiple recipients, you can send multiple RCPT TO commands. After each command, the server responds with the 250 OK code.
  • DATA. This command starts the transfer of the message contents. After it, the server responds with the 354 code and prepares to receive the data. The client transfers the message text, headers, attachments, and ends the transfer with a period on a separate line. The server responds with 250 OK.
  • QUIT. After sending the message, the client uses this command to close the connection. The server responds with the 221 code.
  • RSET (Reset). This command is used to cancel the current transaction. It does not break the connection, but simply resets the state and deletes all data about the message and recipients.
  • The diagram of interaction between a mail client and an SMTP server describes the process of sending emails over the Internet. The email client installed on the user's device initiates a connection to the SMTP server, which is responsible for processing and sending messages. During this interaction, the email client transmits data such as the sender's address, recipient's address, subject, and body of the message. The SMTP server processes this information, verifies the addresses, and, if successful, sends the message to the specified address. Importantly, this scheme is the basis for most email systems and ensures reliable message delivery. Understanding this diagram will help users better navigate the email sending process and resolve potential issues.

    Infographics: Skillbox Media

    The diagram below illustrates an ideal data transfer scenario with a reliable connection. However, in real practice, emails may encounter rejections, blocks, or various other issues. When errors occur, the receiving server generates SMTP error codes. These codes fall into two main categories: temporary and permanent. It's important to consider these codes when diagnosing and troubleshooting problems when sending and receiving email. Proper understanding and interpretation of SMTP codes can significantly improve the quality of email communications.

    The first group of errors is called Persistent Transient Failure. These codes begin with the number 4, followed by two more digits. They typically indicate temporary failures on the mail server. In most cases, resending the email can resolve the issue. However, servers often use these errors intentionally to delay or filter messages from suspicious senders. This is important to consider when working with email systems to minimize risks and optimize message delivery.

    The SMTP protocol on Yandex servers may return code 421. This occurs when the server does not respond within a specified time due to high load or other network issues. Code 421 indicates temporary server unavailability, which may be due to network overload or problems. Users receiving this code can try sending the message again later when the server load decreases.

    The second group is Permanent Error. These codes begin with the number 5 and indicate serious problems, such as a broken SMTP connection or failure to deliver the message. Unlike temporary errors, resending the message with a permanent error will most likely not produce results.

    Code 550 in the Yandex SMTP protocol indicates that the specified recipient is no longer in the system. This message may indicate a typo in the email address, the mailbox has been deleted, or the account simply does not exist. It is important to check the spelling of the address to avoid errors when sending correspondence.

    Reading is an important part of personal development and education. It helps expand horizons, improves critical thinking skills, and helps you absorb new information. Regularly reading books, articles, and other materials can significantly improve your level of knowledge and enriches your vocabulary. A diverse selection of literature, including fiction, scientific articles, and specialized publications, allows you to gain a deeper understanding of the world and develop analytical skills. Don't forget the importance of reading to improve your writing and communication skills. Read regularly to get the most out of this important activity.

    HTTP Codes: An Introduction to Network Communications

    HTTP codes are an important element of network communications, used to convey information about the status of a request between a client and a server. These three-digit codes help you understand how the server processed the request and what response to expect.

    There are many categories of HTTP codes, each representing specific statuses. For example, 200 codes indicate a successful request, while 404 codes indicate that the requested page was not found. 500 codes indicate internal server errors, which may require additional analysis to resolve.

    Proper understanding and use of HTTP codes play a key role in website optimization and performance. Developers and system administrators must closely monitor these codes to ensure a high-quality user experience and maintain the functionality of web resources.

    Knowledge and application of HTTP codes helps not only with technical aspects but also with SEO optimization. Correct codes can influence the indexing of a website by search engines, which, in turn, affects the visibility of the resource on the internet. Therefore, it is important not only to be able to interpret these codes but also to use them to improve the quality of web applications and websites.

    Each SMTP server has a unique address and port that the email client uses to connect. Different email protocols have their own ports. If you think of the Internet as a network of houses around the world, the IP address acts as an "address on a map," and the port is the specific door through which you enter the house. Understanding the addressing structure and port assignments is key to successfully setting up and operating email services. Optimizing these parameters ensures reliable and secure data transmission in email.

    The SMTP protocol originally functioned exclusively on port 25. Although this port is still available, it is often blocked on most user networks because it has long been used by spammers for mass mailings. Port 465 also existed, but it is practically no longer used today, as most users and organizations have switched to more modern encryption methods. Currently, it is recommended to use port 587, which supports TLS and provides more secure data transfer. This makes it the preferred choice for sending email, providing protection against unauthorized access and information leaks.

    Port 587 is the modern standard for sending email via the SMTP protocol. It is widely used by most email services due to its high security. Port 587 supports connection encryption using TLS (Transport Layer Security), which ensures the protection of transmitted data. Using this port minimizes the risks associated with information interception and guarantees confidentiality when sending email.

    Email services often support port 2525. Although this port is not officially standardized for SMTP, it serves as an alternative if the standard ports 25 or 587 are unavailable. This is especially important if your ISP blocks these ports, which can interfere with sending and receiving email. Using port 2525 can ensure reliable communication and improve the deliverability of email messages.

    Connection diagram to Yandex Mail servers Infographics: pixelbazaar / SVG Repo / Skillbox Media

    Practice: sending a letter via SMTP with Mailtrap and Python

    To safely test the SMTP protocol, we recommend creating a free account on the Mailtrap platform. This service is designed for testing email sending and simulates the operation of real mail servers. All sent emails do not reach the recipient's real inbox, but are stored in a special "sandbox" accessible only to you. Mailtrap allows you to effectively debug and test email sending, ensuring the security of your testing and eliminating the possibility of sending spam.

    After registering in your account, copy your Username and Password. You will need this information to connect to the test SMTP server. Make sure you save them in a safe place for future reference. A proper connection to the SMTP server will allow you to effectively test email sending.

    Screenshot: Mailtrap / Skillbox Media

    To get started, you need to install Python and choose a suitable code editor. After installation, create a new file and paste the following code into it, replacing the data with your own.

    Open the terminal in an editor and run the command to run the script.

    Once the script runs, the email will be available in your Mailtrap account. You can open it in the web interface to check the headers, content, and ensure the SMTP transmission is successful. Mailtrap provides convenient tools for analyzing emails, allowing you to ensure that your mail system is configured correctly and troubleshoot potential errors.

    Screenshot: Mailtrap / Skillbox Media

    Learn more about programming and coding in our Telegram channel. Subscribe to stay up to date with interesting content and helpful tips!

    Check out our article for more detailed information.

    • OSPF Protocol: What is it, what is it for, and how does it work?
    • What is a server, how does it work, and what types of servers are there — explained in simple terms.
    • What is the OSI model and why is it needed: dissecting the Internet's layered cake.