Receive Email using SubEthaSMTP (The local SMTP server).

14 / May / 2014 by Akash Sethi 5 comments

In my Grails app, I came across a requirement of setting up an SMTP server for receiving mails and extracting their content. After exploring a lot I found SubEthaSMTP to be the most suitable. SubEthaSMTP lets your application receive an SMTP mail very easily.

To setup an SMTP server in your application, You need to follow the steps as follows:

1) Add dependency for the latest (at the time of writing it was 3.1.7) SubEthaSMTP library in the BuildConfig.groovy file.

dependencies {
        runtime "org.subethamail:subethasmtp:3.1.7"
}

2) After adding the library you need to implement two Interfaces, namely MessageHandlerFactory and MessageHandler.

The MessageHandlerFactory is instantiated for every message to be exchanged in an SMTP conversation which (MessageHandlerFactory) in turn instantiates a new instance of MessageHandler.

You can implement the MessageHandlerFactory as follows:

class MessageHandlerFactoryImpl implements MessageHandlerFactory {

 	@Override
 	MessageHandler create(MessageContext ctx) {
        	return new MessageHandlerImpl(ctx)
    	}
}

And you can implement the MessageHandler as follows:

@Log4j
class MessageHandlerImpl implements MessageHandler {
    MessageContext context

    MessageHandlerImpl() {}

    MessageHandlerImpl(MessageContext context) {
        this.context = context
    }

    @Override
    void from(String from) {
        log.info "FROM: ${from}"
    }

    @Override
    void recipient(String recipient) {
        log.info "RECIPIENT: ${recipient}"
    }

    @Override
    void data(InputStream data) {
        log.info "DATA"           
    }

    @Override
    void done() {
        log.info "DONE"
    }
}

The from(), recipient() and data() methods will be called during each stage of SMTP. Multiple MessageHandler are created if multiple messages are delivered with a single SMTP session.

3) Run the SmtpServer on your app’s start up.

 SMTPServer smtpServer  = new SMTPServer(new MessageHandlerFactoryImpl())

 smtpServer.hostName=<your hostname>
 smtpServer.port =<some port> 
 smtpServer.start()

After getting your SmtpServer instance running the next thing you need to do is to send email to your app. For this you can use Telnet program or you can configure a messenger like Thunderbird or Kmail to send mail on locally running SMTP server which is localhost.

The Telnet program can be used to send emails, as shown below (Note: My SMTP server is running on port 25000):

Voilla! it worked.

That’s all you need to run local SMTP server in your app!

The next milestone is to read content of mail

Most of the email client send a multipart message. A MultipartMessage is a simple Message object where the Content-Type is set to multipart and the content body carries a reference to a Multipart object.

You can easily retrieve content from multipart content-typed message using MimeMessage instance. For this you need to include JavaMail API Dsn library. You can extract body part from multipart message with MultipartReport instance. You can do this as follows:

Session session = Session.getDefaultInstance(new Properties())

MimeMessage message = new MimeMessage(session, data)

if (obj instanceof MimeMultipart) {
    MultipartReport multipartReport = new MultipartReport(message.dataHandler.dataSource);
    def parsedText = multipartReport.textBodyPart.inputStream
    log.info "Body content : ${parsedText}"
}

So guys, this is how you can implement your own locally running SMTP server with very less effort!

Akash Sethi
Software Engineer
IntelliGrape Software Pvt. Ltd.
akash@intelligrape.com
My LinkedIn

FOUND THIS USEFUL? SHARE IT

comments (5)

  1. Kousalya

    log4j is not working for me. There is an error saying that,

    error: ‘;’ expected
    [javac] log.info “DATA”;

    It would be helpful if you provide solution for this error.

    Reply
  2. eventy

    One thing I’d like to say is the fact that before buying more computer system memory, look at the machine directly into which it can be installed. If your machine is usually running Windows XP, for instance, the particular memory ceiling is 3.25GB. Adding above this would basically constitute some sort of waste. Make sure one’s motherboard can handle the actual upgrade volume, as well. Thanks for your blog post.

    Reply
  3. oparkanily

    Woah! I’m really enjoying the template/theme of this blog. It’s simple, yet effective. A lot of times it’s challenging to get that “perfect balance” between usability and visual appeal. I must say that you’ve done a very good job with this. Additionally, the blog loads super quick for me on Opera. Outstanding Blog!

    Reply
  4. FreeFollower|FollowerGratis|

    I believe it is one of the most considerable facts for me. Using this program . pleased examining a person’s post. But desire to remarks upon quite a few popular items, The site style is a plus, a reports is in fact wonderful : Debbie. Good practice, best wishes

    Reply

Leave a comment -