0

I am writing a program to send email using Java mail API but every time it is showing me the exception Could not connect to host 'abc.xyz.pqr' . However there is no problem with the host as I am able to Telnet the host and it is getting connected successfully.

I am trying to use my org mail server for sending email. My code below works fine if I use gmail smtp. I guess there might be some issue with the code properties etc. Take a look:

public void sendEMail(final EmailServiceRequest request, String filePath) {

    Properties properties = System.getProperties();
    properties.put("mail.smtp.host", EmailConstants.HOST);
    properties.put("mail.smtp.port", EmailConstants.PORT); 
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.starttls.enable", "true");

    //Session session = Session.getDefaultInstance(properties, null);
        Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(EmailConstants.USERNAME, EmailConstants.PASSWORD );
        }
    });

    // 2) compose message
    try {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(request.getSenderEmailId()));

        InternetAddress[] addressTo = new InternetAddress[request.getRecipients().size()]; 
        for (int i = 0; i < request.getRecipients().size(); i++) { 
          addressTo[i] = new InternetAddress(request.getRecipients().get(i)); 
        } 
        message.addRecipients(Message.RecipientType.TO, addressTo);

        message.setSubject(request.getSubject());

        // 3) create MimeBodyPart object and set your message text
        BodyPart messageBodyPart1 = new MimeBodyPart();
        messageBodyPart1.setText(request.getContent());

        // 4) create new MimeBodyPart object and set DataHandler object to this object
        MimeBodyPart messageBodyPart2 = new MimeBodyPart();


        DataSource source = new FileDataSource(filePath);

        messageBodyPart2.setDataHandler(new DataHandler(source));
        messageBodyPart2.setFileName(ApplicationUtils.getAttachmentName(filePath));

        // 5) create Multipart object and add MimeBodyPart objects to this object
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart1);
        multipart.addBodyPart(messageBodyPart2);

        // 6) set the multiplart object to the message object
        message.setContent(multipart);

        // 7) send message
     //Transport t = session.getTransport("smtp");
            try {
//                t.connect(EmailConstants.USERNAME, EmailConstants.PASSWORD);
//                t.sendMessage(message, message.getAllRecipients());
                Transport.send(message);
            } finally {
//                t.close();
            }
        System.out.println("message sent....");
    } catch (MessagingException ex) {
        ex.printStackTrace();
    }
}

I have tried both Transport.send and transport.sendMessage method and both are giving the same exception. Here is the stack trace:

javax.mail.MessagingException: Could not connect to SMTP host: 

abc.xyz.pqr, port: 25;
  nested exception is:
    java.net.ConnectException: Operation timed out
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1282)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
    at javax.mail.Service.connect(Service.java:297)
    at javax.mail.Service.connect(Service.java:156)
    at javax.mail.Service.connect(Service.java:105)
    at javax.mail.Transport.send0(Transport.java:168)
    at javax.mail.Transport.send(Transport.java:98)
    at com.pb.email.service.impl.EmailServiceImpl.sendEMail(EmailServiceImpl.java:104)
    at com.pb.scheduler.ScrapeReportScheduler.main(ScrapeReportScheduler.java:64)
Caused by: java.net.ConnectException: Operation timed out
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:382)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:241)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:228)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:431)
    at java.net.Socket.connect(Socket.java:527)
    at java.net.Socket.connect(Socket.java:476)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:232)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1250)
    ... 8 more

I don't know whats wrong? If there was some host issue, why is it getting connected using telnet on command prompt? Am i missing something in the code? Please help.

PS : I understand the USERNAME and PASSWORD should be read from properties file. Please ignore the fact that am using string literals.

7
  • 1
    Is there a smtp-server listening on port 25 on abc.xyz.pqr? Telnet uses different port(23) Commented Jul 2, 2014 at 10:54
  • No. And even removing the port from properties doesn't solves the problem. Commented Jul 2, 2014 at 10:59
  • on wich port the smtp-server is listening. Commented Jul 2, 2014 at 11:04
  • Try netstat -anpt | grep 25 or the equivalent on your system; this will show you if there is a process listening to 25/smtp Commented Jul 2, 2014 at 12:08
  • Also, check the firewall rules on both endpoints. Commented Jul 2, 2014 at 12:34

2 Answers 2

1

Possibly your server is listening on the "SMTP-over-SSL" port? Try setting the property "mail.smtp.ssl.enable" to "true".

Also, see this list of common mistakes.

Sign up to request clarification or add additional context in comments.

2 Comments

Have read the common mistakes column. Also have turned off the firewall and have enabled the ssl in properties but still no luck. Its the same connection timeout exception.
Post the results of trying all the connection debugging tips in the JavaMail FAQ. Copy&paste the results of using telnet as well.
0

I will suggest you to SMTPTransport class instead. Here is a piece of course that may work properly.

    ...
    Properties properties = System.getProperties();
    properties.put("mail.smtp.host", EmailConstants.HOST);
    properties.put("mail.smtp.port", EmailConstants.PORT); //465
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.socketFactory.port", "465");
    properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

    Session session = Session.getInstance(properties, null);
    session.setDebug(true);
    try {
           MimeMessage message = new MimeMessage(session);
           message.setFrom(new InternetAddress(request.getSenderEmailId()));
           ...
           SMTPTransport t = (SMTPTransport)session.getTransport("smtp");
           t.connect(EmailConstants.USERNAME, EmailConstants.PASSWORD);
           t.sendMessage(msg, msg.getAllRecipients());
    }catch(Exception e){
           e.printStackTrace();
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.