javamail returning smtp as transport, instead of smtps
-
06-06-2021 - |
質問
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, "myfakeaddress@gmail.com");
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?
解決
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 InternetAddress
es, which have the type rfc822
Here are three ways to set JavaMail to use smtps protocol for rfc822 addresses:
- Add the line
rfc822=smtps
in the property filesjavamail.address.map
orjavamail.default.address.map
(as described in theSession
javadoc) - Call
s.setProtocolForAddress("rfc822", "smtps")
` on your instantiated session (requires JavaMail 1.4 or later) - Set the property
mail.transport.protocol.rfc822
tosmtps
when instantiating your session (requires JavaMail 1.4.3 or later)
他のヒント
Bill Shannon (current maintainer of Javamail) suggests in this question
Get rid of all the socket factory properties; if you're using a reasonably recent version of JavaMail you don't need them. See the JavaMail FAQ for how to configure JavaMail to access Gmail. You'll also find debugging tips there if it still doesn't work.
Also, change Session.getDefaultInstance to Session.getInstance.
Here is the relevant code from the Javamail FAQ
String host = "smtp.gmail.com";
String username = "user";
String password = "passwd";
Properties props = new Properties();
props.put("mail.smtps.auth", "true");
props.put("mail.debug", "true");
MimeMessage msg = new MimeMessage(session);
// set the message content here
Transport t = session.getTransport("smtps");
try {
t.connect(host, username, password);
t.sendMessage(msg, msg.getAllRecipients());
} finally {
t.close();
}