Labs / MicroPython tutorials

Mail Delivery µMail - Lightweight SMTP Client

Author: Li Zisheng · Source: FreakStudio open documentation, v1.0 · License: CC BY 4.0

Contents

I. Background and Core Positioning

1.1 Development Background

MicroPython is a lightweight implementation of Python designed specifically for embedded devices (such as MCUs like ESP32/ESP8266 and PyBoard), and its operating environment is characterized by limited memory (in the order of kilobytes), simplified network libraries, and constrained performance:

1.2 Core Functions of µMail

µMail (MicroMail) is a lightweight SMTP Client tailored specifically for MicroPython, with the core objectives as follows:

Simply put:µMail enables MCUs such as the ESP32/ESP8266 to send emails easily and securely, serving as a core tool for remote notifications on embedded devices.

Source Code Repository: https://github.com/shawwwn/uMail

II. Core Implementation Principles

2.1 Underlying Dependencies

µMail only relies on the built-in modules of MicroPython:

2.2 Introduction to Core Interaction Procedures and Core Methods of the SMTP Protocol

SMTP (Simple Mail Transfer Protocol) is the standard protocol for email transmission, and µMail is essentially a "minimalist implementation" of the SMTP protocol. Its core interaction process and core methods are as follows:

Mail Delivery µMail - Lightweight SMTP Client

The core features can be summarized as follows:

III. Instructions for Use

3.1 Environment Preparation

Email ProviderSMTP ServerNon-SSL PortSSL PortHow to Get Authorization Code / App Password (Summary)
QQ Mailsmtp.qq.com587465Settings → Account → Enable POP3/SMTP/IMAP → Generate SMTP/POP3 authorization code
163 Mailsmtp.163.com587465Settings → POP3/SMTP/IMAP or Security Settings → Enable SMTP service → Generate authorization code (or client authorization password)
Gmail (Google)smtp.gmail.com587465Enable 2-Step Verification → Go to App Passwords → Generate a 16-digit app password for "Mail" or a custom app

Among these, it is extremely important to note that the authorization code and the login password are two distinct things:

ItemQQ login passwordAuthorization code
PurposeLog in to QQ / web mailboxLog in to third-party clients
Scope of UseOfficial servicesPOP3 / IMAP / SMTP, etc.
SecurityHigh risk of exposureCan be revoked individually
Can be managed separately❌✅

An authorization code can be used to log in to the following QQ Mail services:

👉 Essentially, an authorization code is a dedicated key for "third-party applications". It is recommended that one device / one program corresponds to one unique authorization code.

3.2 Configuration Taking QQ Mail as an Example

Mail Delivery µMail - Lightweight SMTP Client

After clicking the "Settings" button in the top-right corner on the homepage of QQ Mail, we will enter the main settings page. Next, we need to locate and click the "Account and Security" option in the left menu bar to access the account security configuration interface.

Mail Delivery µMail - Lightweight SMTP Client

After entering the "Account & Security" page, locate the "Security Settings" option in the left navigation bar and click on it to access the core configuration page related to security.

Mail Delivery µMail - Lightweight SMTP Client

In the security settings page, we locate the "POP3/IMAP/SMTP/Exchange/CardDAV Services" section, which is the key entry for configuring third-party Mail User Agents. Clicking "Configuration Method" allows you to learn the protocol details first.

Mail Delivery µMail - Lightweight SMTP Client

After clicking "Configuration Method", we are directed to the instruction page for POP3/IMAP/SMTP services, which elaborates on the differences between these protocols and the function of authorization codes. After familiarizing ourselves with this information, we return to the security settings page to proceed with the configuration.

https://wx.mail.qq.com/list/readtemplate?name=app_intro.html#/agreement/authorizationCode

Mail Delivery µMail - Lightweight SMTP Client

Simply put, the summary is as follows:

