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

javax.mail does not want to send my mail from my web application but it send mail from my console app

首先我使用glassfish4服务器。当我尝试从我的网络测试应用程序发送电子邮件时,我收到一个异常,通常显示:

javax.mail.MessagingException: Could not connect to SMTP host: mail.host.com, port: 465, response: -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.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.access0(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");
    }

快速猜测您的代码中的问题在于:

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

您不要在此处插入端口变量...

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

相反,您可以添加:

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

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

如果您可以连接到一个远程服务器但不能连接到另一个远程服务器,则您对该服务器的配置有误,或者您的防火墙阻止了连接。 JavaMail FAQ 有 tips for debugging connection problems.