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.

roger_that
  • 9,493
  • 18
  • 66
  • 102

2 Answers2

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.

Bill Shannon
  • 29,579
  • 6
  • 38
  • 40
  • 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. – roger_that Jul 03 '14 at 06:14
  • Post the results of trying all the [connection debugging tips](http://www.oracle.com/technetwork/java/javamail/faq/index.html#condebug) in the JavaMail FAQ. Copy&paste the results of using telnet as well. – Bill Shannon Jul 03 '14 at 18:20
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();
    }
Kwaye Kant
  • 47
  • 1
  • 6