【问题标题】:Connection reset when try to send mail尝试发送邮件时连接重置
【发布时间】:2020-01-12 10:12:27
【问题描述】:

我正在尝试使用 javax.mail 版本 1.4.7 发送电子邮件。这是我用来发送邮件的代码:

String protocollo = "smtps";
String usernamePec = "fromAddress@pec.it";
String passwordPec = "mypassword";
String pecTo = "ToAddress@pec.it";


Properties props = new Properties();
props.put("mail.transport.protocol", "smtps");
props.put("mail.smtps.host", "smtps.pec.aruba.it"); // esempio smtp.gmail.com
props.put("mail.smtps.auth", "true");

Session session = Session.getInstance(props,new javax.mail.Authenticator()
{
  public PasswordAuthentication getPasswordAuthentication()
    {
    return new PasswordAuthentication( usernamePec,passwordPec);
     }
});

 MimeMessage messaggioEmail = new MimeMessage( session );
 MimeMessageHelper helper = new MimeMessageHelper(messaggioEmail, true);
 helper.setFrom(usernamePec);
 helper.setTo(pecTo);
 helper.setSubject("Test Subject");
 helper.setPriority(1);
 helper.setText("Body Mail ", false);           
 messaggioEmail.saveChanges();
 com.sun.mail.smtp.SMTPMessage mex = new SMTPMessage(messaggioEmail);
 com.sun.mail.smtp.SMTPSSLTransport t = 
 (com.sun.mail.smtp.SMTPSSLTransport)session.getTransport(protocollo); // <--SMTPS
 t.setStartTLS(true); //<-- impostiamo il flag per iniziare la comunicazione sicura
 t.connect( "smtps.pec.aruba.it", usernamePec,passwordPec);
 t.sendMessage( mex, mex.getAllRecipients());
 t.close();

运行此代码我得到以下异常:

javax.mail.MessagingException: Could not connect to SMTP host: smtps.pec.aruba.it, port: 465;
      nested exception is:
        java.net.SocketException: Connection reset
        at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1961)
        at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
        at javax.mail.Service.connect(Service.java:295)
        at javax.mail.Service.connect(Service.java:176)
        at test.Test.main(Test.java:199)
    Caused by: java.net.SocketException: Connection reset
        at java.net.SocketInputStream.read(SocketInputStream.java:210)
        at java.net.SocketInputStream.read(SocketInputStream.java:141)
        at sun.security.ssl.InputRecord.readFully(InputRecord.java:465)
        at sun.security.ssl.InputRecord.read(InputRecord.java:503)
        at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:975)
        at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1367)
        at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1395)
        at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1379)
        at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:549)
        at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:354)
        at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:237)
        at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1927)
... 4 more

由于 ssl 证书握手错误,这似乎是一个问题,对此有何建议,我在哪里做错了?

【问题讨论】:

  • 您的 SSL 设置可能存在问题。 STARTTLS is different to SSL and TLS. Before encryption was standard, many connections between an email client and the server were done insecurely. This put personal information in danger of being stolen. STARTTLS helped to reduce this risk by taking an existing insecure connection and upgrading it to a secure connection that used SSL/TLS. STARTTLS works with either SSL or TLS.reference。因此,您可能需要从一开始就对您的连接进行 SSL/TLS 加密。

标签: java jakarta-mail tls1.2


【解决方案1】:

正如我对 OP 所说,您的 SSL/TLS 连接方法可能存在问题。使用您自己的设置尝试此示例代码,我已经在许多不同的环境中成功使用它。或者,也许您可​​以从示例中选择代码的关键部分:

