Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python send mail inside docker container with local SMTP server

I want to send mail with smtp lib on python. I understand that it uses local smtp service on port number 25. I have below codes. These codes run on my local without any problem and mail sends successfully. But when I move them to docker container, mail is not sent and it doesn't give any error.

My codes:

from_mail = '[email protected]'
to_mail = '[email protected]'

s = smtplib.SMTP('localhost')
subject = 'Test Subject'
content = 'content test'

message = f"""\
      Subject: {subject}
      To: {to_mail}
      From: {from_mail}
      {content}"""
result = s.sendmail(from_mail, to_mail, message)
s.quit()

After running these codes, I get empty dict ({}) as result value. In the 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 all addresses are accepted, then the method will return an empty dictionary.

Is it about network configuration? Should I configure any network settings?

like image 901
kamilyrb Avatar asked Jun 15 '20 09:06

kamilyrb


1 Answers

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 all addresses are accepted, then the method will return an empty dictionary.

like image 130
rok Avatar answered Nov 13 '22 14:11

rok