1

I am new in Java. I want to build an application which will send email to my clients. I searched over stackoverflow but didn't get any desired solution for that. Somewhere I saw that this could be an issue of firewall but didn't get the solution for fixing it. I am using Ubuntu 14.10
//Here is my code.

public class sendMail {

    public void send(String from, String to, String subject, String body) {
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "587");
        props.put("mail.smtp.socketFactory.class",
            "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "587");

        Session session = Session.getDefaultInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("xxxxxxx@gmail.com","xxxxx");
            }
        });

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("xxxxxx@gmail.com"));
            message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse("xxxx@domain.com"));
            message.setSubject("Testing Subject");
            message.setText("Hello this is not spam," +
                "\n\n This is a JavaMail test...!");

            Transport.send(message);

            System.out.println("Done");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }  
}  

And my Error is:

Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
    nested exception is:
       java.net.ConnectException: Connection timed out
       at dbdemo.sendMail.send(sendMail.java:54)
       at dbdemo.DBDemo.main(DBDemo.java:62)
Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
    nested exception is:
       java.net.ConnectException: Connection timed out
       at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1706)
       at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:525)
       at javax.mail.Service.connect(Service.java:313)
       at javax.mail.Service.connect(Service.java:172)
       at javax.mail.Service.connect(Service.java:121)
       at javax.mail.Transport.send0(Transport.java:190)
       at javax.mail.Transport.send(Transport.java:120)
       at dbdemo.sendMail.send(sendMail.java:49)
       ... 1 more
Caused by: java.net.ConnectException: Connection timed out
       at java.net.PlainSocketImpl.socketConnect(Native Method)
       at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
       at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
       at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
       at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
       at java.net.Socket.connect(Socket.java:579)
       at java.net.Socket.connect(Socket.java:528)
       at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:284)
       at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:227)
       at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1672)
       ... 8 more
Java Result: 1

Any help would be appreciated. Please help me.

Avoid
  • 343
  • 2
  • 9
  • 20
  • This question gets asked from time, you really should have tried searching for it (I did a search using `[java] gmail port 587` and found http://stackoverflow.com/questions/21558693/properties-for-sending-email-via-gmail) – MadProgrammer Feb 07 '15 at 05:17
  • You should probably be using `props.put("mail.smtp.starttls.enable", "true");` instead of defining the socket factory. – user207421 Feb 07 '15 at 06:43
  • @MadProgrammer I used direct IP "173.194.78.108". But still same error is coming – Avoid Feb 07 '15 at 11:51
  • @EJP It's still not working. – Avoid Feb 07 '15 at 18:35

3 Answers3

2

Throw away the code that you cut and pasted from someone who doesn't understand how to use JavaMail and use the code for connecting to Gmail in the JavaMail FAQ.

If it doesn't work for you, follow the debugging tips in the JavaMail FAQ.

If you still can't figure it out, and can't find the answer in the JavaMail FAQ, post the JavaMail debug output here.

Bill Shannon
  • 29,579
  • 6
  • 38
  • 40
  • You're very new to debugging, huh? Update your post with the code you're currently using, which hopefully you got from the FAQ. And update your post with the JavaMail debug output, which the FAQ tells you how to get. – Bill Shannon Feb 08 '15 at 00:05
  • DEBUG: setDebug: JavaMail version 1.4.4 DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc] DEBUG SMTP: useEhlo true, useAuth false DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 465, isSSL true. After this the same error is coming. – Avoid Feb 09 '15 at 03:42
  • You might want to [upgrade to a newer version of JavaMail](https://java.net/projects/javamail/pages/Home), although that's unrelated to your problem. Did you try the connection debugging tips in the FAQ? What did they show? In your web browser, is it configured to use a [proxy server](http://www.oracle.com/technetwork/java/javamail/faq/index.html#proxy)? That would be another indication that there's a firewall between you and Gmail. Can you configure Thunderbird to access Gmail? If not, that would be yet another clue that there's a firewall. – Bill Shannon Feb 10 '15 at 00:45
1

This code worked for me,

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class Email {

private static String USER_NAME = "xxxx";  // GMail user name (just the part before "@gmail.com")
private static String PASSWORD = "xxxx"; // GMail password
private static String RECIPIENT = "xxx@gmail.com";

public static void main(String[] args) {
    String from = USER_NAME;
    String pass = PASSWORD;
    String[] to = { RECIPIENT }; // list of recipient email addresses
    String subject = "Java send mail example";
    String body = "Welcome to JavaMail!";

    sendFromGMail(from, pass, to, subject, body);
}

private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
    Properties props = System.getProperties();
  String host = "smtp.gmail.com";
   // String host="localhost";
  // props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
    props.put("mail.smtp.starttls.enable", "true");
   // props.put("mail.smtp.host", host);
   props.put("mail.smtp.ssl.trust", host);
    props.put("mail.smtp.user", from);
    props.put("mail.smtp.password", pass);
    props.put("mail.smtp.port", "587");//587
    props.put("mail.smtp.auth", "true");
   //System.out.println("success point 1");

    Session session = Session.getDefaultInstance(props);
    MimeMessage message = new MimeMessage(session);

    try {
         //System.out.println("success point 2");

        message.setFrom(new InternetAddress(from));
        InternetAddress[] toAddress = new InternetAddress[to.length];

        // To get the array of addresses
        for( int i = 0; i < to.length; i++ ) {
            toAddress[i] = new InternetAddress(to[i]);
        }

        for( int i = 0; i < toAddress.length; i++) {
            message.addRecipient(Message.RecipientType.TO, toAddress[i]);
        }

         //System.out.println("success point 3");

        message.setSubject(subject);
        message.setText(body);
        // System.out.println("success point 4");

        Transport transport = session.getTransport("smtp");
        // System.out.println("success point 5");

        transport.connect(host, from, pass);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
        //System.out.println("success 6");
    }
    catch (AddressException ae) {
        ae.printStackTrace();
    }
    catch (MessagingException me) {
        me.printStackTrace();
    }
  }
}

