3.9.2.4. Email Sending Guide
This section contains a practical guide on sending emails using the CUBA email sending mechanism.
Let’s consider the following task:
-
There are the
NewsItem
entity and theNewsItemEdit
screen. -
The
NewsItem
entity contains the following attributes:date
,caption
,content
. -
We want to send emails to some addresses every time a new instance of
NewsItem
is created through theNewsItemEdit
screen. An email should containNewsItem.caption
as a subject and the message body should be created from a template includingNewsItem.content
.
-
Add the following code to
NewsItemEdit.java
:@UiController("sample_NewsItem.edit") @UiDescriptor("news-item-edit.xml") @EditedEntityContainer("newsItemDc") @LoadDataBeforeShow public class NewsItemEdit extends StandardEditor<NewsItem> { private boolean justCreated; (1) @Inject protected EmailService emailService; @Inject protected Dialogs dialogs; @Subscribe public void onInitEntity(InitEntityEvent<NewsItem> event) { (2) justCreated = true; } @Subscribe(target = Target.DATA_CONTEXT) public void onPostCommit(DataContext.PostCommitEvent event) { (3) if (justCreated) { dialogs.createOptionDialog() (4) .withCaption("Email") .withMessage("Send the news item by email?") .withType(Dialogs.MessageType.CONFIRMATION) .withActions( new DialogAction(DialogAction.Type.YES) { @Override public void actionPerform(Component component) { sendByEmail(); } }, new DialogAction(DialogAction.Type.NO) ) .show(); } } private void sendByEmail() { (5) NewsItem newsItem = getEditedEntity(); EmailInfo emailInfo = EmailInfoBuilder.create() .setAddresses("john.doe@company.com,jane.roe@company.com") (6) .setCaption(newsItem.getCaption()) (7) .setFrom(null) (8) .setTemplatePath("com/company/demo/templates/news_item.txt") (9) .setTemplateParameters(Collections.singletonMap("newsItem", newsItem)) (10) .build(); emailService.sendEmailAsync(emailInfo); } }
1 - indicates that a new item was created in this editor 2 - this method is invoked when a new item is initialized 3 - this method is invoked after commit of data context 4 - if a new entity was saved to the database, ask a user about sending an email 5 - queues an email for sending asynchronously 6 - recipients 7 - subject 8 - the from
address will be taken from the cuba.email.fromAddress application property9 - body template path 10 - template parameters As you can see, the
sendByEmail()
method invokes theEmailService
and passes theEmailInfo
instance describing the the messages. The body of the messages will be created on the basis of thenews_item.txt
template. -
Create the body template file
news_item.txt
in thecom.company.demo.templates
package of the core module:The company news: ${newsItem.content}
This is a Freemarker template which will use parameters passed in the
EmailInfo
instance (newsItem
in this case). -
Launch the application, open the
NewsItem
entity browser and click Create. The editor screen will be opened. Fill in the fields and press OK. The confirmation dialog with the question about sending emails will be shown. Click Yes. -
Go to the Administration > Email History screen of your application. You will see two records (by the number of recipients) with the
Queue
status. It means that the emails are in the queue and not yet sent. -
To process the queue, set up a scheduled task. Go to the Administration > Scheduled Tasks screen of your application. Create a new task and set the following parameters:
-
Bean Name -
cuba_Emailer
-
Method Name -
processQueuedEmails()
-
Singleton - yes (this is important only for a cluster of middleware servers)
-
Period, sec - 10
Save the task and click Activate on it.
If you did not set up the scheduled tasks execution for this project before, nothing will happen on this stage - the task will not be executed until you start the whole scheduling mechanism.
-
-
Open the
modules/core/src/app.properties
file and add the following property:cuba.schedulingActive = true
Restart the application server. The scheduling mechanism is now active and invokes the email queue processing.
-
Go to the Administration > Email History screen. The status of the emails will be
Sent
if they were successfully sent, or, most probably,Sending
orQueue
otherwise. In the latter case, you can open the application log inbuild/tomcat/logs/app.log
and find out the reason. The email sending mechanism will take several (10 by default) attempts to send the messages and if they fail, set the status toNot sent
. -
The most obvious reason that emails cannot be sent is that you have not set up the SMTP server parameters. You can set the parameters in the database through the
app-core.cuba:type=Emailer
JMX bean or in the application properties file of your middleware. Let us consider the latter. Open themodules/core/src/app.properties
file and add the required parameters:cuba.email.fromAddress = do-not-reply@company.com cuba.email.smtpHost = mail.company.com
Restart the application server. Go to Administration > JMX Console, find the
Emailer
JMX bean and try to send a test email to yourself using thesendTestEmail()
operation. -
Now your sending mechanism is set up correctly, but it will not send the messages in the
Not sent
state. So you have to create anotherNewsItem
in the editor screen. Do it and then watch how the status of new messages in the Email History screen will change toSent
.