我有这个代码从 java 发送邮件显示错误

I have this code to send mail from java showing error

      package Controller;

      import java.util.Properties;
      import javax.mail.*;
      import javax.mail.internet.InternetAddress;
      import javax.mail.internet.MimeMessage;

     public class SendMail {
      static String from = "******@gmail.com";
     static String pass ="*****";
     static String to = "****@gmail.com";
     static String host = "smtp.gmail.com";


    public static void main(String[] args) {
          Properties properties = System.getProperties();
          properties.put("mail.smtp.starttls.enable", "true");
          properties.put("mail.smtp.host", host);
          properties.put("mail.smtp.user", from);
          properties.put("mail.smtp.password", pass);
          properties.put("mail.smtp.port", "587");
          properties.put("mail.smtp.auth", "true");
          Session session = Session.getDefaultInstance(properties);

          try{
      MimeMessage message = new MimeMessage(session);


      message.setFrom(new InternetAddress(from));


      message.addRecipient(Message.RecipientType.TO,
                               new InternetAddress(to));


      message.setSubject("This is the Subject Line!");


      message.setText("Ithis is a test");


      Transport transport = session.getTransport("smtp");
      transport.connect(host, from, pass);
      transport.sendMessage(message, message.getAllRecipients());
      transport.close();
      System.out.println("Sent message successfully....");
   }

      catch (MessagingException mex) {
         mex.printStackTrace();


      }
        }
    }

此代码显示以下错误: javax.mail.MessagingException: 无法将套接字转换为 TLS; 谁能帮我,为什么不能将套接字转换为 TLS。我该怎么做才能解决错误??请帮忙。

默认情况下,Gmail 不允许 "less-secure" 应用访问您的电子邮件。

为了得到你的代码运行:

证书尚未安装在文件 cacerts 中,或者您可能希望将 google smtp url 设置为 "trusted"。尝试添加此代码

properties.put("mail.smtp.ssl.trust", "smtp.gmail.com");

在另一张纸条上。当您尝试获取 session

时,您可能需要设置 javax.mail.Authenticator

// 建立会话以创建要发送的 MimeMessage

        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.host", "smtp.gmail.com");
        props.put("mail.smtp.starttls.enable","true");
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "587");
        props.setProperty("mail.smtp.quitwait", "false");

        Session session = Session.getDefaultInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("name_here", "password_here");
            }
        });