📘 Tutorial 6: Electronic Mail: SMTP, POP3, IMAP, and MIME

COMP347 (Revision 10) | TrustOpen University

📑 Table of Contents

🎯 Learning Objectives

Upon completion of this expanded tutorial, students will be able to:

🔭 Overview

Electronic mail is one of the oldest and most resilient Internet applications. Its architecture, built around store‑and‑forward message transfer, has proven remarkably scalable. This tutorial provides a deep technical examination of the email system, from the user agent to the mail server, and the protocols that glue them together.

We begin with a system‑level view, defining the components (UA, MTA, MDA) and their interactions. We then dissect the SMTP protocol, including its state machine, extensions, and the role of DNS MX records. The message format is explored through RFC 5322 and MIME (RFC 2045‑2049), with a focus on multipart structures and content encoding. The comparison between POP3 and IMAP highlights the fundamental design choices: download‑and‑delete vs. server‑side storage and synchronisation. Finally, we examine the security landscape, including SPF, DKIM, DMARC, and DANE, which combat spoofing and ensure transport security.


1. Email System Architecture

1.1 Components and Roles

1.2 Store‑and‑Forward Model

Email is not a real‑time protocol; it uses store‑and‑forward. An MTA accepts a message, queues it, and attempts delivery to the next hop. If delivery fails, the message is retried with exponential backoff (typically for several days). This makes the system tolerant of transient network failures.

1.3 DNS and MX Records

To find the destination MTA, the sending MTA performs a DNS lookup for MX (Mail Exchange) records of the recipient's domain. MX records have a preference value (lower is higher priority). The MTA then connects to the hostname returned, using port 25 (or 587 for submission).


2. SMTP Protocol – Technical Details

2.1 SMTP Commands and Response Codes

SMTP (RFC 5321) is a text‑based, command‑response protocol. Commands are 4‑letter words; responses are 3‑digit numeric codes with optional text.

CommandPurposeExample
HELO / EHLOIdentify client (EHLO for ESMTP)EHLO mail.example.com
MAIL FROMSpecify sender (reverse‑path)MAIL FROM:<sender@example.com>
RCPT TOSpecify recipient (forward‑path)RCPT TO:<recipient@example.net>
DATABegin message data (terminated by ".\r\n")DATA
QUITEnd sessionQUIT
RSETReset session (abort current mail transaction)RSET
VRFYVerify a mailbox (often disabled for security)VRFY user
EXPNExpand a mailing list (often disabled)EXPN list

Common responses: 220 (ready), 250 (OK), 354 (start mail input), 421 (service not available), 450 (mailbox unavailable, temporary), 550 (mailbox unavailable, permanent).

2.2 ESMTP Extensions

2.3 SMTP State Machine

Initial (waiting for connection) │ ├─ EHLO/HELO → Greeting │ │ │ ├─ MAIL FROM → Sender OK │ │ │ │ │ ├─ RCPT TO → Recipient OK (may repeat) │ │ │ │ │ │ │ ├─ DATA → Receive message body │ │ │ │ │ │ │ │ │ └─ . (end) → Queue message │ │ │ │ │ │ │ └─ RSET → Reset │ │ │ │ │ └─ QUIT → Close │ │ │ └─ QUIT → Close │ └─ QUIT → Close

2.4 SMTP Authentication and STARTTLS

To prevent open relays, MTAs require authentication for relaying (especially on submission ports). The AUTH command negotiates a mechanism; credentials are sent Base64‑encoded. STARTTLS upgrades the plaintext connection to TLS, protecting credentials and message content in transit.


3. Email Message Format and MIME

3.1 RFC 5322 Message Structure

A message consists of headers and a body, separated by a blank line. Headers include From, To, Subject, Date, Message‑ID, and optional Reply‑To, CC, BCC (though BCC is often stripped by MTAs). The body is plain ASCII text originally.

3.2 MIME (Multipurpose Internet Mail Extensions)

MIME (RFC 2045‑2049) extends email to support:

3.3 MIME Headers

3.4 Multipart Structure

