1

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("username@gmail.com", "password"));     
    email.setTLS(true); 
    try {
        email.setFrom("username@gmail.com");
        email.setSubject("TestMail");
        email.setMsg("This is a test mail ... :-)");
        email.addTo("username@gmail.com");
        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
Community
  • 1
  • 1
andronikus
  • 4,125
  • 2
  • 29
  • 46
  • If you try to telnet from the command line, can you? $ telnet smtp.gmail.com 465 // If you're running linux, no problem, with windows, you may need to add the telnet program, just go to the control panel and add it in the windows components. – stivlo Sep 29 '11 at 14:30
  • I cannot. telnet hangs for a while and then fails silently. However, see my edit above. – andronikus Sep 29 '11 at 15:41

2 Answers2

1

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.

stivlo
  • 83,644
  • 31
  • 142
  • 199
  • Indeed, there's a mail relay server I need to use, TPS reports to fill out, etc etc. I was really hoping to learn something here too D:. Oh well, have some reputation, and thanks! – andronikus Sep 30 '11 at 13:59
0

You need to set the following (because you are using SSL)

Properties props = new Properties();
props.put("mail.smtp.auth", true);
    props.put("mail.smtp.starttls.enable", true);
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.timeout" , "10000");
    props.put("mail.smtp.connectiontimeout" , "10000");
    props.put("mail.smtp.socketFactory.port", 465);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");
Bassel Kh
  • 1,941
  • 1
  • 19
  • 30