Receiving Emails with OpenWRT

In enterprise-level IoT device and network management, enabling devices to actively receive email notifications from servers is a common requirement. The email system plays an irreplaceable role in the IoT architecture. Email communication based on SMTP/IMAP/POP3 protocols provides a reliable asynchronous communication channel between devices and the cloud, as well as between devices and administrators.For bandwidth-constrained IoT environments, the email system offers a cost-effective data transmission solution.

OpenWRT, as an embedded Linux distribution, can be configured to set up a complete email receiving system.

This article will detail the entire process from system compilation configuration to actual deployment.

For sending emails with OpenWRT, please refer to the following article:

Sending Emails with OpenWRT

Author: Zhi Zhou Cai, WeChat Official Account: Linux IoT Notes – Sending Emails with OpenWRT

Basic Background

OpenWRT 2102 includes the fdm component by default, located in the feeds package directory. It can be used to send emails but only supports the IMAP protocol.

Component Path

Mail  --->   [*] fdm...... fetch mail and deliver

Example Configuration

# vi /etc/fdm.confaccount "qq" imaps server "imap.qq.com" port 993    user "<REDACTED_EMAIL>"    pass "<REDACTED_PASSWORD>"    keepaction "inbox" mbox "/tmp/Mail/inbox"match account "qq" action "inbox"

Start Execution

fdm -vv fetch

It was found that there were login issues, QQ email verification failed, with the error:

qq: unexpected data: 2 BAD Login parameters!qq: fetching error. aborted

NetEase email also reported an error:

163: fetching163: unexpected data: 3 NO SELECT Unsafe Login. Please contact [email protected] for help163: fetching error. aborted

Other email services can be queried and received normally. However, there are many issues, and the project is basically no longer maintained, so it will not be discussed further in this article.

To better meet the current functional requirements for email querying and receiving, a better approach is to port suitable applications to OpenWRT.

Modern Email Requirements

  • TLS/SSL Encrypted Connection (IMAPS/POP3S)
  • OAuth2 Authentication (especially since Gmail has gradually phased out “weak password” logins since 2022)
  • IDLE (Real-time Push)

After comparison, the open-source project fetchmail supports the first requirement, does not support the second, and the third can be satisfied through script polling. Overall, it can meet the daily usage scenarios for most cases, and it is actively maintained with good community support. The size of the compiled binary file is similar to fdm, making it the best email receiving application under the OpenWRT system.

fetchmail supports both IMAP and POP3 protocols. Below, only the IMAP protocol will be introduced.

IMAP Functionality Support

Verification fetchmail successfully supports receiving from the following email service providers:

foxmail, yandex, qq, sina, sohu, 163, 126

hotmail, outlook, live, office365: Microsoft email services, using OAuth2 authentication, currently not supported; or suitable applications can be ported to OpenWRT to implement email receiving functionality.

IMAP server querying and authorization codes need to be enabled by logging into the email website and operating in the email settings. Major domestic email service providers generally support POP3/SMTP/IMAP services.

Example of enabling authorization code for QQ email: login → "Settings" → "Account" → Account and Security → Security Settings → find "POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV services" → generate authorization code.

Porting Open Source Projects

Porting open-source projects to the OpenWRT project mainly involves configuring the Makefile for compilation.

The project source code can be downloaded here:

https://sourceforge.net/projects/fetchmail

Porting to the OpenWRT project directory

openwrt/package/mail/fetchmail/

It is important to note that the version of OpenSSL required by fetchmail must match the current version of OpenWRT’s OpenSSL.

You can refer to the fetchmail package in this repository:

https://github.com/bunny-chz/fetchmail

Click the bottom Read the original text to go directly to the repository.

For specific content, please refer to the README file in the repository.

The repository mainly solves the login issue for NetEase domain emails by sending a command that conforms to the RFC 2971 standard ID extension format when detecting a NetEase domain email during login:

a001 ID ("name" "fetchmail" "version" "6.4.39" "vendor" "OpenWRT")

Declaring client information to the server.

After porting, compile

Once the Makefile, patches, and configuration files are ready, start verifying whether the ported project can compile successfully.

Execute

make menuconfig

Open the macro

Mail  ---> [*]fetchmail... Fetch mail from remote IMAP/POP3 servers

If you need to process email information, open the macro

Mail  ---> [*]mblaze... Unix utilities to deal with Maildir

Temporarily compile fetchmail separately

make package/mail/fetchmail/compile V=s

Error Resolution

make[1]: *** No rule to make target 'package/mail/fetchmail/clean'.  Stop.

The settings in menuconfig did not take effect, due to old caches or intermediate files interfering with the loading of new configurations. It is recommended to clean and then compile.

make cleanmake package/mail/fetchmail/{clean,compile} V=s

After successful compilation, since fetchmail only produces a single binary file, its directory is as follows:

