JavaMail specifies a bunch of properties that can be set to configure an SMTP connection. To use STARTTLS it is necessary to set the following property
mail.smtp.starttls.enable=true
Where do I specify the username/password to use the smtp service? Is it enough to specify the:
mail.smtp.user=me
mail.smtp.password=secret
Or do I have to explicitely login using the:
transport.connect(server, userName, password)
Yes, I already tried to do this and it seems that it is necessary to connect using transport.connect(..). But if yes, what are the mail.smtp.user & pass properties for? Are they not enough to use smtp with starttls?
Here is my sendEmail method which is using GMail smtp (JavaMail) with STARTTLS
You can specify the user as
(or
mail.smtp.user
if you don't usemail.transport.protocol=smtps
) in the properties that you use for the session.AFAIK, you can't supply the password. But you can certainly put it in the props and retrieve it yourself. Or get it in some other way, e.g. by prompting the user.
When you have it, there are two ways of supplying it to the session. The simpler one is to use
Or, as pointed out, you can use an authenticator. But then the user from the props is ignored, and you have to explicitly pass it to
PasswordAuthentication
. If you do, then your reward is that you can use the staticTransport.send
.Using Simple Java Mail it should be straightforward:
If you have two-factor login turned on, you need to generate an application specific password from your Google account.
If you still want to do this yourself, the code behind this library is very simple. It sets specific properties on the Session depending on which TransportStrategy was passed (plain, ssl or tls) and it uses an Authenticator to perform the authentication:
And
You have to provide an authenticator when you create the session
then you use the session to send your message (skipping the try/catch, for brevity):
You have to subclass Authenticator and create a PasswordAuthentication object for Session along with env properties to login
user-name sometimes is full email id for some servers like gmail. Hope this helps.