ProtocolFull NameMain FunctionIn One Sentence
POP3Post Office Protocol v3Receive email (download)Moves mail to the local machine; the server is mostly left alone afterward
IMAPInternet Message Access ProtocolReceive email + synchronized managementLocal and server stay in "real-time sync"
SMTPSimple Mail Transfer ProtocolSend emailDedicated to "sending mail out"

The uses of these different protocols can be briefly summarized as follows:

The core differences between POP3 and IMAP are as follows:

ComparisonPOP3IMAP
Syncs with Server❌ No✅ Yes (two-way sync)
Default Mail BehaviorDownloaded locallyKept on the server
Local Actions Affect Server❌ No effect✅ Synced
Multi-Device Sync Support❌ Very poor✅ Very good
Can Download Headers Only❌ No✅ Supported
Suitable ScenariosSingle device, legacy clientsMultiple devices, modern use
Officially Recommended by QQ Mail❌ Not recommended✅ Recommended

When in use, the general login information that a third-party Client needs to fill in is as follows:

ItemWhat to Enter
Username / AccountFull QQ Mail address (e.g., xxx@qq.com)
Email addressFull QQ Mail address
PasswordAuthorization code (not the QQ password)

You can choose from the following two options for the configuration of a third-party Client for QQ Mail:

OptionFunction typeProtocolServer addressPortEncryptionRecommendation
Option 1Receive emailIMAPimap.qq.com993SSL⭐⭐⭐⭐⭐ (Recommended)
Send emailSMTPsmtp.qq.com465 / 587SSL / STARTTLS⭐⭐⭐⭐⭐
Option 2Receive emailPOP3pop.qq.com995SSL⭐ (Not recommended)
Send emailSMTPsmtp.qq.com465 / 587SSL / STARTTLS⭐⭐⭐

When using POP3, the following points should be noted:

NotesDescription
Keep server copyWhen using POP3, be sure to check "Keep a copy of messages on the server", otherwise messages may be deleted from the server
Multi-device syncPOP3 does not support multi-device status sync, which can easily cause lost or disordered email
Official recommendationQQ Mail officially recommends using the IMAP + SMTP option first

To sum up, IMAP is recommended for receiving emails, SMTP should be used uniformly for sending emails, and POP3 is not recommended unless there are specific special requirements.

Mail Delivery µMail - Lightweight SMTP Client

Return to the security settings page, where you will see that you need to bind your mobile phone number first to enable the service. After clicking "Go to Bind" to complete the mobile phone number binding, the "Enable Service" button will be activated, and then we click this "Enable Service" button.

Mail Delivery µMail - Lightweight SMTP Client

After tapping "Enable Service", the system will enter the SMS verification step. You can complete the verification by scanning a code or sending an SMS manually, then tap "I Have Sent" to submit the verification information.

Mail Delivery µMail - Lightweight SMTP Client
Mail Delivery µMail - Lightweight SMTP Client
Mail Delivery µMail - Lightweight SMTP Client

After returning to the security settings page, check the option "Save to server after SMTP sending" in the "Receiving Options" section, which ensures that emails sent via a third-party Client will also be retained as backups on the QQ Mail server.

3.3 Relevant Cases

3.3.1 WiFi Connection (Mandatory Preparatory Step)

The MCU must connect to WiFi first before accessing the SMTP server; the complete WiFi connection code is provided below:

import network
import time

# Your WiFi configuration (replace with the actual SSID and password)
WIFI_SSID = "Xiaomi_D0EC"
WIFI_PASSWORD = "12345678"