Multipart messages use a boundary string to separate parts. Example for multipart/mixed:

Content‑Type: multipart/mixed; boundary="boundary123" --boundary123 Content‑Type: text/plain; charset="utf‑8" This is the plain text version. --boundary123 Content‑Type: image/png; name="image.png" Content‑Transfer‑Encoding: base64 Content‑Disposition: attachment; filename="image.png" iVBORw0KGgoAAAANSUhEUgAA... --boundary123--

4. Mail Retrieval: POP3 vs IMAP

4.1 POP3 (Post Office Protocol version 3)

4.2 IMAP (Internet Message Access Protocol)

4.3 POP3 vs IMAP – Detailed Comparison

FeaturePOP3IMAP
Server storageUsually no (download and delete)Yes (server retains messages)
Multi‑device syncPoor (flags not sync)Excellent (flags and folders sync)
Offline accessFull (messages stored locally)Partial (cached, sync on reconnect)
Bandwidth usageHigh (downloads all)Low (fetch headers, partial content)
Server‑side searchNoYes (SEARCH)
Push notificationsNo (polling)Yes (IDLE)

5. Email Security: SPF, DKIM, DMARC, DANE

5.1 SPF (Sender Policy Framework)

5.2 DKIM (DomainKeys Identified Mail)

5.3 DMARC (Domain‑based Message Authentication, Reporting & Conformance)

5.4 DANE (DNS‑based Authentication of Named Entities) for TLS


6. Email Delivery Workflow and Queuing

6.1 Complete Flow

  1. Sender composes message in UA.
  2. UA sends message to the configured outgoing MTA (submission port 587, with authentication).
  3. Outgoing MTA performs DNS MX lookup for recipient domain.
  4. MTA connects to the destination MTA (port 25) and performs SMTP transaction.
  5. Destination MTA checks spam, viruses, and authenticates sender using SPF/DKIM/DMARC.
  6. MDA delivers to recipient's mailbox (local storage).
  7. Recipient's UA retrieves via IMAP (or POP3) and displays.

6.2 Mail Queuing and Retry

If delivery fails (e.g., destination MTA unreachable), the message is queued. The MTA will retry with increasing intervals (e.g., 5 min, 15 min, 1 h, 4 h, etc.) until a maximum lifetime (e.g., 4‑5 days) is exceeded, after which a bounce message (DSN) is sent to the sender.


📝 Quiz: Tutorial 6

Q1: Which DNS record type is used to locate a mail server?

Answer

MX (Mail Exchange).

Q2: What SMTP command is used to start a mail transaction and specify the sender?

Answer

MAIL FROM.

Q3: What is the purpose of the MIME Content‑Transfer‑Encoding header?

Answer

It specifies how the message body is encoded (e.g., base64, quoted‑printable) to allow safe transmission over 7‑bit channels.

Q4: Which protocol supports server‑side mailboxes and folders?

Answer

IMAP.

Q5: What is the role of SPF in email security?

Answer

It authorises which IP addresses are allowed to send email for a domain, preventing spoofing.

Q6: How does DKIM protect email integrity?

Answer

It uses a digital signature over selected headers and body; the signature is verified against a public key published in DNS.

Q7: What does DMARC's p=reject policy do?

Answer

It instructs receivers to reject (discard) messages that fail SPF and/or DKIM authentication.

Q8: In IMAP, what is the purpose of the IDLE command?

Answer

It allows the server to push real‑time notifications of new messages to the client, avoiding polling.

Q9: What is the difference between RETR in POP3 and FETCH in IMAP?

Answer

RETR downloads the entire message; FETCH can retrieve specific parts (headers, body, MIME parts) and supports partial fetching.

Q10: Why is port 587 preferred over port 25 for client submission?

Answer

Port 587 requires authentication and supports STARTTLS; port 25 is typically for MTA‑to‑MTA relay and may be blocked by ISPs to prevent spam.

Q11: What is the function of the Message‑ID header?

Answer

It provides a globally unique identifier for the message, used for threading and tracking.

