开发者

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("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 开发者_如何学JAVAit'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


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.


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");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