Proxy to SMTP
SMTP is a protocol used for sending emails. In the simpliest setup, it involves a SMTP client and a SMTP server to send and receive emails.
In a more complicated fashion, it can involves a number of proxies to ensure emails are sent, a number of firewall filters to filter inbound and outbound emails, and a number of exchange servers for setting up mailing lists and groups.
SSH Configuration
Proxying to send emails requires us to setup a forwarding port to send traffic to.
In the configuration below, we have to
- establish a SSH tunnel to the example-network using an SSH key pair (identity file) on port 22.
- setup local port forwarding to a local port 5025 where the traffic going to localhost:5025 will go to smtp.example.com on port 25 via the SSH tunnel.
This section needs an image.
SSH configuration:
Host example-network
HostName 192.168.0.1
User someusername
PasswordAuthentication no
PubkeyAuthentication yes
IdentityFile ~/.ssh/example_network_id_ed25519
IdentitiesOnly yes
Port 22
ServerAliveInterval 10
ServerAliveCountMax 2
Compression yes
TCPKeepAlive yes
GatewayPorts yes
RemoteForward 5020
RemoteForward 5025 smtp.example.com:25
Sending Emails Manually
Test emails can be sent using the smtp protocol using telnet or simple python code without dependencies.
This code below will connect to localhost:5025 using the python smtp library to send an email from email@example.com to email@example.com.
This code will only work with unauthenticated smtp / exchange server.
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
hostname = os.environ.get('host', 'localhost')
port = os.environ.get('port', '5025')
sender_email = os.environ.get('sender_email', 'email@example.com')
receiver_email = os.environ.get('receiver_email', 'email@example.com')
message = MIMEMultipart("alternative")
message["Subject"] = "Welcome Onboard"
message["From"] = sender_email
message["To"] = receiver_email
message["Cc"] = receiver_email
html = """
<html>
<body>
Hello, email from us!
</body>
</html>
"""
part1 = MIMEText(html, "plain")
message.attach(part1)
with smtplib.SMTP(hostname, port) as server:
server.sendmail(
sender_email, receiver_email, message.as_string()
)