Despite the many ways we have to communicate over the network, email is still king. No wonder: it is the closest electronic counterpart of the traditional letter, which remains the most fitting written form for passing formal and informal content over a distance (love letters less so these days). The digital version is far more convenient, lets us process more and faster, and I won't even mention storage costs. That is not always an advantage (spam, spam, spam...), but there is a reason email is still used for things like:

  • sending activation links when you sign up for a service,
  • notifying you about reports that take a long time to generate,
  • newsletters,
  • confirming purchases and payments,
  • official communication with a university, a workplace and so on,
  • shopping offers,
  • requests from your bank to update your ID card number, because they know when it expires.

And whether or not our application supports other kinds of notifications, such as those shown directly in the software, push, desktop pop-ups, SMS and so on, there is a 99% chance that somewhere it will need to send a good old email. That means you have to know how to handle it from within the program. For many developers this is not a problem, especially since frameworks (or rather libraries) make it much easier. But sometimes they don't, and sometimes we simply lack knowledge about what really happens when an electronic message is sent. Today we'll talk about that a little. The knowledge in this article may be a bit too detailed for standard use, because both mail clients and libraries really do all of this in the background, but it is better to have too much information than too little.

A side note: as you may have noticed, I write "mail" and not "e-mail" or the Polish "mejl". I used to be a fan of the first form, and some time ago I decided that the "e-" prefix is no longer needed, since everybody knows what we mean and there is no reason to make the word longer. By the way, I am still in favor of spelling it "e-mail" with a hyphen and will probably stick with that (just like with e-book or e-sports, and greetings to Zbyszek, who is surely fuming right now seeing that I don't write "esport"). "Mejl" looks odd, but it is an attempt to adapt the English term to Polish, and according to linguists we should look on it more kindly. I do, but I have to admit I haven't been convinced to use it.

How does sending an email work?

Probably everyone reading this knows how to send an email. You open your favorite mail client (Thunderbird, Outlook, Apple Mail and so on), choose to write a message, type the body and the subject, pick the sender and click "send". That's it, see you later, time for a round of CS. For most people this is enough, but not for developers, who sometimes have to send an email not through a graphical interface but through an API, a library or generally programmatically. And although in most cases these tools take care of everything for us, it is worth knowing how it works inside, also because many terms come up along the way, for example when configuring access.

First of all, all of this has to be handled by a standardized internet protocol, that is, a set of rules (I would write "algorithm", but ChatGPT chased me with a rolling pin when it fact-checked this text...) responsible for a specific operation on the Internet. An example of such a protocol is HTTP, which serves web pages on the World Wide Web. For receiving mail it is IMAP, or the slowly retired POP3. But we are more interested in the protocol used to send messages, which is SMTP (Simple Mail Transfer Protocol), around since the 1980s. If, while configuring email, you have to enter the hosts of the incoming and outgoing mail servers, the second one is SMTP. The mail client has to know where to send the message, to which port and how, so that the server can then route it onward. Just like typing an address in a browser takes us to a server with a specific IP address.

At a slightly higher level of detail, it looks like this:

  1. The user enters all the details of the email in the mail client.
  2. The client starts a connection to the SMTP server, which is responsible for accepting the message from this user or application and sending it onward. For example, if you have a Google mailbox (domain gmail.com), the connection goes to the server smtp.gmail.com. It happens on a specific port. It used to be 25, today it is more often 465 or 587. The choice depends on how the connection is secured:
    • 465 uses an encrypted TLS connection from the very start, so-called Implicit TLS. It is often called SSL,
    • 587 starts a normal SMTP session and encrypts it with TLS after the STARTTLS command is issued along the way,
    • and 25 is the "it will be fine, why worry" option: no authentication, which is why it should not be used. Today it only serves for mail servers (specifically MTA agents) talking to each other. Admittedly they can also use STARTTLS for encryption, but there is a reason port 25 is discouraged for users sending mail.
  3. The SMTP server answers with code 220 and waits for further instructions. An SMTP session begins, during which various messages are exchanged.
  4. The client sends HELO (or EHLO, if we are about to encrypt and authenticate; the "E" stands for "Extended"), introducing itself to the server. The server confirms with code 250.
  5. If the client wants to secure the communication, it sends the STARTTLS command. At this point the client and the server negotiate encryption, much like when connecting to a website over HTTPS. Interestingly, after STARTTLS the EHLO messages are exchanged again.
  6. Now we log in to the sender's account. The client sends the AUTH command (for example AUTH LOGIN) together with the username and password. If they match, the server returns code 235. Besides AUTH LOGIN there is also AUTH PLAIN (the password sent in clear form), but also XOUATH2, which we will come back to.
  7. The client sends the MAIL FROM message, which names the sender, and gets code 250 in reply. Why do we need it if we have already logged in? Because we can hide the real sender and give, for example, a "noreply" address for emails we don't want answers to. The recipient, in turn, sees what will later appear in the "From" header.
  8. The client names the recipient with the RCPT TO command and gets code 250 from the server. When there are many recipients, RCPT TO is repeated for each of them, whether it is a visible recipient, a carbon copy (CC) or a blind carbon copy (BCC). In the last case the recipient is hidden by not including them in the headers that reach the other addressees.
  9. The client starts sending data with the DATA message. The server answers with code 354 and keeps waiting. Then the client sends various headers, including "Date", "From", "To" and "Subject", the body and attachments encoded with Base64. After the data it all ends like in life: with a full stop (on a separate line, though). The server then answers 250 and starts passing the email on to the destination SMTP server.
  10. The client ends the session with the QUIT message and disconnects from the SMTP server after receiving code 221.
  11. Meanwhile the SMTP server keeps forwarding the email, if it has not done so yet. That is why it may seem that the client has already sent the message, and only after a while we get word that the email could not be delivered, because the recipient cannot be found or for some reason does not accept the email (for example because of an oversized attachment).

That is how it looks under the hood. I left out many details here, because they are not important for our purposes. I also simplified the naming. For example, a mail client is technically called an MUA, and on the SMTP side there are the MSA, MTA and MDA in turn. You can find more details, for example, in this article.

Even though there are many steps, what matters most to a developer in the end is that:

  • there is an SMTP server you have to connect to (but not necessarily directly, more on that later),
  • you usually have to authenticate (that is, log in normally) to send an email,
  • different encryption methods correspond to different ports.

What authentication and connection methods do we have?

Let's go back to the authentication step, because, as you can guess, it is extremely important. Especially since the simple path described above is already being phased out by big providers such as Google or Microsoft.

Namely, sending the login and password through so-called Basic Authentication is now strongly discouraged for security reasons. This does not mean it will be unavailable altogether, since smaller mail providers will keep supporting it for a long time (I'm writing this in August 2026). Still, it is good to know, because it has a big impact on developers. We have to be aware that these are two different things:

  • SMTP is the protocol, the way of communicating with a mail server that listens on a certain port. Or with a server that leads to a mail server.
  • The authentication method is the way of showing "this is my account and I am sending the email". Put bluntly, the way of logging in to the server.

How many combinations are there? Quite a lot.

  1. SMTP + Basic Authentication is the classic I described in the previous section. The login and password are passed along with the AUTH command. This is exactly what is being phased out at big providers, although it is still common on the web, and for decades this is how emails were sent, including from web applications.
  2. SMTP + OAuth2 (XOAUTH2) looks the same as before (the credentials are sent to the SMTP server), but instead of a password a token is used, obtained earlier through an OAuth2 endpoint with a separate login. Of course, the mail provider has to allow getting such a token. But if it does, this method is the preferred one when, as developers, we handle sending from a mail server such as Microsoft's.
  3. Microsoft Graph API/Gmail API/another API + OAuth2 (XOAUTH2): earlier I suggested that you can connect to an SMTP server indirectly. A provider may offer an API where we first get a token through OAuth2 and then send a request to send an email through a given API endpoint. Only then does the API talk to the SMTP server internally. In Microsoft's case the Graph API handles not only email but also other services such as OneDrive or SharePoint, and the interface, acting as a "middleman" to SMTP, can generally allow much more, including receiving messages, queueing and so on.
  4. Sending directly to port 25 through the MX endpoint is something from a completely different barrel, the so-called hardcore path. We don't log in and we don't connect to an SMTP server. We replay the whole delivery directly with the commands described earlier, as if we were an SMTP server. Very inconvenient, low-level and, frankly, often unnecessary, unless we want to build our own MTA (Mail Transfer Agent). And MX is one of the records read from a DNS server.

There are other methods too, which depend more on the mail provider, but in 99.9% of cases we will deal with the first three (I described the fourth as a curiosity for your own research). A good library for sending mail, for example from a PHP application, will let us simply provide all the email data and do the rest for us, and it will often help get an OAuth2 token if one is needed. If not, you can get it with other libraries or by handling the HTTP requests that serve this purpose yourself.

Does this mean you can switch SMTP off on a mail server? No, it is still used to send emails. But there may be a situation where it is recommended to restrict direct logins to it for certain accounts. So it is worth checking whether our application that sends messages uses a mail account created specifically for that.

What if there are many emails to send?

A fair question. We all know systems that have to send thousands of emails at once, for example as a newsletter, a notice about changed terms or a promotion. If we are talking about a dozen or even several dozen emails, it is fairly simple: you just send them one after another, since that volume should not cause any harm to the SMTP server. But what about hundreds, thousands or even millions of electronic messages?

The simplest way is one email with many recipients, of course as blind copies (remember this, because the industry knows too many cases where all recipients cheerfully learned about each other, which drew the attention of the data protection authority). It is the natural way, often replicated when sending by hand, when we type in many addressees. But this method has two drawbacks:

  • the number of recipients depends on the mail provider and is most often 500 addresses,
  • you cannot personalize the email, and that includes links.

That brings another solution to mind: you can open one SMTP session and send many messages within it. Then we deal with separate messages (and the recipient can be given explicitly), but the server treats it as a kind of package (a batch, although in the mail world the word "bulk" is often used). This is how popular libraries for sending email from an application work, although in most cases they are used to send one email at a time anyway.

Sometimes several SMTP servers are available, most often as a "rescue" in case the main one is down. But the second feature of such a setup is balancing the sending of emails and thus achieving higher throughput. It is a sort of load balancer for email, although often you have to decide yourself which SMTP server to use.

Whatever the case, remember that you can separate creating an email from sending it. When an application has hundreds of thousands of emails to send, it usually puts them in a queue managed by the same or another application instead of passing them directly to the SMTP server. Only that application then sends them periodically (for example through a cron mechanism) in batches of a set size, say every minute. This is how external newsletter services work, and they also have extensive infrastructure with many SMTP servers, a spotless reputation that makes it harder to classify sent emails as spam (we'll come back to that) and tools for configuring messages (for example personalization). You can also write such software yourself, dedicated to your own application, and here is a curiosity: to send emails, Feedybacky uses a simple application we wrote ourselves, which does exactly this kind of queueing.

Also remember that limiting sending on the sender's side is one thing, but the recipients' SMTP servers have their own limits too. We may be able to send 1000 emails without trouble, but if they all go to one server (for example smtp.gmail.com), it may reject the excess through its defense mechanisms. It may classify us as a potentially dangerous sender spreading spam.

Protection against becoming a spammer

You can avoid this by sensibly pacing your emails, but also by taking care of:

  • SPF (Sender Policy Framework): a DNS record that lists the servers or IP addresses allowed to send mail. It is a TXT record starting with v=spf1..., listing the servers "authorized" by us. This record is checked by the recipient's SMTP server, but be careful when our email arrives after many redirects.
  • DKIM (DomainKeys Identified Mail): another DNS record of the TXT type, this time with v=DKIM1..., which publishes the server's public key. The message, in turn, is sent signed with a private key, with a header pointing to the original sending domain. Important: this does not mean the email is encrypted. It is only signed with a key so that the recipient can verify it by asking for the public key. That way they know the message came from this domain and nobody altered it along the way.
  • DMARC (Domain-based Message Authentication, Reporting and Conformance): checks the link between the authenticated domain and the one visible in the "From" header. Again we have a DNS record of the TXT type (this time v=DMARC1...), which can contain a policy such as "none" (check but do nothing), "quarantine" (treat as suspicious) or "reject". The last option is the best, because it makes it much harder to impersonate us, but let's use it only when we are sure which servers our message actually passes through.
  • using TLS: that is, encrypting messages, which signals that the sender takes security seriously.
  • providing a one-click unsubscribe mechanism: it may be verified by larger providers, which again want to make sure we are "professional". But that is not all. It is worth providing the headers "List-Unsubscribe: a link with an individual token" and "List-Unsubscribe-Post: List-Unsubscribe=One-Click", which tells Gmail a lot when it receives and displays mail.
  • keeping a good reputation for the domain and the IP address, that is, caring about the history of our "activity". If our mail "causes problems", messages from it are often rejected or there were complaints about our emails, our reputation will be poor, which means a higher chance of landing in spam. So be careful not to overdo the frequency of mailings, make sure nobody unauthorized uses our mail server and, frankly, don't clutter users' inboxes with strange content. The same applies to the server and to the domain.

When we use trusted SMTP providers (Google, Microsoft, newsletter systems), this problem is partly off our hands, but the trouble starts with our own server or simply a less popular one. Frankly, there is rarely a need to configure such records yourself, although it is not unheard of, which is why I gave only the basics without a detailed discussion. Developers are usually not involved in this kind of work. Just remember the distinction: the domain (for example mygreatwebsite.pl) is one thing, and the server that runs SMTP (for example Microsoft) is another, just like with web applications.

Specialists also recommend separating domains and servers for standard emails (for example with a password reset link) and for mass mailings (such as a newsletter). It is not a final cure, but it limits the "losses" when, because of rash moves by a combination of marketers and developers, users fail to get a truly important email from our service.

And what is EML?

Let's step out of the world of SMTP servers, security and so on for a moment and move to the level of the email message itself. Sometimes we come across files with the .eml extension. It is a commonly accepted format for storing a single email, originally developed by Microsoft and gradually becoming the standard in this area. Such files can be exported from emails in a mail program (Outlook, Thunderbird and so on), opened in such a client, saved to disk as an important email you can't lose (for example attached in a knowledge base) and, interestingly, also opened in a web browser after changing the extension to .mht (the same trick as changing the Android .apk extension to .zip).

EML is really just a plain text file with a defined structure that contains everything needed to open the email in a nice, graphical form in a mail client (including information about attachments). However, we have to admit that reading such a message "by hand" is not always a pleasure, because various parts may be encoded in a way unreadable to the human eye.

PGP encryption

We mentioned that with TLS/STARTTLS we can encrypt a message so it cannot be decoded while passing through SMTP servers. Then the communication is encrypted, but the email itself is not: someone who somehow gets into the SMTP server's files can see our scribblings. So you can try encrypting the email in such a way that even the SMTP server doesn't get it in "clear" form, and only the sender and the recipients can display it in their mail clients.

Let's get to know OpenPGP (Open Pretty Good Privacy), a protocol that uses keys on a similar principle as SSH to encrypt a message with the recipient's public key, which the recipient then decrypts with their private key. Then everyone along the way (including the SMTP servers) sees only encoded content they cannot read. Of course, this means the sender first has to obtain the recipient's public key (usually both ways), load it into their mail clients and then encrypt messages with it. The mail client, by the way, shows whether a given message was encrypted.

This is absolutely not used for normal or mass emails sent by applications. I haven't yet met a web application (though more specialized ones surely exist) that would require a public key for that purpose. It is a solution more for exceptionally discreet communication with sensitive data, people in responsible positions or those working in, say, security departments.

It is worth explaining where the distinction between PGP, GPG and OpenPGP comes from, because you can really get lost here. Especially since the actual picture defies intuition a little:

  • PGP (Pretty Good Privacy) is Phil Zimmermann's historical and (importantly) commercial program, which brought the idea of end-to-end email encryption to the masses.
  • OpenPGP: based on PGP, an (open) standard was created that describes what keys, signatures, encrypted messages and the whole process look like. But sometimes people just say "PGP", which I did in the title of this section.
  • GPG or GnuPG (GNU Privacy Guard) is a specific free program implementing the OpenPGP standard, used to generate PGP keys (more on that in a moment) and to verify them. I'm afraid that swapping the letters PGP to GPG is no accident and shows an exceptional sense of humor in the IT world.

How do you create your own PGP key pair with GPG (truly, some jokers worked on this...)? You install GnuPG and run the command gpg --full-generate-key. There are at least two encryption algorithms to choose from: the shorter ECC and the historical, "strong" RSA. Then the user has to provide information very similar to what is asked when generating SSH keys, that is, personal details, company, passphrase and so on. After going through this process you can export the public key with gpg --armor --export [nasz mail] > public-key.asc (the OpenPGP key extension is .asc), which we hand to our correspondents to import, for example, in Outlook. You can also export the private key with the --export-secret-keys switch.

It is also worth mentioning that Thunderbird itself has tools for generating keys, and GPG itself can be used to digitally sign your Git commits (even though SSH keys are used to connect to the repository itself).

Summary

Contrary to what it may seem after reading the article, sending emails from an application is not really hard. Modern libraries do a lot of things for the developer. But sometimes a piece of knowledge is missing about what happens under the hood, and it may cause trouble in specific situations. That is why the description came out a bit longer, showing among other things where encryption sits in this whole process and what kind it is. But I hope the knowledge in this article will prove useful one day.

Best regards and thank you, Jakub Rojek.