Hi guys ,
There is a requirement to send email to users with query results as an attachment from backend . Query result contains pages > 200 .
My doubt is what will be easier to implement in attachment ,CSV or HTML and how to implement it ?
Thanks in advance .
Views
Replies
Total Likes
Hello @newbie34
It would easier to create an Excel with the details. And send the details as an attachment.
Set Up QueryBuilder API:
Example Code to Fetch Results:
Map<String, String> queryMap = new HashMap<>();
queryMap.put("path", "/content/dam");
queryMap.put("type", "dam:Asset");
queryMap.put("property", "jcr:content/metadata/dc:title");
queryMap.put("property.operation", "exists");
Query query = queryBuilder.createQuery(PredicateGroup.create(queryMap), session);
SearchResult result = query.getResult();
Process the Results:
SearchResult
to extract the desired properties:for (Hit hit : result.getHits()) {
String path = hit.getPath();
String title = hit.getProperties().get("jcr:content/metadata/dc:title", String.class);
// Process or store results
}
Set Up Apache POI:
pom.xml
if using Maven):
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.3</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
Create Excel File:
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Assets");
// Add header row
Row headerRow = sheet.createRow(0);
headerRow.createCell(0).setCellValue("Path");
headerRow.createCell(1).setCellValue("Title");
// Add data rows
int rowNum = 1;
for (Hit hit : result.getHits()) {
Row row = sheet.createRow(rowNum++);
row.createCell(0).setCellValue(hit.getPath());
row.createCell(1).setCellValue(hit.getProperties().get("jcr:content/metadata/dc:title", String.class));
}
// Write to file
try (FileOutputStream fileOut = new FileOutputStream("assets.xlsx")) {
workbook.write(fileOut);
} catch (IOException e) {
e.printStackTrace();
} finally {
workbook.close();
}
Configure ACS Commons Email Service:
Use ACS Commons Email API to Send Emails:
@Reference
private EmailService emailService;
Map<String, String> emailParams = new HashMap<>();
emailParams.put("to", "recipient@example.com");
emailParams.put("from", "sender@example.com");
emailParams.put("subject", "AEM Query Results");
emailParams.put("body", "The attached Excel file contains the results.");
// Attach the Excel file
File file = new File("assets.xlsx");
if (file.exists()) {
emailParams.put("attachment", file.getAbsolutePath());
}
EmailService.Config config = emailService.newConfig(emailParams);
emailService.sendEmail(config);
A CSV or Excel report will be better for readability compared to HTML. Displaying HTML on the email or attaching HTML will be little tedious as you might have to fix multiple UI issues and might not be readable.
Views
Replies
Total Likes