【发布时间】:2015-01-09 20:51:15
【问题描述】:
我正在尝试使用 javamail 发送最基本的电子邮件。我基本上复制粘贴了此处给出的代码,但仍然出现异常: http://www.tutorialspoint.com/java/java_sending_email.htm
我搜索了类似的错误,但找不到答案。
代码:
package main.java;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Email {
/*
* This class sends an email to a specified email address
*/
private final String recipient = "foo@baz.com";
private final String sender = "baz@foo.com";
private Properties properties = null;
private Session session = null;
public Email() {
properties = System.getProperties();
properties.setProperty("mail.smtp.host", "localhost");
session = Session.getDefaultInstance(properties);
}
public void send() {
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(sender));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(recipient));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Now set the actual message
message.setText("This is actual message");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
我还在 Maven 中添加了以下依赖项:
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.1</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
我得到以下异常:
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localhost, 25; timeout -1;
nested exception is:
java.net.ConnectException: Connection refused: connect
...
Caused by: java.net.ConnectException: Connection refused: connect
【问题讨论】:
-
您的机器上是否运行了邮件服务器?如果不是,请将“localhost”替换为您的邮件服务器的主机名。
标签: java maven email localhost jakarta-mail