我正在尝试通过 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
或sendMessage
来发送您的电子邮件。所以你的以下代码
Transport transport = session.getTransport("smtp");
transport.connect(host, user, password);
transport.close();
可以替换为
Transport.send(msg);
用户名和密码已通过您的 session 属性提供。
关于Java说邮件已发送,但实际上并没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51613998/