User Tools

Site Tools


This is an old revision of the document!

A PCRE internal error occured. This might be caused by a faulty plugin

====== 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: <sxh java> 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); } } } </sxh> <note important>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.</note> ===== Step 3 : Configuration ===== You probably want to keep the service configurable. So you best use the ConfigAdmin for configuration and implement the ManagedService interface. <sxh java> </sxh> 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(""); 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> {{tag>java osgi}}

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