javax.mail不想从Web应用程序发送邮件,但从控制台应用程序发送邮件

时间:2019-03-07 11:37:20

标签: java javamail java-ee-7 glassfish-4

首先,我使用glassfish4服务器。当我尝试从网络测试应用发送电子邮件时,出现异常,通常显示为:

  

javax.mail.MessagingException:无法连接到SMTP主机:   mail.host.com,端口:465,响应:-1

(我也有另一个例外,但我不记得他们了),但是从我的SE应用程序中,它每次都正确发送电子邮件。另外,我的同事在他的计算机上具有与我相同的代码,并且该代码有效。我还尝试通过smtp.gmail.com发送电子邮件,它的工作原理类似于魅力,但是当我尝试使用我们的专用服务器时,它不起作用。

这是我的网络应用程序中的代码:

    @WebServlet("/email")
public class Email extends HttpServlet{
    private static final String SUBJECT = "TEST";
    private static final String CONTENT = "<h1>HI</h1>"
            + "<header style='width: 100%; height=20vh; background: #ffdd1a; color: #383e72;'>"
            + "<h1>TEST</h1>"
            + "<h2>KTHXBYE</h2>"
            + "</header>";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name"),
               eMail = req.getParameter("eMail"),
               server = req.getParameter("server"),
               port = req.getParameter("port"),
               encryption = req.getParameter("encryption"),
               mailTo = req.getParameter("mailTo");
        final String username = req.getParameter("username"),
                     pass = req.getParameter("pass");
        resp.setCharacterEncoding("UTF-8");
        Session session;

        // setup acc props
        Properties props = System.getProperties();
        props.put("mail.smtp.host", server);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", "true");
        props.put("mail.transport.protocol", "smtp");

        switch (povezava) {
            case "SSL":
                props.put("mail.smtp.socketFactory.port", "port");
                props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                break;
            case "TLS":
                props.put("mail.smtp.starttls.enable", "true");
                break;
            case "NONE":
                props.put("mail.smtp.ssl.enable", "false");
                props.put("mail.smtp.starttls.enable", "false");
                props.put("mail.smtp.ssl.trust", server);
                break;
            default:
                resp.getWriter().print("ERROR");
                return;
        }

        Authenticator auth = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, pass);
            }
        };

        // create msg
        session = Session.getDefaultInstance(props, auth);
        session.setDebug(true);

        MimeMessage message = new MimeMessage(session);
        try {
            try {
                message.setFrom(new InternetAddress(eMail, name));
                message.setSubject(SUBJECT);
                MimeMultipart multipart = new MimeMultipart("related");
                BodyPart bodyPart = new MimeBodyPart();
                bodyPart.setContent(CONTENT, "text/html; charset=utf-8");
                multipart.addBodyPart(bodyPart);
                message.setContent(multipart);
                // send msg
                message.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
//                Transport transport = session.getTransport("smtp");
//                transport.connect(server, username, pass);
//                transport.sendMessage(message, message.getAllRecipients());
                Transport.send(message);
                resp.getWriter().print("Mail was send successfully");
                return;
            } catch (MessagingException ex) {
                Logger.getLogger(Email.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(Email.class.getName()).log(Level.SEVERE, null, ex);
        }
        resp.getWriter().print("Sending mail failed");
    }
}

上层代码的堆栈跟踪:

javax.mail.MessagingException: Could not connect to SMTP host: mail.host.com, port: 465, response: -1
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2042)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:697)
    at javax.mail.Service.connect(Service.java:386)
    at javax.mail.Service.connect(Service.java:245)
    at javax.mail.Service.connect(Service.java:194)
    at javax.mail.Transport.send0(Transport.java:253)
    at javax.mail.Transport.send(Transport.java:124)
    at com.zarja.testmail.Email.doPost(Email.java:113)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
    at java.lang.Thread.run(Thread.java:748)

现在我的SE应用程序代码:

public static void main(String[] args) {
        System.out.println(sendMyMail());
    }

    public static String sendMyMail() {
        try {
            String from = "mailaddress"; // not actual mail
            String pass = "password";
            Authenticator auth = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(from, pass);
                }
            };

            Session session;
            //setup account properties
            Properties props = System.getProperties();
            props.put("mail.smtp.host", "mail.host.com");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class",
                    "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465");

            session = Session.getDefaultInstance(props, auth);
            session.setDebug(true);
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from, "TEST"));
            message.setSubject(SUBJECT);
            MimeMultipart multipart = new MimeMultipart("related");
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setContent(CONTENT, "text/html; charset=utf-8");
            multipart.addBodyPart(messageBodyPart);
            message.setContent(multipart);
            //send message
            try {
                message.setRecipient(Message.RecipientType.TO, new InternetAddress("host@gmail.com"));
    //                Transport transport = session.getTransport("smtp");
    //                    transport.connect("mail.host.com", from, pass);
    //                    transport.sendMessage(message, message.get

AllRecipients());
                    Transport .send(message);
                    return "SENT";
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "FAILED";
        }