Q12: How does DANE improve SMTP security?

Answer

It uses DNS TLSA records to pin the expected certificate, reducing reliance on CAs and preventing MITM attacks.


✏️ Exercises: Tutorial 6

Exercise 1 – SMTP Session Trace

Interpret the following SMTP session and explain each response code.

220 mail.example.com ESMTP EHLO client.example.net 250‑mail.example.com Hello client.example.net 250‑SIZE 10240000 250‑AUTH PLAIN LOGIN 250 OK MAIL FROM:<sender@example.com> 250 2.1.0 Ok RCPT TO:<recipient@example.net> 250 2.1.5 Ok DATA 354 End data with <CR><LF>.<CR><LF> Subject: Test . 250 2.0.0 Ok: queued as 12345 QUIT 221 2.0.0 Bye
Sample Solution

220: service ready; 250: command OK (multiple with EHLO response); 354: start mail input; 250 after DATA: message queued; 221: closing connection.

Exercise 2 – MIME Message Construction

Create a MIME message with a plain text part, an HTML part, and an image attachment. Show all relevant headers and structure.

Sample Solution

Use multipart/mixed with a multipart/alternative child for text/html, and a separate part for the image with Content‑Type: image/png and Content‑Disposition: attachment.

Exercise 3 – IMAP Synchronisation

Explain how an IMAP client keeps read/unread status synced across multiple devices.

Sample Solution

The client uses STORE to set the \Seen flag on the server. All other clients will see the updated flag when they FETCH the message or when the server sends unsolicited flag updates (if supported).

Exercise 4 – Email Deliverability Troubleshooting

Emails from your domain are going to spam. What steps would you take?

Sample Solution

Check SPF, DKIM, DMARC records. Ensure reverse DNS (PTR) matches the sending IP. Check IP reputation (blacklists). Use a dedicated IP for bulk sending. Ensure DKIM signing uses a strong key. Monitor DMARC reports.

Exercise 5 – POP3 Session Walkthrough

Write the commands for a POP3 session that downloads message 1, marks it for deletion, then quits.

Sample Solution

USER username, PASS password, RETR 1, DELE 1, QUIT.

Exercise 6 – MTA Queuing Behavior

What happens if the destination MTA responds with a 450 (temporary failure)?

Sample Solution

The sending MTA queues the message and retries later with exponential backoff. After repeated failures, a DSN (bounce) may be sent to the sender.


📚 Homework: Tutorial 6

Homework 1 – Email Security Deployment

Design a complete email security deployment for a small business domain. Include SPF, DKIM, DMARC policies, and TLS configuration. Provide DNS records and justification for policy choices.

Guidance

Use a DMARC policy of p=quarantine initially, then progress to reject after monitoring.

Homework 2 – IMAP vs POP3 Decision

A company has 100 employees who use both desktop and mobile email clients. Which protocol would you recommend and why?

Guidance

Recommend IMAP for synchronisation, server‑side folders, and flags. Consider Exchange ActiveSync if push is needed.

Homework 3 – DANE and DNSSEC Research

Research the relationship between DANE and DNSSEC. How does DNSSEC protect TLSA records? What are the challenges in deploying DANE for SMTP?

Guidance

DNSSEC provides authentication of DNS responses; DANE relies on it. Challenges include DNSSEC adoption and CA opposition.

Homework 4 – Email Headers Analysis

Analyse the full headers of a spam email. Identify the authentication results (SPF, DKIM, DMARC) and trace the relay path.

Guidance

Look for Received headers, Authentication‑Results, and DKIM‑Signature.

Homework 5 – MIME Parsing Implementation

Write a simple MIME parser (in pseudo‑code) that extracts the plain text body from a multipart/alternative message.

Guidance

Parse boundaries, read Content‑Type headers, select the text/plain part, and decode transfer encoding if needed.


📌 Summary

This expanded tutorial has provided a comprehensive, technical examination of Internet email systems. Key takeaways:

Understanding these protocols and mechanisms is essential for managing mail servers, troubleshooting delivery issues, and securing email communications.