def connect_wifi():
    """Connect to WiFi, return whether the connection succeeded"""
    # Create a WLAN object (Pico 2W uses STA mode, i.e. client mode)
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)  # Activate WiFi
    
    # Avoid reconnecting
    if wlan.isconnected():
        print("已连接 WiFi,IP 地址:", wlan.ifconfig()[0])
        return True
    
    # Start connecting to WiFi
    print("正在连接 WiFi:", WIFI_SSID)
    wlan.connect(WIFI_SSID, WIFI_PASSWORD)
    
    # Wait for connection (up to 10 seconds)
    timeout = 10
    while not wlan.isconnected() and timeout > 0:
        print("等待连接中...剩余超时时间:", timeout, "秒")
        time.sleep(1)
        timeout -= 1
    
    # Check the connection result
    if wlan.isconnected():
        print("WiFi 连接成功!IP 地址:", wlan.ifconfig()[0])
        return True
    else:
        print("WiFi 连接失败,请检查 SSID/密码或网络环境")
        return False

# Run the WiFi connection (it must succeed before continuing to send the email)
if not connect_wifi():
    raise Exception("WiFi 连接失败,无法继续发送邮件")
Mail Delivery µMail - Lightweight SMTP Client

3.3.2 Basic Usage (WiFi + Email Sending)

First, we import the umail library:

Mail Delivery µMail - Lightweight SMTP Client

On the basis of a successful WiFi connection, here is the complete code for sending a short text email. Note that only by using port 465 for SSL and including the From/To/Subject/MIME-Version/Content-Type standard headers can the email be properly displayed and visible in QQ Mail:

import umail
import network
import time

WIFI_SSID = "Xiaomi_D0EC"
WIFI_PASSWORD = "12345678"

def connect_wifi():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if wlan.isconnected():
        print("已连接 WiFi:", wlan.ifconfig()[0])
        return True
    wlan.connect(WIFI_SSID, WIFI_PASSWORD)
    timeout = 10
    while not wlan.isconnected() and timeout > 0:
        time.sleep(1)
        timeout -= 1
    if wlan.isconnected():
        print("WiFi 连接成功:", wlan.ifconfig()[0])
        return True
    else:
        print("WiFi 连接失败")
        return False

if not connect_wifi():
    raise Exception("WiFi 连接失败")

# ========== Send email (using SSL port 465) ==========
FROM = "123456@qq.com"             # Your QQ mailbox (full address)
TO = "real_recipient@domain.com"   # Replace with the real recipient address
SUBJECT = "Pico 2W 告警通知"
BODY = "树莓派 Pico 2W 测试邮件:设备运行正常!"

try:
    smtp = umail.SMTP(
        host="smtp.qq.com",
        port=465,
        ssl=True,                 # Use SSL (465)
        username=FROM,
        password="abcdefghijklmn" # QQ mailbox authorization code (not the login password)
    )

    # Add standard headers; it is safer if From matches the login user
    msg = (
        "From: {}\r\n"
        "To: {}\r\n"
        "Subject: {}\r\n"
        "MIME-Version: 1.0\r\n"
        "Content-Type: text/plain; charset=UTF-8\r\n"
        "\r\n"
        "{}"
    ).format(FROM, TO, SUBJECT, BODY)

    smtp.to(TO)
    smtp.send(msg)
    smtp.quit()
    print("邮件发送成功(已通过 SMTP 提交)!")
except Exception as e:
    print("邮件发送失败:", e)

Wherein:

Mail Delivery µMail - Lightweight SMTP Client

After completing the SMTP service configuration and the writing of the corresponding function code, click Run, and we can see that the email titled "Pico 2W Long Email Test (Chunked Sending)" has successfully appeared in the QQ mailbox inbox:

Mail Delivery µMail - Lightweight SMTP Client

3.3.3 Advanced Usage: Sending Long Emails in Batches

The Pico 2W has limited memory, so long emails must be sent in chunks using write ():

import umail
import network
import time

# ====================== Step 1: Connect to WiFi ======================
WIFI_SSID = "Xiaomi_D0EC"
WIFI_PASSWORD = "12345678"

def connect_wifi():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if wlan.isconnected():
        print("已连接 WiFi:", wlan.ifconfig()[0])
        return True
    wlan.connect(WIFI_SSID, WIFI_PASSWORD)
    timeout = 10
    while not wlan.isconnected() and timeout > 0:
        time.sleep(1)
        timeout -= 1
    if wlan.isconnected():
        print("WiFi 连接成功:", wlan.ifconfig()[0])
        return True
    else:
        print("WiFi 连接失败")
        return False

