Search code examples
dockeremailsmtp

Cannot send mail from inside docker container


I have a spring mvc application which I have dockerized. See this link the way I dockerized. Before containerization the ordinary war deployed in tomcat was able to send emails using host smtp.gmail.com and port 587.

My bean definition was like this:

<beans:bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <beans:property name="host" value="smtp.gmail.com" />
    <beans:property name="port" value="587" />
    <beans:property name="username" value="xxxxxx" />
    <beans:property name="password" value="xxxxx" />
    <beans:property name="javaMailProperties">
         <beans:props>
              <beans:prop key="mail.smtp.auth">true</beans:prop>
              <beans:prop key="mail.smtp.starttls.enable">true</beans:prop>
         </beans:props>
    </beans:property>
    </beans:bean>

Now I get this:

    org.springframework.mail.MailSendException: Mail server connection failed; nested exception is javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
  nested exception is:
        java.net.ConnectException: Connection refused (Connection refused). Failed messages: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
  nested exception is:
        java.net.ConnectException: Connection refused (Connection refused); message exception details (1) are:
Failed message 1:
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
  nested exception is:
        java.net.ConnectException: Connection refused (Connection refused)
        at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1282)

Solution

  • Looking at the link you've provided and assuming that is exactly what you copied for your Dockerfile you'll need to expose an additional port for your mail client.

    If you don't already know, by default, when you create a container, it does not publish any of its ports to the outside world.

    In Dockerfiles you can use EXPOSE. In your case you'll need EXPOSE 587 to enable communication for SMTP

    Additionally, in the future if you need to expose other ports with different protocols you can use

    EXPOSE 587/tcp (tcp is default)

    If you want to read up more on EXPOSE I got my information from Docker Docs: https://docs.docker.com/engine/reference/builder/