And i had used some jar files are activation,java-mail-1.4.4,javamail-smtp-1.4.2,pop3,mail-6.0.0-sources

Anptk
  • 1,125
  • 2
  • 17
  • 28
  • @user3817980 Can you post the error which you got ? – Anptk Feb 09 '15 at 04:21
  • The same problem solved...http://stackoverflow.com/questions/26087018/sending-emails-through-java-javax-mail-messagingexception-could-not-connect-t/26092701#26092701 Check your jar files and versions – Anptk Feb 09 '15 at 04:26
  • Which version should I use? – Avoid Feb 09 '15 at 04:32
  • I am using the same as DEBUGGER is showing: DEBUG: setDebug: JavaMail version 1.4.4 DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc] DEBUG SMTP: useEhlo true, useAuth true DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 587, isSSL false – Avoid Feb 09 '15 at 04:52
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/70537/discussion-between-user3817980-and-anptk). – Avoid Feb 09 '15 at 04:59
0

Connection timeouts typically result from

  • some kind of firewall on the way that simply eats the packets without telling the sender things like "No Route to host"
  • packet loss due to wrong network configuration or line overload
  • too many requests overloading the server

Here is How do I turn off firewall on Ubuntu

If that doesn't work try Changing the props.put("mail.smtp.port", "587"); to props.put("mail.smtp.port", "465"); or props.put("mail.smtp.port", "25");


Some further info (not timeout related), once you're connected:

Don't forgot to Double check your login credentials. because they may cause Authentication Failed Exception if provided incorrect

Community
  • 1
  • 1
Neeraj Jain
  • 7,643
  • 6
  • 34
  • 62
  • All good information up to but excluding the final sentence. Login credentials have nothing to do with connection timeouts whatsoever. – user207421 Feb 07 '15 at 09:37
  • @EJP , I have mentioned it for further Authentication Failed Exception which might likely to be caused if the Login Credentials are incorrect . that has no relation with Connection Timeout – Neeraj Jain Feb 07 '15 at 09:40
  • That's exactly what I said. If you want to clarify your answer accordingly, by all means proceed. If you want to mention 1000 other irrelevant error conditions,bmake sure you mention the associate exceptions they cause too. – user207421 Feb 07 '15 at 10:06