Search code examples
javaemailapache-commons-email

Commons email example hanging on send()


I'm trying to get this example for the Apache Commons email library to work. Here is my code:

    SimpleEmail email = new SimpleEmail();      
    email.setHostName("smtp.gmail.com");
    email.setSmtpPort(465);
    email.setAuthenticator(new DefaultAuthenticator("[email protected]", "password"));     
    email.setTLS(true); 
    try {
        email.setFrom("[email protected]");
        email.setSubject("TestMail");
        email.setMsg("This is a test mail ... :-)");
        email.addTo("[email protected]");
        System.out.println("Sending...");
        email.send();
        System.out.println("Email sent!");

    } catch (Exception e) {
        System.out.println("Email not sent!");
        e.printStackTrace();
    }

As you can see it's basically unchanged from the example, except I have to use port 465 instead of 587 because 587 causes a Connection refused exception (based on this question). Now this code is hanging on the email.send() line. The only output I get is:

Sending...

But no exceptions are thrown. Do I need to open a port in my firewall? (I might not be able to do that as I'm trying to do this from work). Thanks!

Edit

After a long time I get this exception:

org.apache.commons.mail.EmailException: Sending the email to the following server failed : smtp.gmail.com:465
...
Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1

Solution

  • Based on your edits and answer to my comment, you shouldn't look for your problems in Java code, but in the firewall or your network configuration.