SMTP Authentication and STARTTLS with Commons Net

Usually the port used for this matter is 25 or the alternate 587 port : you connect to the SMTP server on a plain connection, you ask for the available commands, if STARTTLS is supported, you use it and the rest of the communication is encrypted.

Let’s take the gmail example, since smtp.gmail.com supports authentication and STARTTLS

Java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

publicvoidsendEmail()throwsException{

Stringhostname="smtp.gmail.com";

intport=587;

Stringpassword="gmailpassword";

Stringlogin="account@gmail.com";

Stringfrom=login;

Stringsubject="subject";

Stringtext="message";

AuthenticatingSMTPClient client=newAuthenticatingSMTPClient();

try{

Stringto="recipient@email.com";

// optionally set a timeout to have a faster feedback on errors

client.setDefaultTimeout(10*1000);

// you connect to the SMTP server

client.connect(hostname,port);

// you say ehlo and you specify the host you are connecting from, could be anything

thrownewException("Failure to send the email "+client.getReply()+client.getReplyString());

}

}else{

thrownewException("Failure to send the email "+client.getReply()+client.getReplyString());

}

}catch(Exceptione){

throwe;

}finally{

client.logout();

client.disconnect();

}

}

I did not repeat the checkReply() method here, since it is the same for both code snippets; you will have noticed that using SSL right away means you don’t have to check for execTls() response (in fact it won’t work if you do so).

Wrapping up

That’s about it; if you want to make those examples work in your environment, you can add the apache commons net 3.3 jar to your classpath

If you’re using Maven add the dependency :

XHTML

1

2

3

4

5

<dependency>

<groupid>commons-net</groupid>

<artifactid>commons-net</artifactid>

<version>3.3</version>

</dependency>

If you’re using Gradle for your Android project, you can also use the following build.gradle file :