如何使用线程发送电子邮件?我写了下面的代码,但是没有用。它不会引发任何异常,但是我也没有收到电子邮件。如果我不使用线程,则代码可以正常工作。有什么问题吗?
final String username = "admin@gmail.com";
final String password = "admin";
new Thread(()-> {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.prot", "465");
Session session = Session.getDefaultInstance(props,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}
);
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
message.setSubject(subject);
message.setText(text);
Transport.send(message);
} catch (Exception e) {
System.out.println("Something is wrong!");
}
}).start();