当前位置: 首页 > 知识库问答 >
问题:

使用Java Netbeans发送电子邮件(例外)

司马宏茂
2023-03-14
(javax.net.ssl.SSLException: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty)
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title> Java Mail </title>
</head>
<body>
    <form action="sendMail.jsp" method="POST">
        <table border="0" align="center" cellpadding="5">
            <tbody>
                <thead><tr> <td colspan="3" align="center">
                <b> Send Mail </b> </td> </tr> </thead>
                <tr>
                    <td> To </td> <td> : </td>
                    <td> <input type="text" name="to" value="" /> </td>
                </tr>
                <tr>
                    <td> Subject </td> <td> : </td>
                    <td> <input type="text" name="subject" value="" /> </td>
                </tr>
                <tr>
                    <td> Message </td> <td> : </td>
                    <td> <textarea name="message" rows="8" cols="30">
                    </textarea></td>
                </tr>
                <tr>
                    <td colspan="3" align="center">
                    <input type="submit" value="Send Mail" />

                    <input type="reset" value="Reset" />
                    <td>
                </tr>
            </tbody>
        </table>
    </form>
</body>
</html>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=">
    <jsp:useBean id="mail" scope="session" class="jMail.Mail" />
    <jsp:setProperty name="mail" property="to" param="to" />
    <jsp:setProperty name="mail" property="from" value="MyEmail@gmail.com" />
    <jsp:setProperty name="mail" property="smtpServ" value="smtp.gmail.com" />
    <jsp:setProperty name="mail" property="subject" param="subject" />
    <jsp:setProperty name="mail" property="message" param="message" />
</head>
<body>
    <%
        String to = mail.getTo();
        int result;
        result = mail.sendMail();
        if (result == 0) {
            out.println(" Mail Successfully Sent to " + to);
        } else {
            out.println(" Mail NOT Sent to " + to);
        }
    %>
</body>
</html>
package jMail;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class Mail {
private String to;
private String from;
private String message;
private String subject;
private String smtpServ;

/**
 * @return the to
 */
public String getTo() {
    return to;
}

/**
 * @param to the to to set
 */
public void setTo(String to) {
    this.to = to;
}

/**
 * @return the from
 */
public String getFrom() {
    return from;
}

/**
 * @param from the from to set
 */
public void setFrom(String from) {
    this.from = from;
}

/**
 * @return the message
 */
public String getMessage() {
    return message;
}

/**
 * @param message the message to set
 */
public void setMessage(String message) {
    this.message = message;
}

/**
 * @return the subject
 */
public String getSubject() {
    return subject;
}

/**
 * @param subject the subject to set
 */
public void setSubject(String subject) {
    this.subject = subject;
}

/**
 * @return the smtpServ
 */
public String getSmtpServ() {
    return smtpServ;
}

/**
 * @param smtpServ the smtpServ to set
 */
public void setSmtpServ(String smtpServ) {
    this.smtpServ = smtpServ;
}


public int sendMail(){
    try
    {
        Properties props = System.getProperties();
          // -- Attaching to default Session, or we could start a new one --
          props.put("mail.transport.protocol", "smtp" );
          props.put("mail.smtp.starttls.enable","true" );
          props.put("mail.smtp.host",smtpServ);
          props.put("mail.smtp.auth", "true" );
          Authenticator auth = new SMTPAuthenticator();
          Session session = Session.getInstance(props, auth);
          // -- Create a new message --
          Message msg = new MimeMessage(session);
          // -- Set the FROM and TO fields --
          msg.setFrom(new InternetAddress(from));
          msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to,     false));
          msg.setSubject(subject);
          msg.setText(message);
          // -- Set some other header information --
          msg.setHeader("MyMail", "Mr. XYZ" );
          msg.setSentDate(new Date());
          // -- Send the message --
          Transport.send(msg);
          System.out.println("Message sent to"+to+" OK." );
          return 0;
    }
    catch (Exception ex)
    {
      ex.printStackTrace();
      System.out.println("Exception "+ex);
      return -1;
    }
}



private class SMTPAuthenticator extends javax.mail.Authenticator {
    @Override
    public PasswordAuthentication getPasswordAuthentication() {
        String username =  "MyEmail@gmail.com";           
        String password = "MyPassword";
        return new PasswordAuthentication(username, password);
    }
  }

}

请帮帮我,我总是有运行时异常:

异常javax.mail.MessagingException:无法将套接字转换为TLS;嵌套异常为:javax.net.ssl.sslexception:java.lang.runtimeException:意外错误:java.security.InvalidAlgorithmParameterException:trustAnchors参数必须为非空

共有1个答案

梁丘赞
2023-03-14

这是我的代码,