if not connect_wifi():
    raise Exception("WiFi 连接失败")

# ====================== Step 2: Send email (SSL port 465) ======================
# Configure email information (replace with actual values)
FROM_EMAIL = "123456@qq.com"          # Your QQ mailbox (must match the login account)
TO_EMAIL = "real_recipient@domain.com"# Real recipient mailbox
EMAIL_SUBJECT = "Pico 2W 设备告警通知"
EMAIL_BODY = """树莓派 Pico 2W 测试邮件:
Device running status: normal
Current time: 2026-01-24
Sensor data: temperature 28℃ | humidity 60%
"""

# Build the email content with standard headers (key: specify UTF-8 encoding to avoid garbled Chinese text)
EMAIL_MSG = (
    "From: {from_email}\r\n"
    "To: {to_email}\r\n"
    "Subject: {subject}\r\n"
    "MIME-Version: 1.0\r\n"
    "Content-Type: text/plain; charset=UTF-8\r\n"
    "\r\n"  # A blank line is required between the headers and the body (SMTP protocol requirement)
    "{body}"
).format(
    from_email=FROM_EMAIL,
    to_email=TO_EMAIL,
    subject=EMAIL_SUBJECT,
    body=EMAIL_BODY
)

try:
    # Initialize the SMTP client (QQ Mail, port 465 SSL)
    smtp = umail.SMTP(
        host="smtp.qq.com",
        port=465,                # SSL-only port
        ssl=True,                # SSL must be enabled
        username=FROM_EMAIL,     # Login account = sender email
        password="abcdefghijklmn"# QQ Mail authorization code (not the login password)
    )

    # Specify the recipient (must match the To header of the email)
    smtp.to(TO_EMAIL)
    
    # Send the email content with standard headers
    smtp.send(EMAIL_MSG)
    
    # Close the connection (required)
    smtp.quit()
    
    print("邮件发送成功!已通过 SSL 465 端口提交")
except Exception as e:
    print("邮件发送失败:", str(e))
Mail Delivery µMail - Lightweight SMTP Client
Mail Delivery µMail - Lightweight SMTP Client

Click to view the details of this email, and you will see that the email fully contains log information such as device startup and Data Acquisition, which means that we have not only successfully completed the configuration of the QQ mailbox SMTP service, but also realized the function of chunking and sending long emails, and the entire email sending process can operate normally.

3.3.4 Advanced Usage: Custom MAIL FROM Address

