Mail MessageGateway is null
- January 11, 2016
- 15 replies
- 8747 views
I created a mail service class, which should use the CQ Mail Configuration.
However I compared my code to several samples from the Internet my service does not work, because
messageGatewayService.getGateway(...) always returns null. This is my simplified code:
------------------------------------------
import org.apache.commons.mail.Email;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.mail.SimpleEmail;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.day.cq.mailer.MessageGateway;
import com.day.cq.mailer.MessageGatewayService;
@Component(immediate = true)
@Service(MailService.class)
public class MailServiceImpl implements MailService {
private static final Logger LOGGER = LoggerFactory.getLogger(MailServiceImpl.class);
@Reference
private MessageGatewayService messageGatewayService;
@Override
public void sendMail(String subject, String mailText, List<String> recipients) {
LOGGER.info("Send mail");
try {
Email email = new SimpleEmail();
for (String recipient : recipients) {
email.addTo(recipient, recipient);
}
email.setSubject(subject);
email.setMsg(mailText);
MessageGateway<Email> messageGateway = messageGatewayService.getGateway(Email.class);
// --> returns null
MessageGateway<SimpleEmail> messageGateway1 = messageGatewayService.getGateway(SimpleEmail.class);
// --> returns null
MessageGateway<HtmlEmail> messageGateway2 = messageGatewayService.getGateway(HtmlEmail.class);
// --> returns null
//MessageGateway messageGateway3 = messageGatewayService.getGateway(com.day.cq.mailer.impl.DefaultMailService.class);
// --> deactivated in code, because DefaultMailService.class unknown
if (messageGateway!=null) {
messageGateway.send((Email) email);
} else {
LOGGER.error("Message gateway could not be retrieved.");
}
} catch(Exception ex) {
LOGGER.error("Error on sending mail.");
}
}
}
------------------------------------------
I tested the params used in my CQ Mail configuration in a different mail application and mails were sent out correctly, so the configuration seems not to be the problem.
When I debug the messageGatewayService class I can see it contains a map for gateway configurations which contains the CQ Mail configuration I defined in OSGI (see attachment).
So the messageGatewayService knows about my CQ Mail config. But it resists to deliver it to me :(
I noticed that the CQ Mail configuration in the gateway map is stored with key 'com.day.cq.mailer.impl.DefaultMailService' so it is the PID of the service.
But all examples I saw get the gateway via
MessageGateway<Email> messageGateway = messageGatewayService
.getGateway(Email.class) or
.getGateway(SimpleEmail.class) or
.getGateway(HtmlEmail.class)
which does not work for me?
Any idea?

