Differences
This shows you the differences between two versions of the page.
— |
mailservice_for_osgi [2021/04/05 11:23] (current) |
||
---|---|---|---|
Line 1: | Line 1: | ||
+ | ====== MailService in OSGi ====== | ||
+ | OSGi itself doesn' | ||
+ | ===== Step 1: Install Apache Commons Email ===== | ||
+ | Apache Commons Email does the heavy lifting when it comes to sending emails. | ||
+ | |||
+ | install mvn: | ||
+ | |||
+ | |||
+ | ===== 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(" | ||
+ | } | ||
+ | finally { | ||
+ | // set original classloader | ||
+ | Thread.currentThread().setContextClassLoader(cl); | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | <note important> | ||
+ | |||
+ | ===== 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> | ||
+ | public class MailService implements IMailService, | ||
+ | |||
+ | ... | ||
+ | |||
+ | @Override | ||
+ | public void updated(Dictionary< | ||
+ | if (properties == null || properties.isEmpty()) { | ||
+ | return; | ||
+ | } | ||
+ | | ||
+ | Object value = properties.get(" | ||
+ | if (value != null) { | ||
+ | mailHost = value.toString(); | ||
+ | } | ||
+ | | ||
+ | value = properties.get(" | ||
+ | if (value != null) { | ||
+ | mailPort = Integer.parseInt(value.toString()); | ||
+ | } | ||
+ | | ||
+ | value = properties.get(" | ||
+ | if (value != null) { | ||
+ | mailSender = value.toString(); | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | {{tag> |