send a mail from drools

443 Views Asked by At

I'm create a project using Drools + Sprint boot.

I need trigger the mail when LHS satisfied. How can i trigger a mail from drl.

Let's say

 dialect "mvel"
  rule "mail trigger acoount hold customers"
   timer (cron: 0 0/30 * * * ?)
  when
        $customer: Customer( status == "hold") 
       then
        // send the account hold mail notification to customers registered mail address
  end

How can integrate the mail service with Drools.?

Suggestions are welcome.

Thanks in advance

1

There are 1 best solutions below

3
tarilabs On

You could integrate Drools with Apache Camel: using Drools you define the rule for email sending, and Camel manages the actual email forwarding which can also properly manage potential SLAs with SMTP servers (for example via throttling).

Your rule in this architecture would look ~like:

rule "mail trigger account hold customers"
timer (cron: 0 0/30 * * * ?)
when
    $customer: Customer( status == "hold") 
then
    // send the account hold mail notification to customers registered mail address
    Map<String, Object> headers = new HashMap<String, Object>();
    headers.put("To", $customer.getEMail());
    headers.put("From", new javax.mail.internet.InternetAddress("[email protected]", "Drools"));
    headers.put("Subject", "Account hold mail notification");

    StringBuilder sb = new StringBuilder();
    sb.append("<html><body><h1>Account hold mail notification</h1>");
    sb.append("lorem ipsum");
    sb.append("</body></html>");

    try {
        camel.sendRouteBodyHeaders("direct:smtp", sb.toString(), headers);
    } catch (Exception e) {
        // TODO email was not sent
    }
end

and you would only need to manage the camel.sendRouteBodyHeaders(..) part to be properly configured based on your SB environment. Additionally, camel could be a Drools global that is injected by Spring with the Camel's ProducerTemplate, this is really up to you.

This solution guarantees Drools is only used for the purpose of defining the business requirement when an email need to be sent, while the integration logic is performed by Apache Camel.

If you want to get more details, also for equivalent/analogous JavaEE or MicroProfile environment, some pointers might be found in old post.