Wednesday, June 15, 2011

JRapid Quick Tip 4: Easily Send Emails in Controller Actions

It’s a common requirement to send emails when certain action is performed in a web application. For example, send an email to a customer when his order has been confirmed.

This can be implemented in a few simple steps when using JRapid. All you need to do is import the Email template, configure your JRapid application to use an available outgoing email server and add a few lines of code.

Suppose we have a basic CustomerOrder entity that registers customer orders and has a property indicating if it has been confirmed. When this property is changed to “Confirmed”, an email should be sent to the corresponding customer notifying about this.

The entity definition:

<entity label="Customer Order" menu="Menu" name="CustomerOrder">
        <property display="primary" label="Customer" name="customer"/>
        <property display="primary" label="Email" name="email"/>
        <property label="Description" name="description" type="text"/>
        <property label="Confirmed" name="confirmed" type="boolean"/>
    </entity>


We add the SMTP configuration to the jrapid.properties files. In this case I’m using a Gmail account:



Import the Email template. Click on the Add-ons -> Import Template.


Select the Email template to import it.


This templates adds the Email entity that uses the Email stereotype. This adds the necessary methods for sending the message. Read more about email stereotype here

The last step is to add the Java code to the store method of the CustomerServices class to send the email. This is a simple implementation that is by no means production ready!




Now, when a user marks a customer order as confirmed and submits the changes, the web app sends an email notifying the customer.



No comments:

Post a Comment