In the past few days I’ve been working with a code where I needed to see whether the service successfully sends mails through SMTP. I did not want to use or set up an actual mail server locally. As is turns out Python has a oneliner to solve this situation.

Python oneliner

Python by default has a module called smtpd, that you can use to event implement SMTP servers. Though it’s deprecated in favor of aiosmtpd, it’s still useful for my purposes, namely to intercept outgoing messages.

python -m smtpd -n -c DebuggingServer localhost:2500

It’s as simple as this.

Test it out

For testing out that it really works, I used telnet.

telnet localhost 2500
# The lines below should be typed into telnet, WITHOUT the starting `>`
> helo localhost
> mail from:
> rcpt to:
> data
Subject: Integration test email #1

This template is used by integration tests only.
> .
> quit

And the message will appear in stdout of the DebuggingServer.

---------- MESSAGE FOLLOWS ----------
Subject: Integration test email #1

This template is used by integration tests only.
------------ END MESSAGE ------------

Happy coding!

Cover Photo by Ylanite Koppens from Pexels