Java 说邮件已发送,但实际上没有

Java says mail has been sent, But it actually has not

我正在尝试通过 java 发送邮件,但它不起作用。那也没有显示任何错误。我是 javamail 的新手,所以请帮助:) 我到处搜索这个问题,但我只能在 php 中找到这个问题。所以请让我知道如何在 java.

中调试它
public void sendMail(){

        String host = "smtp.gmail.com";
        String user = "tharumudu@gmail.com";
        String password = "pass";
        String to = "tharumudu@gmail.com";
        String from = "tharumudu@gmail.com";
        String subject = "Subject";
        String messageText = "Thada ! ";
        boolean sessionBug = false;

        Properties properties = System.getProperties();

        properties.put("mail.smtp.starttls.enable","true");
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", "587");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.required","true");
        properties.put("mail.smtp.ssl.trust", "smtp.gmail.com");

        Session session = Session.getDefaultInstance(properties, null);
        session.setDebug(sessionBug);

        Message msg = new MimeMessage(session);
        try {
            msg.setFrom(new InternetAddress(from));
            InternetAddress address = new InternetAddress(to);
            msg.setRecipient(Message.RecipientType.TO, address);
            msg.setSubject(subject);
            msg.setSentDate(new Date());
            msg.setText(messageText);


            Transport transport = session.getTransport("smtp");
            transport.connect(host, user, password);
            transport.close();
            System.out.println("email sent successfully");

        } catch (MessagingException e) {
            System.err.println(e);
        }


    }

我已经调用了这里的方法

  public void sendButtonClicked(ActionEvent actionEvent) {
        sendMail();
    }

您的代码中没有调用 send or sendMessagesend 是实际发送电子邮件的内容。您所做的只是创建一条消息并进行连接。连接后,发送。

您必须致电 sendsendMessage 才能发送电子邮件。所以你下面的代码

Transport transport = session.getTransport("smtp");
transport.connect(host, user, password);
transport.close();

可以替换为

Transport.send(msg);

用户名和密码已通过您的会话属性提供。