我编写了一个简单的功能,允许我在Web应用程序中使用SMTP协议发送邮件。该功能如下所示:
public void sendEmail(String recipient,String subject,String content) {
try {
// Recipient's email ID needs to be mentioned.
// String to = "example@hotmail.com";
// Sender's email ID needs to be mentioned
String from = "kobay@gmail.com";
// Assuming you are sending email from localhost
String host = "localhost";
System.out.println("Please Wait, sending email...");
/*Setup mail server */
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", 587);
// Get session
Session session = Session.getDefaultInstance(props, null);
session.setDebug(true);
// Define message
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
// Set Subject: header field
message.setSubject(subject);
// Now set the actual message
message.setText(content);
try {
Transport.send(message);
} catch (AddressException addressException) {
addressException.printStackTrace();
}
编译没有问题,但是当我点击发送电子邮件并检查我的Glassfish日志时,它说:
Couldn't connect to host, port: localhost, 587; timeout -1]]
我知道我需要将Java Mail API jar文件导入到我的项目中。而且仍然是相同的错误。
我做错了吗?