Get Remote IP with aiosmtpd in Python 3.12: Step-by-Step Guide (2026)

Learn to extract remote IP addresses using aiosmtpd in Python 3.12. Enhance your SMTP server's logging and security with this step-by-step guide.

Get Remote IP with aiosmtpd in Python 3.12: Step-by-Step Guide (2026)

In this tutorial, you'll learn how to extract the remote IP address from an SMTP connection using the aiosmtpd module in Python 3.12. This can be particularly useful for logging, debugging, or applying connection-specific rules in your SMTP server implementation.

Key Takeaways

  • Learn how to configure aiosmtpd to access connection details.
  • Understand how to use the handle_DATA method to intercept SMTP transactions.
  • Access the remote IP address within the SMTP session context.
  • Implement error handling for common connection issues.

Introduction

The aiosmtpd module is a powerful Python library for creating asynchronous SMTP servers. One common requirement when working with SMTP servers is to log or utilize the IP address of the client making the connection. This information can be crucial for security, analytics, or even custom server logic.

As of Python 3.12, aiosmtpd provides a straightforward way to access connection-specific information, including the remote IP address. This guide will walk you through the steps required to implement this functionality in a simple, effective way.

Prerequisites

  • LinuxMint 22.3 or another compatible Linux distribution.
  • Python 3.12 installed on your system.
  • Basic understanding of SMTP protocol and Python programming.
  • aiosmtpd module installed (latest version as of 2026).

Step 1: Install aiosmtpd

First, ensure that the aiosmtpd module is installed on your system. You can do this using pip:

pip install aiosmtpd

This will install the latest version of aiosmtpd compatible with Python 3.12.

Step 2: Setup a Basic SMTP Server

Create a basic SMTP server using aiosmtpd to handle incoming connections. We'll extend its functionality to capture the remote IP address.

import asyncio
from aiosmtpd.controller import Controller

class CustomSMTPHandler:
    async def handle_DATA(self, server, session, envelope):
        # Extract the remote IP address
        remote_ip = session.peer[0]
        print(f'Remote IP address: {remote_ip}')
        
        # Your logic here
        return '250 OK'

if __name__ == '__main__':
    handler = CustomSMTPHandler()
    controller = Controller(handler, hostname='localhost', port=8025)
    controller.start()
    print('SMTP server running on localhost:8025')
    try:
        # Run the server until interrupted
        asyncio.get_event_loop().run_forever()
    except KeyboardInterrupt:
        pass

This code sets up an SMTP server on localhost, port 8025, and logs the remote IP address whenever data is received.

Step 3: Understand the handle_DATA Method

The handle_DATA method in your handler class is responsible for processing the SMTP DATA command, which typically contains the email message. Within this method, the session object provides access to the connection details, including the remote IP via session.peer[0].

By accessing session.peer[0], you can log or use the IP address for custom server logic.

Step 4: Implement Error Handling

Network interactions can fail for various reasons. Implement error handling to ensure your server remains robust and informative during failures.

class SafeSMTPHandler:
    async def handle_DATA(self, server, session, envelope):
        try:
            remote_ip = session.peer[0]
            print(f'Remote IP address: {remote_ip}')
            
            # Additional logic here
            return '250 OK'
        except Exception as e:
            print(f'Error processing data: {e}')
            return '451 Temporary server error'

This code ensures that any exception is caught, and a temporary error is returned if handling fails.

Common Errors/Troubleshooting

  • Connection Refused: Ensure that the specified port is open and not used by another service.
  • Address Already in Use: Check if another instance of your server or any service is using the same port.
  • Module Not Found: Verify that aiosmtpd is installed properly and accessible to your Python environment.
  • Permission Denied: If binding to a port below 1024, ensure the script runs with appropriate permissions.

Conclusion

By following this guide, you now have a functional SMTP server using aiosmtpd that can log the IP address of incoming connections. This setup provides a foundation for more complex mail handling and security implementations.

Frequently Asked Questions

How can I install the aiosmtpd module?

You can install it using pip with the command: pip install aiosmtpd.

What Python version is required for this setup?

This tutorial uses Python 3.12, but earlier versions may also work with some adjustments.

Can I run the SMTP server on a different port?

Yes, you can specify a different port when initializing the Controller object by changing the port parameter.