Contents
Introduction
Every developer who has ever built a contact form, a password reset feature, or an order confirmation email has faced the same problem: how do you test email functionality without accidentally sending messages to real users?
Early in my career, I once triggered a test batch of 500 “Welcome” emails to a production user database because I forgot to swap the SMTP credentials. The support inbox exploded. The lesson stuck: never test email against real inboxes during development.
That is exactly what Mailpit solves. It is a lightweight, open-source tool that captures every email your application sends — locally — and presents them in a clean web interface. No messages reach the internet. No real users get spammed. You get full visibility into headers, HTML, attachments, and raw source.
This guide covers everything: installing Mailpit on Windows, macOS, and Linux; configuring it for WordPress, Laravel, Node.js, Python, and Docker; understanding how it works under the hood; and troubleshooting the issues you will actually encounter.
Important: Mailpit is a development-only tool. It does not send emails to Gmail, Outlook, or any external provider. Think of it as a safety net that catches every outgoing message before it leaves your machine.
What Is Mailpit?
Mailpit is an open-source email testing tool written in Go. It acts as a local SMTP server that intercepts outgoing emails from your applications and stores them in a built-in database. You then inspect those emails through a web-based inbox running in your browser.
Think of it as a digital fishing net placed between your application and the internet. Every email your app tries to send gets caught in the net. You can examine each one, but none ever swim out to the open ocean.
Key Characteristics
| Attribute | Description |
|---|---|
| Type | Local SMTP server + Web UI for email inspection |
| License | Open source (MIT) |
| Language | Go (single binary, no dependencies) |
| Platforms | Windows, macOS, Linux, Docker |
| Default SMTP Port | 1025 |
| Default Web UI Port | 8025 |
| Database | SQLite (in-memory by default, persistent file optional) |
How Mailpit Works
Understanding the email lifecycle inside Mailpit helps you debug issues faster and configure it correctly for any stack. Here is the complete flow:
The Email Lifecycle
- Your application generates an email. This could be a WordPress password reset, a Laravel notification, or a Node.js transactional email. The email contains a recipient, subject, body, headers, and optionally attachments.
- The application connects to Mailpit via SMTP. Instead of connecting to Gmail’s SMTP server or SendGrid, your app connects to
127.0.0.1:1025(or whatever port you configured). No authentication is required by default. - Mailpit receives and parses the message. It reads the SMTP envelope, extracts headers, decodes the body (handling both plain text and MIME multipart), and stores attachments separately.
- The message is stored in SQLite. By default, Mailpit uses an in-memory database, meaning emails vanish when you close Mailpit. You can optionally specify a file path for persistence.
- The web UI updates in real time. Open
http://localhost:8025and new emails appear instantly. No refresh required. - You inspect, debug, and iterate. Click any message to view HTML preview, plain text, headers, raw source, or download attachments. Fix your template, trigger the email again, and compare.
What Happens to the Email After Capture?
Nothing. That is the point. Mailpit does not attempt delivery to external servers. The email sits in its database until you delete it or Mailpit restarts (if using in-memory storage). This is what makes it safe for development: there is zero chance of a test email reaching a real person.
Why Developers Use Mailpit
Before Mailpit, developers had a few painful options for testing email:
- Create a disposable Gmail account and hope you do not hit rate limits.
- Use a real SMTP provider in staging and pray nobody gets a test notification.
- Install MailHog, which worked well but is no longer actively maintained.
- Write emails to log files and read raw text in a terminal.
Mailpit improves on all of these. Here is what makes it worth adopting:
| Benefit | What It Means for You |
|---|---|
| Zero Risk | Emails never leave your machine. No accidental sends to real users. |
| Instant Feedback | Emails appear in the web UI the moment your app sends them. No delays. |
| HTML Preview | See exactly how your email renders in a browser before it goes to a real inbox. |
| Header Inspection | Debug SPF, DKIM, MIME boundaries, and routing headers without external tools. |
| Attachment Handling | Download and inspect PDFs, images, and other attachments sent by your app. |
| Raw Source | View the complete MIME message exactly as it would travel over the wire. |
| Single Binary | No dependencies, no package managers, no complex setup. One file runs everything. |
| Cross-Platform | Same workflow on Windows, macOS, and Linux. Docker image available too. |
Mailpit vs. Real Email
This is the most important concept to internalize. Mailpit is not a replacement for Gmail, SendGrid, Amazon SES, or any production email service. It is a development tool with a completely different purpose.
Warning: Mailpit does NOT send emails to Gmail, Outlook, Yahoo, or any external mail server. It captures emails locally and displays them in a browser. If you need to deliver real emails, use a production SMTP provider.
| Aspect | Mailpit | Real SMTP (Gmail, SendGrid, etc.) |
|---|---|---|
| Purpose | Development testing | Production email delivery |
| Delivery | None — emails stay local | Delivers to real inboxes worldwide |
| Authentication | Optional / Off by default | Required (API keys, OAuth, passwords) |
| Encryption | Optional / Off by default | Required (TLS/SSL) |
| Rate Limits | None | Strict (varies by provider) |
| Cost | Free | Free to paid tiers |
| Network | Localhost only | Internet required |
The analogy I use with junior developers: Mailpit is like a practice net on a driving range. You can hit as many golf balls as you want, examine your swing, and adjust your technique. But those balls never leave the range. When you are ready for the real course, you switch to a production SMTP provider.
Cross-Platform Installation
Mailpit is distributed as a single static binary for each platform. There is no installer, no registry modification, and no background service required. You download, extract, and run. This simplicity is one of its biggest strengths.
6.1 Windows Installation
Windows is the most common platform for WordPress developers using LocalWP, XAMPP, or WAMP. The process is straightforward but includes a few Windows-specific quirks.
Step 1: Download Mailpit
Navigate to the Mailpit GitHub Releases page. Download the latest mailpit-windows-amd64.zip file. Unless you are on a very old 32-bit machine, the AMD64 (64-bit) version is what you need.
Tip: Always download from the official GitHub releases page. Third-party download sites may bundle unwanted software or outdated versions.
Step 2: Verify the Download (SHA256)
Security-conscious developers verify file integrity using the SHA256 checksum. This ensures the file was not corrupted during download or tampered with.
On the releases page, each ZIP file has a corresponding .sha256.txt file. Download that too, then verify:
# In PowerShell (run as Administrator is not required)
$expected = Get-Content mailpit-windows-amd64.zip.sha256.txt
$actual = (Get-FileHash mailpit-windows-amd64.zip -Algorithm SHA256).Hash
if ($expected -eq $actual) { Write-Host "Checksum matches. File is valid." -ForegroundColor Green }
else { Write-Host "Checksum MISMATCH. Do not use this file." -ForegroundColor Red }
If the checksums match, you know the file is exactly what the developer published. If they do not match, delete the file and re-download.
Step 3: Extract and Organize
Extract the ZIP to a permanent location. I recommend a dedicated tools folder:
D:\Tools\Mailpit └── mailpit.exe
Avoid extracting to Downloads or the Desktop. Those locations get cluttered, and you might accidentally delete the file.
Step 4: Add to PATH (Optional but Recommended)
Adding Mailpit to your PATH lets you run it from any terminal window without typing the full path.
- Press Win + S, search for “Environment Variables,” and select Edit the system environment variables.
- Click Environment Variables.
- Under User variables, find Path and click Edit.
- Click New and add
D:\Tools\Mailpit\(or your actual path). - Click OK on all dialogs.
- Open a new PowerShell or Command Prompt window and type
mailpit --versionto confirm.
Step 5: Understanding Windows Security Warnings
The first time you run mailpit.exe, Windows Defender SmartScreen may display a warning: “Windows protected your PC” or “Unknown Publisher.”
This happens because Mailpit is open-source software that is not digitally signed with an expensive code-signing certificate. It is not malware. It is simply that Windows cannot verify the publisher’s identity.
To proceed:
- Click More info on the SmartScreen dialog.
- Click Run anyway.
If your organization blocks unsigned executables, you may need to whitelist mailpit.exe in your antivirus or group policy.
Developer Note: Code-signing certificates cost hundreds of dollars annually. Many open-source projects skip them to keep costs low. Always verify the SHA256 checksum from the official release page as your trust anchor.
Step 6: Run Mailpit
Open PowerShell or Command Prompt and type:
mailpit
You should see output similar to this:
INFO[2026/07/14 08:00:00] SMTP server listening on :1025
INFO[2026/07/14 08:00:00] HTTP server listening on :8025
Open your browser and navigate to http://localhost:8025. You will see the Mailpit inbox, empty and ready.
Common Mistake: Do not double-click mailpit.exe from File Explorer. It will open and immediately close because it runs as a console application. Always launch it from a terminal (PowerShell or Command Prompt) so you can see the output and stop it with Ctrl + C.
Persistent Database
By default, Mailpit stores emails in memory. When you close the terminal, they are gone. For persistent storage across restarts:
mailpit -d D:\Mailpit\mailpit.db
Create the D:\Mailpit\ folder first. Now every email survives a reboot.
Custom Ports
If port 1025 or 8025 is already in use:
mailpit --smtp 2525 --listen 127.0.0.1:8080
Then configure your application to use SMTP port 2525 and open http://127.0.0.1:8080 for the web UI.
Auto-Start with Windows
Use Windows Task Scheduler to start Mailpit automatically:
- Open Task Scheduler and click Create Task.
- On the General tab, name it “Mailpit Auto-Start.”
- Check Run whether user is logged on or not.
- On the Triggers tab, click New and select At logon.
- On the Actions tab, click New:
- Program:
D:\Tools\Mailpit\mailpit.exe - Arguments:
-d D:\Mailpit\mailpit.db
- Program:
- Click OK and enter your password when prompted.
6.2 macOS Installation
macOS users have two paths: Homebrew for convenience, or manual binary installation for control.
Option A: Homebrew (Recommended)
# Install
brew install mailpit
# Run
mailpit
# Verify
mailpit --version
Option B: Manual Binary
# Download from GitHub releases
# Extract to /usr/local/bin or ~/bin
# Make executable
chmod +x ~/bin/mailpit
# Add to PATH (if using ~/bin)
echo 'export PATH="$HOME/bin:$PATH"' >> ~/.zshrc
source ~/.zshrc
Auto-Start with macOS
Create a LaunchAgent plist file:
# ~/Library/LaunchAgents/com.mailpit.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.mailpit</string>
<key>ProgramArguments</key>
<array>
<string>/usr/local/bin/mailpit</string>
<string>-d</string>
<string>/Users/yourname/Mailpit/mailpit.db</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>StandardOutPath</key>
<string>/Users/yourname/Mailpit/mailpit.log</string>
<key>StandardErrorPath</key>
<string>/Users/yourname/Mailpit/mailpit.error.log</string>
</dict>
</plist>
Then load it:
launchctl load ~/Library/LaunchAgents/com.mailpit.plist
launchctl start com.mailpit
6.3 Linux Installation
Linux users benefit from the install script, which handles architecture detection automatically.
Option A: Install Script
# Download and run the official installer
curl -sL https://raw.githubusercontent.com/axllent/mailpit/develop/install.sh | bash
# The script places mailpit in /usr/local/bin/
mailpit --version
Option B: Manual Binary
# Download the appropriate binary for your architecture
# Common: linux-amd64, linux-arm64
wget https://github.com/axllent/mailpit/releases/download/v1.x.x/mailpit-linux-amd64.tar.gz
# Extract
sudo tar -xzf mailpit-linux-amd64.tar.gz -C /usr/local/bin/
sudo chmod +x /usr/local/bin/mailpit
Option C: Package Managers
Some distributions package Mailpit:
# Arch Linux (AUR)
yay -S mailpit
# NixOS
nix-env -iA nixpkgs.mailpit
Systemd Service
For persistent background operation on Linux:
# /etc/systemd/system/mailpit.service
[Unit]
Description=Mailpit Email Testing Server
After=network.target
[Service]
Type=simple
ExecStart=/usr/local/bin/mailpit -d /var/lib/mailpit/mailpit.db
Restart=always
RestartSec=5
User=mailpit
Group=mailpit
[Install]
WantedBy=multi-user.target
# Create user and directory
sudo useradd -r -s /bin/false mailpit
sudo mkdir -p /var/lib/mailpit
sudo chown mailpit:mailpit /var/lib/mailpit
# Enable and start
sudo systemctl daemon-reload
sudo systemctl enable mailpit
sudo systemctl start mailpit
sudo systemctl status mailpit
6.4 Docker Installation
Docker is the cleanest option for teams or CI/CD pipelines. The official image is axllent/mailpit.
Docker Run
docker run -d --name mailpit -p 1025:1025 -p 8025:8025 -v mailpit-data:/data axllent/mailpit
Docker Compose
# docker-compose.yml
version: "3.8"
services:
mailpit:
image: axllent/mailpit
container_name: mailpit
ports:
- "1025:1025"
- "8025:8025"
volumes:
- mailpit-data:/data
environment:
- MP_DATA_FILE=/data/mailpit.db
restart: unless-stopped
volumes:
mailpit-data:
docker-compose up -d
From your application container, connect to mailpit:1025 (the service name) instead of 127.0.0.1:1025.
6.5 Build From Source
Building from source is rarely necessary. Use it only if you need a custom build or are contributing to the project.
git clone https://github.com/axllent/mailpit.git
cd mailpit
go build -o mailpit
Requires Go 1.21 or later.
Configuration
Mailpit is designed to work out of the box with zero configuration. But as your needs grow, you will want to customize ports, storage, and behavior. Here are the most common options.
Command Line Arguments
| Flag | Description | Example |
|---|---|---|
--smtp |
SMTP listen address and port | --smtp 127.0.0.1:2525 |
--listen |
HTTP UI listen address and port | --listen 127.0.0.1:8080 |
-d |
Database file path (persistent storage) | -d /data/mailpit.db |
--max |
Maximum number of messages to store | --max 500 |
--webroot |
Web UI root path | --webroot /mailpit |
--auth-file |
HTTP Basic Auth file | --auth-file /etc/mailpit/auth |
--tls-cert |
TLS certificate file | --tls-cert cert.pem |
--tls-key |
TLS private key file | --tls-key key.pem |
Environment Variables
Every command-line flag has an equivalent environment variable prefixed with MP_:
MP_SMTP=127.0.0.1:2525
MP_LISTEN=127.0.0.1:8080
MP_DATABASE=/data/mailpit.db
MP_MAX=500
Persistent Database
By default, Mailpit stores emails in memory. When you close Mailpit, they are gone. For persistent storage across restarts:
# Windows
mailpit -d D:\Mailpit\mailpit.db
# macOS / Linux
mailpit -d ~/.mailpit/mailpit.db
# Docker (set via environment variable)
MP_DATABASE=/data/mailpit.db
Recommended Folder Structure
For a development machine that hosts multiple local projects, a clean setup is:
D:\
├── Tools\
│ └── Mailpit\
│ └── mailpit.exe
├── Mailpit\
│ └── mailpit.db
└── Projects\
├── Project1
├── Project2
└── Project3
With this setup, you start Mailpit once and every local project can use the same SMTP endpoint (127.0.0.1:1025), while all captured emails are available in one inbox at http://localhost:8025. This is a good fit if you want a single local mail server shared across all development projects.
Running Mailpit
Command Prompt & PowerShell (Windows)
# Basic start
mailpit
# With persistent database
mailpit -d D:\Mailpit\mailpit.db
# Custom ports
mailpit --smtp 2525 --listen 127.0.0.1:8080
# Background all output to a log file
mailpit -d D:\Mailpit\mailpit.db > D:\Mailpit\mailpit.log 2>&1
Terminal (macOS & Linux)
# Basic start
mailpit
# With persistent database
mailpit -d ~/.mailpit/mailpit.db
# Custom ports
mailpit --smtp 127.0.0.1:2525 --listen 127.0.0.1:8080
# Background process
nohup mailpit -d ~/.mailpit/mailpit.db > ~/.mailpit/mailpit.log 2>&1 &
Windows Task Scheduler (Auto-Start)
To start Mailpit automatically when Windows boots:
- Open Task Scheduler (search in Start menu)
- Click Create Task
- General tab: Name it “Mailpit”, check “Run whether user is logged on or not”
- Triggers tab: New → At logon → OK
- Actions tab: New → Start a program
- Program:
D:\Tools\Mailpit\mailpit.exe - Arguments:
-d D:\Mailpit\mailpit.db
- Program:
- Click OK and enter your password
Linux systemd (Already Covered in Section 6.3)
Refer to the systemd service file example above for production-like Linux deployments.
macOS LaunchAgent (Already Covered in Section 6.2)
Refer to the LaunchAgent plist example above for macOS auto-start.
Understanding Ports
Mailpit uses two ports by default. Understanding what each does prevents confusion when configuring your applications.
| Port | Purpose | Protocol | Used By |
|---|---|---|---|
| 1025 | SMTP server | SMTP | Your application sends emails here |
| 8025 | Web UI | HTTP | Your browser views captured emails here |
Port 1025 is used for SMTP communication — the same protocol Gmail, SendGrid, and every other email provider use. Your application connects to 127.0.0.1:1025 and sends email exactly as it would to any SMTP server. The difference is that Mailpit captures the message instead of relaying it.
Port 8025 is used for the web interface — the inbox you open in your browser. This is where you read, inspect, and manage captured emails.
Why Port 1025 Instead of 25?
Port 25 is the standard SMTP port, but it requires administrative privileges on most systems and is frequently blocked by ISPs and firewalls. Port 1025 is unprivileged (any user can bind to it) and avoids conflicts. You can change it if needed:
mailpit --smtp 2525
Firewall Considerations
Since Mailpit is a development tool, it should only listen on 127.0.0.1 (localhost). Never expose Mailpit’s SMTP or web UI to the public internet without authentication. If you need remote access, use a reverse proxy with SSL and basic auth.
Using Mailpit with WordPress & LocalWP
WordPress does not send email natively via SMTP. It uses PHP’s mail() function by default, which on most local development stacks is either disabled or unreliable. An SMTP plugin bridges the gap.
Recommended SMTP Plugins
Any of these plugins work with Mailpit:
- WP Mail SMTP — Most popular, comprehensive settings
- FluentSMTP — Modern, lightweight, multiple providers
- Post SMTP — Advanced logging and debugging
- Easy WP SMTP — Simple, no-frills configuration
SMTP Configuration for Mailpit
| Setting | Value |
|---|---|
| Mailer | Other SMTP |
| SMTP Host | 127.0.0.1 |
| SMTP Port | 1025 |
| Encryption | None |
| Authentication | Off / Disabled |
| Username | Leave empty |
| Password | Leave empty |
Tip: Do not use SSL or TLS when connecting to Mailpit. It does not support encrypted connections by default, and your SMTP plugin will fail to connect if you force TLS.
Testing with WP Mail SMTP
- Install and activate WP Mail SMTP
- Go to WP Mail SMTP → Settings
- Select Other SMTP as the mailer
- Enter
127.0.0.1as the SMTP Host and1025as the port - Set Encryption to None
- Turn Authentication off
- Save settings
- Go to WP Mail SMTP → Tools → Email Test
- Send a test email and check Mailpit at
http://localhost:8025
LocalWP Workflow
LocalWP is a popular WordPress development environment. Here is the complete workflow:
- Start LocalWP and your site.
- Start Mailpit (
mailpitin PowerShell). - Open
http://localhost:8025in your browser. - Install an SMTP plugin in your LocalWP site.
- Configure the plugin with
127.0.0.1:1025, no encryption, no auth. - Trigger an email (password reset, new user, contact form).
- Watch it appear instantly in the Mailpit inbox.
Real-World WordPress Email Scenarios
Here are the most common WordPress email scenarios you should test with Mailpit:
- Password reset: Click “Lost your password?” on the login page.
- New user registration: Create a new user from the admin panel.
- Contact form: Submit a form using Contact Form 7, WPForms, or Gravity Forms.
- WooCommerce order: Place a test order and check the confirmation email.
- Comment notification: Post a comment and check the moderation email.
- Plugin notifications: Trigger any plugin that sends email (membership, LMS, etc.).
Using Mailpit with PHP & PHPMailer
PHP mail() Function
PHP’s built-in mail() function does not use SMTP directly. It delegates to the system’s sendmail binary. To route mail() through Mailpit, you need to configure PHP’s sendmail_path in php.ini:
; php.ini
sendmail_path = "D:\Tools\Mailpit\mailpit.exe sendmail"
Then in your PHP code:
<?php
mail('[email protected]', 'Hello from PHP', 'This is a test email sent via Mailpit.');
The email will appear in the Mailpit inbox.
PHPMailer
PHPMailer is the most popular PHP email library. It gives you full SMTP control:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
$mail->isSMTP();
$mail->Host = '127.0.0.1';
$mail->Port = 1025;
$mail->SMTPAuth = false;
$mail->SMTPSecure = false;
$mail->setFrom('[email protected]', 'Developer');
$mail->addAddress('[email protected]', 'Test User');
$mail->Subject = 'Test Email via Mailpit';
$mail->Body = '<h1>Hello World</h1><p>This is an HTML email.</p>';
$mail->AltBody = 'This is the plain text version.';
$mail->send();
echo 'Email captured by Mailpit. Check http://localhost:8025';
} catch (Exception $e) {
echo "Failed: {$mail->ErrorInfo}";
}
Using Mailpit with Laravel
Laravel has excellent built-in mail support. Configuring it for Mailpit takes two minutes.
Configuration
Edit your .env file:
MAIL_MAILER=smtp
MAIL_HOST=127.0.0.1
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="[email protected]"
MAIL_FROM_NAME="${APP_NAME}"
Then clear the config cache:
php artisan config:clear
Sending a Test Email
// routes/web.php or a controller
use Illuminate\Support\Facades\Mail;
use App\Mail\TestEmail;
Route::get('/test-email', function () {
Mail::to('[email protected]')->send(new TestEmail());
return 'Email sent. Check Mailpit at http://localhost:8025';
});
Mailable Class
// app/Mail/TestEmail.php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class TestEmail extends Mailable
{
use Queueable, SerializesModels;
public function build()
{
return $this->subject('Laravel Test via Mailpit')
->view('emails.test');
}
}
Blade Template
<!-- resources/views/emails/test.blade.php -->
<!DOCTYPE html>
<html>
<head><title>Test</title></head>
<body>
<h1>Hello from Laravel</h1>
<p>This email was captured by Mailpit.</p>
</body>
</html>
Using Mailpit with Node.js
Node.js applications typically use the nodemailer package for SMTP. It works seamlessly with Mailpit.
Installation
npm install nodemailer
Configuration
const nodemailer = require('nodemailer');
const transporter = nodemailer.createTransport({
host: '127.0.0.1',
port: 1025,
secure: false, // No TLS
auth: null // No authentication
});
async function sendTestEmail() {
const info = await transporter.sendMail({
from: '"Developer" <[email protected]>',
to: '[email protected]',
subject: 'Node.js Test via Mailpit',
text: 'This is the plain text body.',
html: '<h1>Hello from Node.js</h1><p>This is an HTML email.</p>'
});
console.log('Message captured by Mailpit:', info.messageId);
}
sendTestEmail().catch(console.error);
Express.js Route Example
const express = require('express');
const nodemailer = require('nodemailer');
const app = express();
const transporter = nodemailer.createTransport({
host: '127.0.0.1',
port: 1025,
secure: false
});
app.get('/send-email', async (req, res) => {
await transporter.sendMail({
from: '[email protected]',
to: '[email protected]',
subject: 'Express Test',
html: '<p>Email sent from Express!</p>'
});
res.send('Email captured. Check Mailpit.');
});
app.listen(3000, () => console.log('Server running on http://localhost:3000'));
Using Mailpit with Python
Python’s smtplib module is part of the standard library. No external dependencies needed.
Plain Python (smtplib)
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
msg = MIMEMultipart('alternative')
msg['Subject'] = 'Python Test via Mailpit'
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
html = '<html><body><h1>Hello from Python</h1></body></html>'
text = 'Hello from Python (plain text)'
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
msg.attach(part1)
msg.attach(part2)
with smtplib.SMTP('127.0.0.1', 1025) as server:
server.send_message(msg)
print('Email captured by Mailpit. Check http://localhost:8025')
Django Configuration
In your settings.py:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = '127.0.0.1'
EMAIL_PORT = 1025
EMAIL_USE_TLS = False
EMAIL_USE_SSL = False
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
DEFAULT_FROM_EMAIL = 'webmaster@localhost'
Then send a test email:
from django.core.mail import send_mail
send_mail(
'Django Test via Mailpit',
'This is a test email from Django.',
'[email protected]',
['[email protected]'],
fail_silently=False,
)
Flask Example
from flask import Flask
from flask_mail import Mail, Message
app = Flask(__name__)
app.config['MAIL_SERVER'] = '127.0.0.1'
app.config['MAIL_PORT'] = 1025
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = False
app.config['MAIL_USERNAME'] = None
app.config['MAIL_PASSWORD'] = None
mail = Mail(app)
@app.route('/send')
def send_email():
msg = Message('Flask Test via Mailpit',
sender='[email protected]',
recipients=['[email protected]'])
msg.body = 'Plain text body'
msg.html = '<h1>Hello from Flask</h1>'
mail.send(msg)
return 'Email sent. Check Mailpit.'