Tuesday, October 23, 2007

JavaMail and GMail : it's all about configuration

Yesterday I spent a couple of hours trying to send emails with JavaMail APIs via my GMail account.

It wasn't easy: the standard JavaMail configuration didn't work, while Google gave me a lot of wrong and/or outdated information.
Moreover, JavaMail FAQs provide a sample about sending emails via GMail, but it has some problems too.

So I think these bits of information will be helpful to someone trying to accomplish the same task ...

The problem is that GMail uses TLS and the STARTTLS command.
The solution applies to JavaMail 1.4 and JDK 1.4 or higher and is just a matter of configuration.

First, and obviously, enable POP support for your GMail account.

Then, put the following configuration in your properties file:

mail.transport.protocol=smtp

mail.smtp.host=smtp.gmail.com

mail.smtp.starttls.enable=true

mail.smtp.auth=true

mail.user=<your_username>

mail.password=<your_password>

The key point is the part in bold: enabling the STARTTLS command.
That's the tricky part.
Once created the properties file above, just configure your JavaMail Session object and send your mail message as you'd always do:


Properties props = ...; // <-- Your properties above

Authenticator authenticator = new YourAuthenticator(...);

Session session = Session.getInstance(props, authenticator);

Transport t = session.getTransport();

t.send(yourMail);


That's all.
Feel free to comment on for any question.
Enjoy it!

8 comments:

Anonymous said...
This comment has been removed by a blog administrator.
Le said...

Do you need to return PasswordAuthentication with the username/password from the Authenticator class if you are giving them in the properties aswell?

Sergio Bossa said...

Hi Le,

as far as I know, passwords must be provided through a proper Authenticator object: so it should be always mandatory.

Cheers,

Sergio B.

Anonymous said...

thanks 4 the info.

Nathan said...

Yeah, I checked. You don't need to set the username and passwords as properties. Just extend the Authentication class and pass that into Session.getInstance(...). This blog entry contained the one key piece of information that was missing from umpteen forum postings, which is that THIS WILL NOT WORK IF YOU DO NOT ENABLE SUPPORT IN GMAIL. Thanks for the info.

Lailson Bandeira said...

Thanks guy. You saved my day!

Akcasoy said...

Hi Sergio!
I am trying to make same but i couldnt achieve still.
I just continue to get same kind of errors.
Can u please send me the code with that full configuration file?
Thank you very much!

Sergey Bezrukov said...

Don't forget to set mail.smtp.port=587 as Gmail doesn't use standard SMTP port (25)