Automating Workflows: Sending Weekly Reports
Jared Drueco | July 14, 2022
This week I created an automated workflow that emails a report to a user weekly. To do this, I used a ‘Codeunit’ to implement the logic and a ‘Job Queue’ to schedule the task at hand. Although there are built-in workflows in Business Central, I found that writing an AL script.
Codeunit For Sending Emails in AL
Before I created the codeunit, I had to set up SMTP mail in Business Central. To do this, I went to the ‘Email Setup’ page, and filled out the information from the email account that I planned to send from.
To start off, we create a codeunit that holds a procedure which gets called when the codeunit is run (It is run when the job queue calls it). We also initialize variables necessary to save a report and send it as an attachment via email.
![](/Products/Power-Platforms/Automating-Workflows-Sending-Weekly-Reports/1 1.png)
The report that we are sending is the ‘Vendor Trial Balance’ report which extracts data from a Vendor record. In this case, we filter out a vendor with a ‘Number’ ID of 10000 and get their information within a certain period of time (their first Fiscal period).
![](/Products/Power-Platforms/Automating-Workflows-Sending-Weekly-Reports/2 1.png)
Now we create an email message using the built-in EmailMsg.Create() method. We pass in the following parameters: the email account we send to, the email subject, the email body, and a boolean to determine if the body is HTML formatted.
![](/Products/Power-Platforms/Automating-Workflows-Sending-Weekly-Reports/3 1.png)
Next, we use a temporary BLOB to create an out-stream and use the Report.SaveAs() method to write our report to. Then, using an in-stream to read the report, we can attach it to the EmailMsg we created above. Finally, using the Email.send() method, we can send the EmailMsg object we have been creating.
![](/Products/Power-Platforms/Automating-Workflows-Sending-Weekly-Reports/4 1.png)
Job Queue for the Codeunit
After compiling and deploying our new codeunit, we can head over to the ‘Job Queue Entries’ page to create a new job queue. All we have to do on the Job queue page is to specify the codeunit and the frequency we perform that codeunit.
For my task, I want it to be weekly starting from the day I created it, so I use the formula: ‘1W’.
![](/Products/Power-Platforms/Automating-Workflows-Sending-Weekly-Reports/5 1.png)
The last thing we need to make sure of, is to set the Status to ‘Ready’ so Business Central knows that we are done editing the job queue.
![](/Products/Power-Platforms/Automating-Workflows-Sending-Weekly-Reports/6 1.png)