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



我试图通过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();
}

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

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

可以用代替

Transport.send(msg);

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

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

最新更新