Surez
Surez

Reputation: 131

Java Mail over TLS

I am trying to send an email from my program through a TLS connection. Here is my code

    final String username = "XXXXXX";
    final String password = "XXXXX"; 
    Properties props = new Properties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.starttls.enable","true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.host", "mail.xxxx.com");
    props.put("mail.smtp.port", "587");

    Session session = Session.getInstance(props,
            new javax.mail.Authenticator() {
              protected PasswordAuthentication getPasswordAuthentication() {
                  return new PasswordAuthentication(username, password);
              }
            });

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("[email protected]"));
    message.setRecipients(Message.RecipientType.TO,
        InternetAddress.parse(to_address));
    message.setSubject("Test Mail"); 
    message.setText("TestMail ");
    Transport.send(message)

My email gateway has incoming Mail settings with SSL enabled and outgoing with TLS enabled on port 587. I am able to configure this settings in outlook and it's working fine. But through my java program it's saying "Connection Refused". Help Appreciated!

Worked Finally:

I used the InstallCert program to import the certicate to generate jssecacerts file and I added the file to my /jre/lib/security/ path. here is my working code

    properties.put("mail.transport.protocol", "smtp");
    properties.put("mail.smtp.host", "XXXXXX");  
    properties.put("mail.smtp.port", "465"); 
    properties.put("mail.smtp.ssl.enable", true);
    properties.put("mail.smtp.socketFactory.port", "465");
    properties.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
    properties.put("mail.smtp.socketFactory.fallback", "false"); 
    properties.put("mail.smtp.quitwait", "false"); 
    properties.put("mail.smtp.auth", "true"); 

Upvotes: 9

Views: 20766

Answers (1)

Aviram Segal
Aviram Segal

Reputation: 11120

You need to use the smtps protocol instead of smtp

props.put("mail.transport.protocol", "smtps");
props.put("mail.smtps.starttls.enable","true");
props.put("mail.smtps.auth", "true");
props.put("mail.smtps.host", "mail.xxxx.com");
props.put("mail.smtps.port", "587");

You can also try to set the protocol specificly for rfc822, this helps some times

props.put("mail.transport.protocol.rfc822", "smtps");

Upvotes: 5

Related Questions