使用外部smtp从容器发送邮件

时间:2017-02-14 09:37:58

标签: email docker smtp

我准备了一个可以通过smtp.gmail.com发送邮件的应用程序,但效果很好但是,当我使用docker运行它时,我收到错误 - 因为它无法连接到smtp.gmail.com。发送邮件的功能是:

public void sendEmal(String body, String mailRecipient){
   Properties props = new Properties();
   props.put("mail.transport.protocol", "smtp");
   props.put("mail.smtp.auth", "true");
   props.put("mail.smtp.host", "smtp.gmail.com");
   props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
   props.put("mail.smtp.port", "465");
   try{
        Authenticator auth = new SMTPAuthenticator();
        Session mailSession = Session.getDefaultInstance(props, auth);
        mailSession.setDebug(true);
        Transport transport = mailSession.getTransport();

        MimeMessage message = new MimeMessage(mailSession);
        message.setContent(body, "text/plain");
        message.addRecipient(Message.RecipientType.TO,
        new InternetAddress("mailRecipient"));

        transport.connect();
        transport.sendMessage(message,
        message.getRecipients(Message.RecipientType.TO));
        transport.close();  
    }
    catch(Exception e){
        System.out.println(e);
    }
}

这是错误:

  

myapp_thirdInst | DEBUG SMTP:尝试连接到主机   “smtp.gmail.com”,端口465,是SSL错误

     

myapp_thirdInst | javax.mail.MessagingException:未知的SMTP主机:   smtp.gmail.com;

     

myapp_thirdInst |嵌套异常是:

     

myapp_thirdInst | java.net.UnknownHostException:smtp.gmail.com

     

myapp_thirdInst |发送邮件时出错

这是我第一次玩Docker,经过一些尝试,它仍然会失败。我有点迷茫 - 有人能给我一些提示来解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

您需要做的第一件事就是让DNS工作!首先使用shell测试容器DNS,使其正常工作,然后您的SMTP代码可以正常工作。

也许您可以使用有关DNS配置的信息更新您的问题

相关问题