Saturday, July 13, 2024

A Simple Python Email Server for offline use

 Creating a simple offline Python email server can be achieved using the smtplib library for sending emails and a basic SMTP server for testing. This server won't connect to the internet but will allow you to send and receive emails locally.

Here’s a step-by-step guide to set up a simple offline Python email server:

  1. Install Python Libraries: Ensure you have Python installed. You may also need the smtplib and email libraries, which are typically included in the standard library.

  2. Create a Local SMTP Server: Use Python’s smtpd module to create a local SMTP server.

  3. Send Emails: Use the smtplib module to send emails through the local server.

Here’s an example implementation:

Step 1: Create a Local SMTP Server

Create a Python script (local_smtp_server.py) to start a local SMTP server:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import smtpd
import asyncore

class CustomSMTPServer(smtpd.SMTPServer):
    def process_message(self, peer, mailfrom, rcpttos, data, **kwargs):
        print('Message received from:', peer)
        print('Message addressed from:', mailfrom)
        print('Message addressed to  :', rcpttos)
        print('Message length        :', len(data))
        return

if __name__ == '__main__':
    server = CustomSMTPServer(('localhost', 1025), None)
    asyncore.loop()

Step 2: Run the Local SMTP Server

Run the script in your terminal:

1
python local_smtp_server.py

The server will start and listen for incoming emails on localhost:1025.

Step 3: Send Emails Using the Local SMTP Server

Create another Python script (send_email.py) to send emails using the local server:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import smtplib
from email.mime.text import MIMEText

def send_email(subject, body, from_email, to_email):
    msg = MIMEText(body)
    msg['Subject'] = subject
    msg['From'] = from_email
    msg['To'] = to_email

    with smtplib.SMTP('localhost', 1025) as server:
        server.sendmail(from_email, [to_email], msg.as_string())

if __name__ == '__main__':
    subject = 'Test Email'
    body = 'This is a test email sent from a local SMTP server.'
    from_email = 'sender@example.com'
    to_email = 'receiver@example.com'

    send_email(subject, body, from_email, to_email)

Step 4: Run the Email Sending Script

Run the script in your terminal:

1
python send_email.py

You should see the email details printed in the terminal where the local SMTP server is running, indicating that the email was successfully sent and received by the server.

This setup allows you to test email sending and receiving functionalities locally without the need for an internet connection.

No comments:

Post a Comment