javamail returning smtp as transport, instead of smtps

AgostinoX picture AgostinoX · May 6, 2012 · Viewed 7.5k times · Source

I set the mail.transport property to smtps, beside the very basic information for connecting to a smtps server:

    Properties p = new Properties();
    p.put("mail.transport.protocol", "smtps");
    p.put("mail.smtps.host", "smtp.gmail.com");
    p.put("mail.smtps.auth", true);

    Session s = Session.getDefaultInstance(p,new Authenticator(){/*authenticator impl.*/});

    MimeMessage mm = new MimeMessage(s); /*then i set the subject, then the body... */
    mm.setRecipients(RecipientType.TO, "[email protected]");

And now, i try to send my message. I want to try the static method; using the instance method sendMessage it works fine. Here it is:

    Transport.send(mm);

It tries to connect to a smtp server, instead of a smtps server. Stepping inside the implementation of javamail (btw, my version is 1.4.5) i've discovered that the method that fails is:

 transport = s.getTransport(addresses[0]);

because it returns an SMTPTransport instead of SMTPSSLTransport; this even if i've set the mail.transport.protocol property to smtps as you can see in the second line of code. Is my procedure buggy anywhere or it isn't possible to send smtps mails via Transport.send static method?

Answer

Stuart Caie picture Stuart Caie · Nov 14, 2014

Transport.send(msg) is looking up the protocol(s) associated with the recipients of your email, for each type of recipient.

All your recipients are InternetAddresses, which have the type rfc822

Here are three ways to set JavaMail to use smtps protocol for rfc822 addresses:

  1. Add the line rfc822=smtps in the property files javamail.address.map or javamail.default.address.map (as described in the Session javadoc)
  2. Call s.setProtocolForAddress("rfc822", "smtps")` on your instantiated session (requires JavaMail 1.4 or later)
  3. Set the property mail.transport.protocol.rfc822 to smtps when instantiating your session (requires JavaMail 1.4.3 or later)