使用Java GUI发送电子邮件:不起作用

时间:2016-08-12 06:20:35

标签: java email

我正在编写此代码,但它无效。

public static void main(String[] args) {
    String to = JOptionPane.showInputDialog("Email is to be sent to");
    String from = "raedafd@gmail.com";
    String host = "localhost";
    Properties properties = System.getProperties();
    properties.setProperty("mail.smtp.host", host);
    Session session = Session.getDefaultInstance(properties);
    try {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(JOptionPane.showInputDialog("Subject"));
        message.setContent(JOptionPane.showInputDialog("Content:"), "text/html");
        Transport.send(message);
    } catch (MessagingException mex) {
        mex.printStackTrace();
    }
}

出现以下错误:

 Could not connect to SMTP host: localhost, port: 25;
  nested exception is:
    java.net.ConnectException

1 个答案:

答案 0 :(得分:1)

通过这种方式,电子邮件API希望您在localhost(您自己的PC)上运行SMTP服务器,您是否设置并启动了电子邮件服务器?

如果您想从您的Gmail帐户发送电子邮件,请查看以下示例:https://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/