如何从 JSP 发送电子邮件?我有一个错误

How can I send an email from a JSP? I have an error

我正在尝试使用 gmail 从 JSP 发送电子邮件,我在普通的 Java 应用程序(非网络)中测试了我的代码并且运行良好,但我遇到了这个问题 java.lang.NoSuchMethodError: sun.security.ssl.Handshaker.setApplicationProtocols([Ljava/lang/String;)V 当我 运行 JSP 时,这是我的代码

<%
    String result = "failed";
    
    Properties props = new Properties();
    
    String gmailAccount = "mymail@gmail.com";
    String gmailPassword = "mypass";
    String body = "<h1>Hello!</h1>";
    String subject = "Test";
    String to = "destinationmail@gmail.com";
    Session sessionmail;
    props.put("mail.smtp.host", "smtp.gmail.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");

    sessionmail = Session.getInstance(props, new javax.mail.Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(gmailAccount, gmailPassword);
        }
    });
    
    try {
        MimeBodyPart a = new MimeBodyPart();
        Multipart multipart = new MimeMultipart();
        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setContent(body, "text/html");
        multipart.addBodyPart(mimeBodyPart);
        Message message = new MimeMessage(sessionmail);
        message.setFrom(new InternetAddress(gmailAccount));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);
        message.setContent(multipart);
        Transport transport = sessionmail.getTransport("smtp");
        transport.connect("smtp.gmail.com", gmailAccount, gmailPassword);
        transport.sendMessage(message, message.getAllRecipients());

        result = "Ok";
    } catch (MessagingException e) {
        result = "failed";
    }
%>

顺便说一下,我使用的是 jdk 1.8.0_251 和 Payara 服务器 5.194(我尝试使用 glassfish,但出现了同样的错误)

如果您的代码在控制台应用程序中运行,但在 Payara 和 Glassfish 中抛出该异常,那么很可能是服务器加载包含不同版本的 JAR 文件引起的问题 class .

This list of errors for Glassfish mentions grizzly-npn-bootstrap.jar. See the third error. Looking for the file in combination with your error 显示了提及相同问题原因的其他结果。

在您的服务器安装中查找该文件并将其重命名为 grizzly-npn-bootstrap.old(或尝试更新版本的服务器),然后重试。