User Tools

Site Tools


This is an old revision of the document!

MailService in OSGi

OSGi itself doesn't provide you with a mail service and most osgi container don't provide one either. But it is not very difficult to write a simple mail service yourself.

Step 1: Install Apache Commons Email

Apache Commons Email does the heavy lifting when it comes to sending emails.

install mvn:org.apache.commons/commons-email/1.3.3

Step 2: MailService

This sample service is all you need for a start:

public class MailService {

    public void send(String subject, String message, String receiver) {
        // backup classloader
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        try {
            //  switch to tccl so that javamail can resolve data content handlers

            Email email = new SimpleEmail();

        catch(Exception e) {
            logger.error("E-mail konnte nicht versandt werden.", e);
        finally {
            // set original classloader

You need to take of classloaders as the javax.mail package from Sun/Oracle does some assumptions on classloaders which are not met in an OSGi environment.

Step 3 : Configuration

You probably want to keep the service configurable. So you best use the ConfigAdmin for configuration and implement the ManagedService interface.

public class MailService implements IMailService, ManagedService {

  public void updated(Dictionary<String, ?> properties) throws ConfigurationException {
      if (properties == null || properties.isEmpty()) {
      Object value = properties.get("");
      if (value != null) {
          mailHost = value.toString();
      value = properties.get("mail.port");
      if (value != null) {
          mailPort = Integer.parseInt(value.toString());
      value = properties.get("mail.sender");
      if (value != null) {
          mailSender = value.toString();

} </sxh>

mailservice_for_osgi.1455885623.txt.gz · Last modified: 2016/02/19 12:40 by mihael