import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class SendMail {
     public static int Send(String SMTPServer,
                        String Sender,
                        String Recipient,
                        String Subject,
                        String Body,
                        String ErrorMessage,
                        String Attachments) {
    // Error status;
    int ErrorStatus = 0;

    // Create some properties and get the default Session;
    final String username = Sender;
    final String password = "pswd";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    Session session = Session.getInstance(props,
      new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
      });

    try {
       // Create a message.
       MimeMessage msg = new MimeMessage(session);

       // extracts the senders and adds them to the message.
       // Sender is a comma-separated list of e-mail addresses as per RFC822.
       {
          InternetAddress[] TheAddresses = InternetAddress.parse(Sender);
          msg.addFrom(TheAddresses);
       }

       // Extract the recipients and assign them to the message.
       // Recipient is a comma-separated list of e-mail addresses as per RFC822.
       {
          InternetAddress[] TheAddresses = InternetAddress.parse(Recipient);
          msg.addRecipients(Message.RecipientType.TO,TheAddresses);
       }

       // Subject field
       msg.setSubject(Subject);

       // Create the Multipart to be added the parts to
       Multipart mp = new MimeMultipart();

       // Create and fill the first message part
       {
          MimeBodyPart mbp = new MimeBodyPart();
          mbp.setText(Body);

          // Attach the part to the multipart;
          mp.addBodyPart(mbp);
       }

       // Attach the files to the message
       if (null != Attachments) {
          int StartIndex = 0, PosIndex = 0;
          while (-1 != (PosIndex = Attachments.indexOf("///",StartIndex))) {
             // Create and fill other message parts;
             MimeBodyPart mbp = new MimeBodyPart();
             FileDataSource fds =
             new FileDataSource(Attachments.substring(StartIndex,PosIndex));
             mbp.setDataHandler(new DataHandler(fds));
             mbp.setFileName(fds.getName());
             mp.addBodyPart(mbp);
             PosIndex += 3;
             StartIndex = PosIndex;
          }
          // Last, or only, attachment file;
          if (StartIndex < Attachments.length()) {
             MimeBodyPart mbp = new MimeBodyPart();
             FileDataSource fds = new FileDataSource(Attachments.substring(StartIndex));
             mbp.setDataHandler(new DataHandler(fds));
             mbp.setFileName(fds.getName());
             mp.addBodyPart(mbp);
          }
       }

       // Add the Multipart to the message
       msg.setContent(mp);

       // Set the Date: header
       msg.setSentDate(new Date());

       // Send the message;
       Transport.send(msg);
    } catch (MessagingException MsgException) {
        System.out.println("blows here");
        ErrorMessage = MsgException.toString();
        Exception TheException = null;
        if ((TheException = MsgException.getNextException()) != null)
         ErrorMessage += "\n" + TheException.toString();
         ErrorStatus = 1;
    }
    System.out.println(ErrorMessage);
    return ErrorStatus;
 } // End Send method

    public static void main(String args[]){
        SendMail.Send("smtp.gmail.com", "my_mail@gmail.com", "my_mail@gmail.com",
                 "try sending mail", "came? ","" ,null); 
    }


 } // End of public class SendMail

缩进的事很抱歉

现在试试。希望它能起作用

 类似资料:
  • 问题内容: 如何使用curl命令行程序从gmail帐户发送电子邮件? 我尝试了以下方法: 使用file.txt作为电子邮件的内容,但是,当我运行此命令时,出现以下错误: 是否可以从仍由curl托管的个人服务器托管帐户发送电子邮件?这样会使身份验证过程更容易吗? 问题答案: curl –url 'smtps://smtp.gmail.com:465’ –ssl-reqd \ –mail-from '

  • 问题内容: 我正在尝试使用Java发送电子邮件: 我收到错误消息: 此代码可以发送电子邮件吗? 问题答案: 户名+密码不再是推荐的解决方案。这是因为 我尝试了此操作,Gmail向该代码中用作用户名的电子邮件发送了一封电子邮件,其中说我们最近阻止了你的Google帐户的登录尝试,并将我定向到此支持页面:support.google.com/accounts/answer/6010255因此它看起来很

  • 问题内容: 这有点令人困惑,所以请在这里忍受… 我想建立一个系统,使用户可以通过我的网站发送模板化的电子邮件,但实际上并没有使用我的服务器发送它- 它只是打开自己的本地邮件客户端,并准备发送电子邮件。该应用程序将使用预定义的变量填充电子邮件的正文,以节省用户必须自己键入的电子邮件。然后,如果该消息不完全适合其目的,则他们可以根据需要编辑该消息。 我有很多理由希望它通过用户的本地邮件客户端,因此让服

  • 它显示以下错误: JasperException:处理JSP页面/assignment3/send_email.JSP第132 129行时发生异常:Message Message=new MimeMessage(session1);130:131://Set FROM:header标头字段。132:message.setFrom(新InternetAddress(from));133:134://

  • 问题内容: 如何使用Python在电子邮件中发送HTML内容?我可以发送简单的文字。 问题答案: 这是一个如何使用替代纯文本版本创建HTML消息的示例:

  • 问题内容: 我已经在ES6中使用React.js构建了一个Web应用程序。我目前要创建一个基本的“联系我们”页面,并希望发送电子邮件。我是React的新手,只是发现我实际上不能使用React本身发送电子邮件。我正在使用,但在将示例代码与我的React文件集成时遇到了一些困难。具体来说,调用是可行的,但是我不知道如何将其链接到我的React前端。 Nodemailer:https://github.