Hello World

Sending a mail in Java (and Android) with Apache Commons Net SMTP : STARTTLS, SSL 본문

Java/Core

Sending a mail in Java (and Android) with Apache Commons Net SMTP : STARTTLS, SSL

EnterKey 2016. 1. 12. 16:46
반응형

Recently working on an Android experiment, I wanted to send emails using a SMTP server, using authentication and encryption, from an android app.

Well, I found out that javax.mail on Android is not a really good option, since it depends on awt classes (legacy I guess) ; some people have tried to adapt it so that you don’t require the whole awt package, but I had little success with that; not mentioning those people have refactored javax.mail for Android few years ago themselves, without any maintenance.

Another option that came to my mind is re using Apache Commons Net : since the community added an SMTPSClient and an AuthenticatingSMTPClient to the original SMTP client (and applied a little patch of mine for SSL and authentication), you can embed this library in your Android app (no transitive dependencies needed) to send mail using authentication over a secured layer. (this post actually inspired me, but it is using an old version of Apache Commons Net, using 3.3 you don’t need to do that anymore)

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

01public void sendEmail() throws Exception { 
02    String hostname = "smtp.gmail.com";
03    int port = 587;
04  
05    String password = "gmailpassword";
06    String login = "account@gmail.com";
07  
08    String from = login;
09  
10    String subject = "subject" ;
11    String text = "message";
12  
13    AuthenticatingSMTPClient client = new AuthenticatingSMTPClient();
14    try {
15      String to = "recipient@email.com";
16      // optionally set a timeout to have a faster feedback on errors
17      client.setDefaultTimeout(10 1000);
18      // you connect to the SMTP server
19      client.connect(hostname, port);
20      // you say ehlo  and you specify the host you are connecting from, could be anything
21      client.ehlo("localhost");
22      // if your host accepts STARTTLS, we're good everything will be encrypted, otherwise we're done here
23      if (client.execTLS()) {
24  
25        client.auth(AuthenticatingSMTPClient.AUTH_METHOD.LOGIN, login, password);
26        checkReply(client);
27  
28        client.setSender(from);
29        checkReply(client);
30  
31        client.addRecipient(to);
32        checkReply(client);
33  
34        Writer writer = client.sendMessageData();
35  
36        if (writer != null) {
37          SimpleSMTPHeader header = new SimpleSMTPHeader(from, to, subject);
38          writer.write(header.toString());
39          writer.write(text);
40          writer.close();
41          if(!client.completePendingCommand()) {// failure
42            throw new Exception("Failure to send the email "+ client.getReply() + client.getReplyString());
43          }
44        else {
45          throw new Exception("Failure to send the email "+ client.getReply() + client.getReplyString());
46        }
47      else {
48        throw new Exception("STARTTLS was not accepted "+ client.getReply() + client.getReplyString());
49      }
50    catch (Exception e) {
51        throw e;
52    finally {
53        client.logout();
54        client.disconnect();
55    }
56  }
57  
58  private static void checkReply(SMTPClient sc) throws Exception {
59    if (SMTPReply.isNegativeTransient(sc.getReplyCode())) {
60      throw new Exception("Transient SMTP error " + sc.getReply() + sc.getReplyString());
61    else if (SMTPReply.isNegativePermanent(sc.getReplyCode())) {
62      throw new Exception("Permanent SMTP error " + sc.getReply() + sc.getReplyString());
63    }

Nothing much to add here, of course the exception handling could be optimized if you used your own exception classes.

SMTP Authentication and SSL with Commons Net

Some SMTP servers are configured to only accept “a to z SSL” : you have to secure the communication right before issuing any commands to the server; usually the port used is 465.

Let’s take the LaPoste.net example (free email accounts offered by the french post) :

01public void sendEmail() throws Exception { 
02    String hostname = "smtp.laposte.net";
03    int port = 465;
04  
05    String password = "password";
06    String login = "firstname.lastname";
07  
08    String from = login + "@laposte.net";
09  
10    String subject = "subject" ;
11    String text = "message";
12  
13    // this is the important part : you tell your client to connect using SSL right away
14    AuthenticatingSMTPClient client = new AuthenticatingSMTPClient("TLS",true);
15    try {
16      String to = "anthony.dahanne@gmail.com";
17      // optionally set a timeout to have a faster feedback on errors
18      client.setDefaultTimeout(10 1000);
19      client.connect(hostname, port);
20      client.ehlo("localhost");
21      client.auth(AuthenticatingSMTPClient.AUTH_METHOD.LOGIN, login, password);
22      checkReply(client);
23  
24      client.setSender(from);
25      checkReply(client);
26  
27      client.addRecipient(to);
28      checkReply(client);
29  
30      Writer writer = client.sendMessageData();
31  
32      if (writer != null) {
33        SimpleSMTPHeader header = new SimpleSMTPHeader(from, to, subject);
34        writer.write(header.toString());
35        writer.write(text);
36        writer.close();
37        if(!client.completePendingCommand()) {// failure
38          throw new Exception("Failure to send the email "+ client.getReply() + client.getReplyString());
39        }
40      else {
41        throw new Exception("Failure to send the email "+ client.getReply() + client.getReplyString());
42      }
43    catch (Exception e) {
44        throw e;
45    finally {
46        client.logout();
47        client.disconnect();
48    }

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  :

1<dependency>
2    <groupid>commons-net</groupid>
3    <artifactid>commons-net</artifactid>
4    <version>3.3</version>
5</dependency>

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

01buildscript {
02    repositories {
03        mavenCentral()
04    }
05    dependencies {
06        classpath 'com.android.tools.build:gradle:0.4.2'
07    }
08}
09apply plugin: 'android'
10  
11repositories {
12    mavenCentral()
13}
14  
15dependencies {
16    compile fileTree(dir: 'libs', include: '*.jar'), 'commons-net:commons-net:3.3'
17}
18  
19android {
20    compileSdkVersion 17
21    buildToolsVersion "17.0.0"
22  
23    sourceSets {
24        main {
25            manifest.srcFile 'AndroidManifest.xml'
26            java.srcDirs = ['src']
27            resources.srcDirs = ['src']
28            aidl.srcDirs = ['src']
29            renderscript.srcDirs = ['src']
30            res.srcDirs = ['res']
31            assets.srcDirs = ['assets']
32        }
33  
34        instrumentTest.setRoot('tests')
35    }
36}

Enjoy !
 


출처: http://www.javacodegeeks.com/2013/11/sending-a-mail-in-java-and-android-with-apache-commons-net-smtp-starttls-ssl.html?utm_content=buffer7de2c&utm_medium=social&utm_source=facebook.com&utm_campaign=buffer

반응형
Comments