openwrt/build_dir/target-<architecture>_musl/fetchmail-<version>

You can upload it to the OpenWRT system for temporary verification of usability.

Execute the command line

fetchmail -V

If the version number is displayed normally, it indicates that the porting was successful.

Finally, compile the entire firmware and flash it to the board device for use.

Configuration File

The default configuration file is /root/.fetchmailrc

Example configuration file, supporting IMAP protocol.

poll imap.example.comproto IMAPuser [email protected] examplesslsslcertcksslcertfile /etc/ssl/certs/ca-certificates.crtkeep# unit: byte, email size limitation# limit 100000mda /usr/bin/fetchmail_deliver.sh

Explanation

Custom configuration file /etc/config/fetchmailrc can be specified using fetchmail -f.

Permissions 600 (-rw——-)

poll imap.example.com: Specify the hostname of the email server to poll (check).

proto IMAP: Use the IMAP protocol (instead of POP3) to communicate with the server.

user [email protected]: The username for logging into the email (the full email address).

password example: The authorization code for the IMAP service corresponding to the account.

ssl: Enable SSL/TLS encrypted connection to ensure secure communication.

sslcertck: Enable SSL certificate verification to prevent man-in-the-middle attacks.

sslcertfile /etc/ssl/certs/ca-certificates.crt: Specify the path to the trusted CA certificate bundle for verifying the validity of the server certificate (usually the system’s default CA certificate store).

keep: Retain the original emails on the server (i.e., do not delete the server copy after downloading). To delete, remove this line or replace it with fetchall + no keep.

limit 100000: A commented option to limit downloading emails smaller than 100,000 bytes (about 100 KB). To enable, uncomment and adjust the value as needed.

mda /usr/bin/fetchmail_deliver.sh: Specify the Mail Delivery Agent (MDA), all successfully fetched emails will be processed through this script (e.g., delivered to the local MTA, stored in Maildir, or trigger other automation operations).

Start Receiving Emails

fetchmail -f /etc/config/fetchmailrc -v

-f: Specify the configuration file

-v: Output detailed information

By default, it receives unread email information.

Successful login log (the successful exit status is 1)

~# fetchmail -f /etc/config/fetchmailrc -vfetchmail: Server certificate:fetchmail: Subject CommonName: *.mail.qq.comfetchmail: will idle after pollfetchmail: IMAP> A0001 LOGINfetchmail: IMAP< A0001 OK Success login okfetchmail: IMAP> A0002 SELECT "INBOX"fetchmail: IMAP< * SEARCHfetchmail: IMAP< A0003 OK SEARCH completedfetchmail: IMAP> A0004 LOGOUTfetchmail: IMAP< * BYE LOGOUT receivedfetchmail: IMAP< A0004 OK LOGOUT Completedfetchmail: 6.4.39 querying imap.qq.com (protocol IMAP) at Wed, 20 Jun 2024 07:14:24 +0800 (UTC): poll completedfetchmail: normal termination, status 1

Since the mda item in the configuration file specifies the receiving processing script /usr/bin/fetchmail_deliver.sh, the script is mainly responsible for saving the received email content in a single email format in $MAILDIR/new, achieving atomic processing of emails. For specific operations, click Read the original text to view.

Check the save directory of the script to see if there are new emails

ls -l /tmp/maildir/new/

Processing Email Content

The email files saved in the temporary directory /tmp/maildir/new/ follow the standard RFC 2822 / RFC 5322 structure for individual emails.

The content format is as follows:

[Email Header]From: [email protected]: [email protected]: Test EmailDate: Wed, 5 Jun 2025 07:00:00 +0800MIME-Version: 1.0Content-Type: text/plain; charset=utf-8[Empty Line][Email Body]Hello, this is a test email.

The header fields exist in the form of Field Name: Value.

There must be an empty line between the header and the body.

MIME encoding (such as base64) is supported for attachments or non-ASCII content.

Using the previously compiled mblaze tool, common email information can be retrieved. mblaze contains several small components.

Below is a summary of common email processing command lines.

# Extract senderFrommaddr -a from /tmp/maildir/extract/ 2>/dev/null | head -n 1# Extract recipientTomaddr -a from /tmp/maildir/extract/ 2>/dev/null | sed -n '2p'# Extract subjectSubjectmhdr -h subject /tmp/maildir/extract/ 2>/dev/nullmhdr -h subject /tmp/maildir/extract/# Extract bodyBody (text/plain)mshow -O /tmp/maildir/extract/ 2

At this point, you have successfully retrieved the email information you wanted from the server.

Email communication, as an important supplement to the IoT communication system, perfectly matches the asynchronous, reliable, and cross-platform characteristics of IoT device applications. As the scale of IoT continues to expand, this mature and stable communication method will continue to play a key role.

Leave a Comment