【问题标题】:Can't send basic email with javamail无法使用 javamail 发送基本电子邮件
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 你有什么邮件服务器可以推荐吗?我看到可以使用 gmail 但有更好的选择吗?
  • JavaMail FAQ 可以解答您当前和未来的许多问题,包括示例代码。
猜你喜欢
  • 1970-01-01
  • 2019-08-10
  • 2018-12-18
  • 2020-01-21
  • 2015-05-21
  • 1970-01-01
  • 1970-01-01
  • 2012-04-27
相关资源
最近更新 更多