Python is the language that can do it all - including SMTP email! Using the in-built library we can setup outbound email sending in Python to external SMTP servers. Let us demonstrate.

What is SMTP and how does it work?

Firstly, a quick overview of SMTP and how emails work. SMTP (simple mail transfer protocol) describe the sending and receiving of email over TCP - typically on the ports 25, 2525, 465 or 587. Each email address (such as @gmail.com) has an underlying SMTP server that runs on the domain (smtp.gmail.com for instance) and listens for incoming emails. When we wish to email an address provided by the server we can connect via SMTP in Python and submit a message.

Configuring SMTPLib

To use Python to send SMTP emails we first need to import and configure the batteries included library. In a new python file add:

Once imported you can open a new connection like so:

For each email you wish to send you will need to connect to the underlying SMTP server or use your own SMTP server to pass the emails on for you. When using your own SMTP server you will want to create authentication so that only you can send from it.

Using authentication

Say you have created an SMTP server with MailSlurp, you can access the server using your username and password for the account hosted on a domain and port:

ProtocolHostPortTLSDescription
SMTPmx.mailslurp.com2525falseSMTP server

In code you can use the MailSlurp SDK to obtain these details with the method.

SMTP servers provide several authentication methods but and are two common methods.

Sending email content

To send SMTP emails in Python you must construct and email body. The body of an email begins with lines of headers that are key value pairs and then a body separated by a new line. For instance: .

Testing emails with MailSlurp

To test if your Python application is sending emails correctly or to run your own SMTP server try MailSlurp. MailSlurp provides unlimited disposable (or permanent) email mailboxes that can be connected to using Python and SMTP to send emails. Let us use MailSlurp and Pytest to demonstrate:

More information

To read more about SMTP email sending in Python consult the smtplib docs or see the MailSlurp Python developer page.