Attaching reports to emails

Hi,

I’m currently trying to find a way to programmatically attach reports to emails to be sent to users. This probably involves multiple parts, but:

  1. How can I generate a report programmatically and be able to persist the report in order to…
  2. Add the report as a file attachment on emails that will be sent to users.

Hope this makes sense, any help is appreciated, thanks.

Hi Kuo,

The code snippet below is what I used to do exactly what you are asking. Sorry that I cannot send you all of the code but it will point you in the right direction.

Please note that I used the Email Templates ADDON as well as the Reporting module.

    @Inject
    protected Persistence persistence;
    @Inject
    private DataManager dataManager;
    @Inject
    private ReportService reportService;
    @Inject
    EmailTemplatesAPI emailTemplatesAPI;


    public void createAttachmentFromReport(Job job, boolean sendEmail) {
        Map<String, Object> reportParams = new HashMap<>();
        reportParams.put("job", job);


        FileDescriptor fd = reportService.createAndSaveReport(
                "REPORT_CODE",
                "REPORT_TEMPLATE_CODE",
                reportParams,
                "Job-Order-Report");


        // Create attachment record :
        CommitContext commitContext = new CommitContext();
        JobAttachment jobAttachment = dataManager.create(JobAttachment.class);
        jobAttachment.setDate(new Date());
        jobAttachment.setTitle("Job Order");
        jobAttachment.setJob(job);
        jobAttachment.setFileDescriptor(fd);
        commitContext.addInstanceToCommit(jobAttachment);
        dataManager.commit(commitContext);

        if (sendEmail) {
            // Send email to recipients:
            emailNow(job);
        }
    }

    public void emailNow(Job job) {
        String sendTo = "me@yahoo.com, you@yahoo.com";
        String templateCode = "EMAIL_TEMPLATE_CODE";

        Map<String, Object> reportParams = new HashMap<>();
        reportParams.put("job", job);

        if (StringUtils.isNotBlank(sendTo)) {
            try {
                emailTemplatesAPI.buildFromTemplate(templateCode)
                        .setTo(sendTo)
                        .setBodyParameter("job", job)
                        .setAttachmentParameters("REPORT_CODE", reportParams)
						.setAttachmentFiles(files)	// List of files
                        .sendEmailAsync();
            } catch (TemplateNotFoundException | ReportParameterTypeChangedException e) {
                LOG.warn(e.getMessage());
            }
        }
    }
1 Like

Thanks for the code sample! I am just using the core emailer API, but I’ve found a way to attach the report with it.