private void sendMail()
        throws MessagingException, AddressException, IOException {
    String smtpHost = "";
    Integer smtpPort = 465;
    final String from = "me@me.com";
    final String password = "";
    String to = "theOtherGuy@he.com";
    String cc = "";
    String bcc = "";
    String subject = "";
    String bodyText = "";
    List<File> files = null; // Set attachment files if needed

    boolean sslEnable = true;
    boolean startTlsEnable = false;

    String user = "";
    Properties properties = new Properties();
    properties.put("mail.smtp.host", smtpHost);
    properties.put("mail.smtp.port", smtpPort);

    if (user != null && !user.equals("")) {
        properties.put("mail.smtp.user", user);
        properties.put("mail.smtps.user", user);
    } else {
        properties.put("mail.smtp.user", from);
        properties.put("mail.smtps.user", from);
    }
    properties.put("mail.smtp.sendpartial", "true");
    properties.put("mail.smtps.host", smtpHost);
    properties.put("mail.smtps.port", smtpPort);
    properties.put("mail.smtps.sendpartial", "true");
    properties.put("mail.smtp.timeout", 30000);
    properties.put("mail.smtp.connectiontimeout", 60000);
    properties.put("mail.smtp.writetimeout", 15000);

    if (startTlsEnable) {
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtps.starttls.enable", "true");
        properties.put("mail.smtp.ssl.trust", smtpHost);
        properties.put("mail.smtps.ssl.trust", smtpHost);
        properties.put("mail.protocol.ssl.trust", smtpHost);
    }
    if (sslEnable) {
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.trust", smtpHost);
        properties.put("mail.smtps.ssl.enable", "true");
        properties.put("mail.smtps.ssl.trust", smtpHost);
        properties.put("mail.protocol.ssl.trust", smtpHost);
    }

    Session session;
    if (password != null && password.length() > 0) {
        properties.put("mail.smtp.auth", "true");
        final String userName = user;
        if (user != null && !user.equals("")) {
            session = Session.getInstance(properties,
                    new javax.mail.Authenticator() {
                        protected PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(userName,
                                    password);
                        }
                    });
        } else {
            session = Session.getInstance(properties,
                    new javax.mail.Authenticator() {
                        protected PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(from,
                                    password);
                        }
                    });
        }

    } else {
        session = Session.getInstance(properties);
    }

    MimeMessage mailMessage = new MimeMessage(session);
    try {
        mailMessage.setFrom(new InternetAddress(from));
    } catch (AddressException e) {
        throw new AddressException("Invalid FROM address: " + e.getMessage());
    }

    mailMessage.setRecipients(Message.RecipientType.TO, to);
    mailMessage.setRecipients(Message.RecipientType.CC, cc);
    mailMessage.setRecipients(Message.RecipientType.BCC, bcc);
    mailMessage.setSubject(subject);
    mailMessage.setSentDate(new Date());

    // Set the email message text.
    MimeBodyPart messagePart = new MimeBodyPart();
    messagePart.setContent(bodyText, "text/html; charset=utf-8");
    // messagePart.setText(bodyText);
    Multipart multipart = new MimeMultipart("mixed");
    multipart.addBodyPart(messagePart);

    try {
        if (files != null) {
            for (File file : files) {
                MimeBodyPart attachmentPart = new MimeBodyPart();
                attachmentPart.attachFile(file);
                multipart.addBodyPart(attachmentPart);
            }
        }
    } catch (MessagingException e) {
        throw new MessagingException(
                "Error attaching files, MessagingException: "
                        + e.getMessage());
    } catch (IOException e) {
        throw new IOException("Error attaching files: " + e.getMessage());
    }

    mailMessage.setContent(multipart);

    if (password == null || password.length() < 1) {
        Transport.send(mailMessage, mailMessage.getAllRecipients());
    } else if (user != null && !user.equals("")) {
        Transport.send(mailMessage, mailMessage.getAllRecipients(), user,
                password);
    } else {
        Transport.send(mailMessage, mailMessage.getAllRecipients(), from,
                password);
    }
}

【讨论】:

  • 我尝试使用你的代码,但我遇到了同样的问题
【解决方案2】:

首先,让我们简化您的代码。

将会话创建更改为:

Session session = Session.getInstance(props);

像这样获取传输:

 Transport t = session.getTransport(protocollo); // <--SMTPS

移除对 t.setStartTLS 的调用;这可能是您的问题的根源。

您正在使用“smtps”协议,该协议在首次连接到服务器时使用 SSL。 “STARTTLS”支持适用于服务器要求您首先使用纯文本连接进行连接,然后在连接后切换到 TLS (SSL) 的情况。这不是你在这里要做的,除非你的服务器需要它,否则你不想这样做。

【讨论】:

  • 我尝试根据您的建议修改我的代码,但我总是遇到同样的问题
  • 发布更新后的代码和JavaMail debug output
【解决方案3】:

升级库:

<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.2</version>
</dependency>

【讨论】:

  • 你好麦酒!欢迎来到 StackOverflow!你读过How to Ask 页面吗?我建议您采取以下步骤: 1)提出问题,不要命令试图帮助您的人。 2)更具体:你遇到什么问题?您要升级到哪个版本? 3)在问你的问题之前你尝试和搜索了什么?这样会有更多人愿意回复您。
猜你喜欢
  • 2022-07-13
  • 2018-04-27
  • 1970-01-01
  • 2012-04-24
  • 2011-02-06
  • 1970-01-01
  • 1970-01-01
  • 2021-02-07
  • 2014-10-08
相关资源
最近更新 更多