3

All examples of Java Mail usage that I've found set properties for Session with property names defined as simple strings. Example:

   props.put("mail.smtp.auth", "true");
   props.put("mail.smtp.starttls.enable", "true");

As soon as documentation defines "standard" properties for Java Mail API, there might exist a way to check their correctness and autocomplete them in IDE.

However, I can't find such way using google/documentation. I also can't find any explanation for absence of predefined names.

So, is there any way to overcome this problem? Am I missing something obvious that makes an approach with constants impossible/unwanted?

user1875642
  • 1,303
  • 9
  • 18
  • I haven't come across any of such (if you're speaking about `javax.mail`). Btw, make sure you read [this document](http://www.oracle.com/technetwork/java/javamail/faq/index.html) before copying any examples from the Internet. – Andrew Logvinov Nov 13 '13 at 15:04

3 Answers3

4

No, there are no defined constants for these properties. Part of the reason why is that these properties are not completely constant - they're composed of some constant parts but also include the name of the protocol. The JavaMail reference implementation includes at least 8 protocols, so there would need to be 8 "constants" for each property. The property name needs to match the protocol that you're using; I don't know how an IDE would figure that out.

Bill Shannon
  • 29,579
  • 6
  • 38
  • 40
2

I was also looking for similar API's. And it is true that Java does not provide API for email constants however I came across these email API's from apache which provide EmailConstants class for this use.

Yogesh Patil
  • 536
  • 5
  • 20
1

I suggest to create an interface for this:

public interface SessionProperties {
    String AUTH = "mail.smtp.auth";
}

An interface makes it easy to define and use the names (just implement the interface to get access). This was most useful with older Java versions where you had no static imports.

Note that some people frown upon this. The main reason why I'm still using it is the simplicity of the code: I don't have to write all those access modifiers.

From my experience, there are several reasons why many frameworks forget to define global constants for things like that:

  1. Misunderstood data hiding (the constants are somewhere in the code but private - great, they are part of the public API but private! Well done...)

  2. People love cut&paste code. That's what they started with and they always fall back to it.

  3. It makes examples easier to share since all the information is there.

  4. People are too lazy to create a proper public API.

Community
  • 1
  • 1
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820