Python send mail inside docker container with local SMTP server Python send mail inside docker container with local SMTP server docker docker

Python send mail inside docker container with local SMTP server


The code you shared is SMTP client application. Assuming SMTP client standard library smtplib is used and SMTP server is running on localhost, the code will work in Docker container in the following conditions:

  • You start the container with --net=host, then no changes is needed. calling smtplib.SMTP('localhost') will connect to SMTP server running on the host.
  • You don't start the container with --net=host. Then you need to connect to host.docker.internal instead of localhost if you use Windows or MacOS. If you use Linux, may need to use another trick. Essentially, the code is still connecting to SMTP server running on the host.
  • You package SMTP server and the python stmp client application (code you shared) in the same Docker image. It's bad practice and should be avoided. But you can follow the docs to achieve it.

Please, do share the following to better understand the question:

More specifically:

  • OS you are use. Docker for desktop behaves differently for Mac and Windows, especially in terms of networking features.

  • Dockerfile you use. Otherwise it's impossible to run the image and replicate the issue you are facing and understand what you mean by sendmail service is running in my container.

  • Fully working python code (including imports, etc...) Otherwise, it's not clear what smtplib you use.

  • Links to documentation. If you use standard library smtplib, then its docs doesn't have such description:

sendmail method description has this:

... the message was accepted for delivery to three of the four addresses, and one was rejected, with the error code 550. If alladdresses are accepted, then the method will return an emptydictionary.


By default, the docker containers run in a separate network stack, so localhost does not mean the same thing inside a docker container as it does when your code runs directly on your computer.

Depending on how your SMTP server is set up, it might also be configured to refuse sending any email but those coming directly from your computer, and a docker container might be treated as an outsider that should not be sending an email through it.

I guess the simplest solution would be to run your docker container with --net=host. With this the network stack of the docker container will be the same as the stack of your computer and everything should work as if the code was running directly outside docker.


If it works on host machine, try using the host IP instead of localhost.

s = smtplib.SMTP(HOST_IP)

Or as Arthur suggested, you can run the container in host network with --net=host and then continue using localhost.