Sona Shetty
Sona Shetty

Reputation: 1047

Java Mail API fails intermittently

I have created automated email report using java mail api which needs to be triggered everyday after a batch file run.Although it works fine most of the times,at times it gives exception javax.mail.MessagingException: Could not connect to SMTP host: my host name, port: 25; nested exception is: java.net.ConnectException: Connection refused.This is not due to authentication issue as i use the same credentials whenever i sent the email.

I am not sure why java mail api fails intermittently.Can i get some suggestion to debug the issue?

I am using the below code snippet -

  String to = "[email protected]";//change accordingly

  String from = "[email protected]";//change accordingly
  final String username = "abc";//change accordingly
  final String password = "*****";//change accordingly

  String host = "My SMTP server";

  Properties props = new Properties();
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.starttls.enable", "true");
  props.put("mail.smtp.host", host);
  props.put("mail.smtp.port", "25");

  // Get the Session object.
  Session session = Session.getInstance(props,
  new javax.mail.Authenticator() {
     protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password);
     }
  });

  try {       
     Message message = new MimeMessage(session);
     message.setFrom(new InternetAddress(from));
     message.setRecipients(Message.RecipientType.TO,
     InternetAddress.parse(to));
     message.setSubject("Testing Subject");
     message.setText("message to stakeholders");
     Transport.send(message);
  }

Upvotes: 0

Views: 817

Answers (2)

Bill Shannon
Bill Shannon

Reputation: 29971

If JavaMail can't connect "sometimes" with "connection refused", the possibilities are:

  1. The server is actually down.
  2. The server is up, but too busy to accept new connections.
  3. The server is up, but is rejecting connections for some policy reason, e.g., you've connected too frequently.
  4. Some firewall or anti-virus program has rejected the connection.

Check the server configuration and log files. If there's nothing on the server indicating that it's rejecting connections, check the client.

Upvotes: 1

Daniel Protopopov
Daniel Protopopov

Reputation: 7236

It's a good idea to check logs on the mail server to see possible cause of the refusal - especially since you know WHEN failed attempts were made at.

Upvotes: 1

Related Questions