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
            Thread.currentThread().setContextClassLoader(javax.mail.Session.class.getClassLoader());

            Email email = new SimpleEmail();
            email.setHostName(mailHost);
            email.setSmtpPort(mailPort);
            email.setFrom(mailSender);
            email.addTo(receiver);
            email.setSubject(subject);
            email.setMsg(message);

            email.send();
        }
        catch(Exception e) {
            logger.error("E-mail konnte nicht versandt werden.", e);
        }
        finally {
            // set original classloader
            Thread.currentThread().setContextClassLoader(cl);
        }
    }
}

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 {

    ...

    @Override
    public void updated(Dictionary<String, ?> properties) throws ConfigurationException {
        if (properties == null || properties.isEmpty()) {
            return;
        }
        
        Object value = properties.get("mail.host");
        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();
        }
    }
}