Some professional email service providers (such as AWS SES and enterprise email) support the separation of the "sender address (MAIL FROM)" from the login account, which needs to be customized via the smtp.to () mail_from parameter (sender/domain verification needs to be completed in advance on the service provider's backend).

The following is a complete example adapted to port 465 SSL and containing standard email headers (taking AWS SES as an example):

import umail
import network
import time

# ====================== Step 1: Connect to WiFi ======================
WIFI_SSID = "Xiaomi_D0EC"
WIFI_PASSWORD = "12345678"

def connect_wifi():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if wlan.isconnected():
        print("已连接 WiFi:", wlan.ifconfig()[0])
        return True
    wlan.connect(WIFI_SSID, WIFI_PASSWORD)
    timeout = 10
    while not wlan.isconnected() and timeout > 0:
        time.sleep(1)
        timeout -= 1
    if wlan.isconnected():
        print("WiFi 连接成功:", wlan.ifconfig()[0])
        return True
    else:
        print("WiFi 连接失败")
        return False

if not connect_wifi():
    raise Exception("WiFi 连接失败")

# ====================== Step 2: Send email with custom MAIL FROM ======================
# Configuration (replace with actual values)
SMTP_USERNAME = "AKIAXXXXXXXXXXXXXX"  # AWS SES login account (not an email address)
SMTP_PASSWORD = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"  # AWS SES authorization code
SMTP_HOST = "email-smtp.us-west-2.amazonaws.com"  # AWS SES SMTP server
TO_EMAIL = "someones@gmail.com"  # Recipient email
CUSTOM_MAIL_FROM = "notification@my-domain.com"  # Custom sender address (must be verified in AWS)
EMAIL_SUBJECT = "自定义 MAIL FROM 测试(SSL 465)"
EMAIL_BODY = """这是通过 Pico 2W 发送的自定义发件人测试邮件:
- Login account: {smtp_user}
- Actual sender (MAIL FROM): {custom_from}
- Recipient: {to_email}
""".format(smtp_user=SMTP_USERNAME, custom_from=CUSTOM_MAIL_FROM, to_email=TO_EMAIL)

# Build the email content with standard headers
EMAIL_MSG = (
    "From: {custom_from}\r\n"  # Sender shown in the email (recommended to match MAIL FROM)
    "To: {to_email}\r\n"
    "Subject: {subject}\r\n"
    "MIME-Version: 1.0\r\n"
    "Content-Type: text/plain; charset=UTF-8\r\n"
    "\r\n"
    "{body}"
).format(
    custom_from=CUSTOM_MAIL_FROM,
    to_email=TO_EMAIL,
    subject=EMAIL_SUBJECT,
    body=EMAIL_BODY
)

try:
    # Initialize the SMTP client (AWS SES, port 465 SSL)
    smtp = umail.SMTP(
        host=SMTP_HOST,
        port=465,                # AWS SES supports port 465 SSL
        ssl=True,                # Force SSL on
        username=SMTP_USERNAME,  # AWS SES login account (different from the custom sender)
        password=SMTP_PASSWORD   # AWS SES authorization code
    )

    # Key: customize the MAIL FROM address via the mail_from parameter
    smtp.to(TO_EMAIL, mail_from=CUSTOM_MAIL_FROM)
    
    # Send the email with standard headers
    smtp.send(EMAIL_MSG)
    
    # Close the SSL connection
    smtp.quit()
    
    print(f"邮件发送成功!自定义 MAIL FROM:{CUSTOM_MAIL_FROM}")
except Exception as e:
    print(f"自定义 MAIL FROM 发送失败:{str(e)}")

Please note the following when using it:

IV. API Reference

4.1 Core Class: umail.SMTP

Initialization method:

umail.SMTP(host, port, ssl=False, username=None, password=None)
ParameterTypeDescription
hoststrSMTP server address (e.g., smtp.qq.com, smtp.gmail.com)
portintServer port (587 = non-SSL / STARTTLS; 465 = SSL)
sslboolWhether to use SSL encryption directly: set to True if using 465, False if using 587 (and use STARTTLS)
usernamestrEmail account (usually the full email address; optional, if not passed at initialization, login() can be called later)
passwordstrEmail authorization code or app-specific password (optional, used together with username; do not use the main email login password)

4.2 Core Methodology

MethodPurpose
login(username, password)Log in to the SMTP server manually (used when no account/password was passed at initialization).
to(addrs, mail_from=None)Specify recipients: - addrs: string (single) or list (multiple); - mail_from: custom sender (default = login account, recommended not to change).
write(content)Send content to the server in chunks (content is a string or binary), no return value (used for sending long message bodies or segmented upload).
send(content='')Finish sending the email: - content: optional, short content can be passed directly as the complete email (including headers); for long content, call write() first to upload in chunks, and pass an empty string here; - Returns: (status code, response message).
quit()Send the QUIT command and close the SSL-encrypted TCP connection (must be executed to end the session properly).

5. Precautions for Use

Version Record

Version Number

Revision Date

Modifier

Modify Content

v1.0

2026-01-24

Lee Eonyong

Initial release, based on the release date 2026-01-19 (MicroPython v1.24.0)