无法使用javamail发送基本电子邮件

时间:2014-11-12 21:03:39

标签: java maven email localhost javamail

我正在尝试使用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

1 个答案:

答案 0 :(得分:0)

邮件API正尝试通过SMTP联系邮件服务器以发送邮件。您将其配置为使用localhost上的邮件服务器,即运行代码的同一台计算机。错误“连接被拒绝”意味着没有任何内容正在侦听标准SMTP端口(25)

我的猜测是该机器上没有运行邮件服务器。找出您要使用的服务器(或允许使用的服务器),并将其用于SMTP主机配置。