谢谢您的帮助!

编辑(代码的外观)

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name"),
               eMail = req.getParameter("eMail"),
               server = req.getParameter("server"),
               port = req.getParameter("port"),
               encryption = req.getParameter("encryption"),
               mailTo = req.getParameter("mailTo");
        final String username = req.getParameter("username"),
                     pass = req.getParameter("pass");
        resp.setCharacterEncoding("UTF-8");
        Session session;

        // setup acc props
        Properties props = System.getProperties();
        props.put("mail.smtp.host", server);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", "true");
        props.put("mail.transport.protocol", "imap");

        switch (enryption) {
            case "SSL":
                props.put("mail.smtp.ssl.enable", "true");
                break;
            case "TLS":
                props.put("mail.smtp.starttls.enable", "true");
                break;
            case "NONE":
                props.put("mail.smtp.ssl.enable", "false");
                props.put("mail.smtp.starttls.enable", "false");
                props.put("mail.smtp.ssl.trust", server);
                break;
            default:
                resp.getWriter().print("ERROR");
                return;
        }

        // create msg
        session = Session.getInstance(props);
        session.setDebug(true);

        MimeMessage message = new MimeMessage(session);
        try {
            try {
                message.setFrom(new InternetAddress(eMail, name));
                message.setSubject(SUBJECT);
                MimeMultipart multipart = new MimeMultipart("related");
                BodyPart bodyPart = new MimeBodyPart();
                bodyPart.setContent(CONTENT, "text/html; charset=utf-8");
                multipart.addBodyPart(bodyPart);
                message.setContent(multipart);
                // send msg
                message.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTp));
                Transport transport = session.getTransport("imap");
                transport.connect(streznikPoste, uporabniskoIme, geslo);

                Transport.send(message);
                resp.getWriter().print("Mail was send successfully");
                return;
            } catch (MessagingException ex) {
                Logger.getLogger(Email.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(Email.class.getName()).log(Level.SEVERE, null, ex);
        }
        resp.getWriter().print("Sending mail failed");
    }

编辑修复(似乎可行):

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name"),
               eMail = req.getParameter("eMail"),
               server = req.getParameter("server"),
               port = req.getParameter("port"),
               encryption = req.getParameter("encryption"),
               mailTo = req.getParameter("mailTo");
        final String username = req.getParameter("username"),
                     pass = req.getParameter("pass");
        resp.setCharacterEncoding("UTF-8");
        Session session;

        // setup acc props
        Properties props = System.getProperties();
        props.put("mail.smtp.host", server);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", "true");
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.ssl.trust", server);

        switch (encryption) {
            case "SSL":
                props.put("mail.smtp.ssl.enable", "true");
                break;
            case "TLS":
                props.put("mail.smtp.starttls.enable", "true");
                break;
            case "NONE":
                props.put("mail.smtp.ssl.enable", "false");
                props.put("mail.smtp.starttls.enable", "false");
                props.put("mail.smtp.ssl.trust", server);
                break;
            default:
                resp.getWriter().print("ERROR");
                return;
        }

        // create msg
        session = Session.getInstance(props);
        session.setDebug(true);

        MimeMessage message = new MimeMessage(session);
        try {
            try {
                message.setFrom(new InternetAddress(eMail, name));
                message.setSubject(SUBJECT);
                MimeMultipart multipart = new MimeMultipart("related");
                BodyPart bodyPart = new MimeBodyPart();
                bodyPart.setContent(CONTENT, "text/html; charset=utf-8");
                multipart.addBodyPart(bodyPart);
                message.setContent(multipart);
                // send msg
                message.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
                Transport transport = session.getTransport();
                transport.connect(server, username, pass);
                Transport.send(message, username, pass);
                resp.getWriter().print("Mail was send successfully");
                return;
            } catch (MessagingException ex) {
                Logger.getLogger(Email.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(Email.class.getName()).log(Level.SEVERE, null, ex);
        }
        resp.getWriter().print("Sending mail failed");
    }

2 个答案:

答案 0 :(得分:2)

一个快速的猜测是代码中的问题在这里:

switch (povezava) {
    case "SSL":
        props.put("mail.smtp.socketFactory.port", "port");

您无需在此处插入端口变量...

如果此后不起作用,您可以尝试删除与“ socketFactory”相关的属性,我认为您不需要它们。

您可以添加:

props.put("mail.smtp.ssl.enable", "true");

答案 1 :(得分:2)

首先,修复所有这些common JavaMail mistakes

如果您可以连接到一个远程服务器,但不能连接到另一台远程服务器,则该服务器的配置错误,或者您的防火墙阻止了连接。 JavaMail常见问题解答包含tips for debugging connection problems