How to create a fake mail server on localhost
Creating a fake mail server on localhost can be useful for testing email-related functionality, such as sending and receiving emails, without actually sending emails to real mail servers. Here are a few ways to create a fake mail server on localhost:
Method 1: Using Mailhog
Mailhog is a popular, open-source tool that allows you to capture and inspect emails sent to your application. It's easy to set up and use.
- Install Mailhog using npm or yarn:
npm install -g mailhog
oryarn global add mailhog
- Start Mailhog:
mailhog
- Mailhog will start a fake mail server on
localhost:1025
and a web interface onhttp://localhost:8025
- Configure your application to send emails to
localhost:1025
instead of a real mail server - Inspect emails in the Mailhog web interface or using the
mailhog
command-line tool
Method 2: Using a Python script
You can create a simple Python script to act as a fake mail server using the smtpd
module.
- Create a new Python file (e.g.,
fake_smtp.py
) - Add the following code:
import smtpd import asyncore
class FakeSMTPServer(smtpd.SMTPServer): def process_message(self, peer, mailfrom, rcpttos, data): print(f"Received email from {mailfrom} to {rcpttos}")
You can also store the email in a file or database here
if name == "main": server = FakeSMTPServer(("localhost", 2525), None) asyncore.loop()
3. Run the script: `python fake_smtp.py`
4. Configure your application to send emails to `localhost:2525` instead of a real mail server
5. The script will print the received email to the console
**Method 3: Using a Docker container**
You can use a Docker container to run a fake mail server. One popular option is `mailserver`:
1. Install Docker: `docker run -d --name mailserver mailserver/mailserver`
2. Configure your application to send emails to `localhost:25` instead of a real mail server
3. The `mailserver` container will capture and store the emails in a database
These are just a few examples of how you can create a fake mail server on localhost. You can choose the method that best fits your needs.