Streamlining Report Delivery: Attaching PDFs Directly to Emails
Clicking a link to download a report might seem like a small step, but in a busy work environment, every click saved improves efficiency. In the Hidrobombas Mérida CMMS project, we recently tackled this user experience hurdle, moving from email notifications containing only a link to service reports, to directly attaching the PDF report for immediate access.
The Problem: An Extra Step for Critical Information
Previously, when a service report was generated in our CMMS (Computerized Maintenance Management System), the system would send an email with a link to view the report. While functional, this introduced an additional step for users. They had to open the email, click the link, wait for the browser to open, and then download or view the PDF. This small friction point could add up over time, especially for high-volume users.
The Solution: Direct PDF Attachments
Our goal was to streamline this process by attaching the generated PDF report directly to the email. This enhancement significantly reduces the steps for users, allowing them to open the report instantly from their inbox. Achieving this required several key modifications across our backend services.
Key Implementation Details
1. Generating PDF as a Buffer
The first challenge was to render the PDF content into a format that could be attached to an email. Our existing pdfService was designed to generate PDFs and typically save them to disk or stream them directly as a response. We introduced a new method, buildReportPDFBuffer, which leverages PDFKit (or a similar PDF generation library) to collect the PDF stream into a Node.js Buffer.
// In pdfService.js
const PDFDocument = require('pdfkit');
async function buildReportPDFBuffer(reportId) {
return new Promise((resolve, reject) => {
const doc = new PDFDocument();
const buffers = [];
doc.on('data', buffers.push.bind(buffers));
doc.on('end', () => {
resolve(Buffer.concat(buffers));
});
doc.on('error', reject);
// Assume generateReportContent populates the PDF
generateReportContent(doc, reportId);
doc.end();
});
}
module.exports = { buildReportPDFBuffer };
This buildReportPDFBuffer function ensures that the PDF content is available in memory, ready to be passed to an email service.
2. Enhancing the Email Service for Attachments
Our emailService needed to be updated to accept and handle attachments. We modified its send() method to include an attachments parameter, which is an array of objects, each containing filename, content (the Buffer), and contentType. This required adapting the attachment format for each of our email providers (SMTP via Nodemailer, Brevo, and Resend).
// In emailService.js
async function send(to, subject, htmlContent, attachments = []) {
// Logic for each provider (simplified example for nodemailer)
const mailOptions = {
from: '[email protected]',
to,
subject,
html: htmlContent,
attachments: attachments.map(att => ({
filename: att.filename,
content: att.content,
contentType: att.contentType
}))
};
try {
// Example using an SMTP transport (e.g., Nodemailer)
await transporter.sendMail(mailOptions);
console.log('Email sent with attachment');
} catch (error) {
console.error('Failed to send email:', error);
throw error;
}
}
module.exports = { send };
3. Integrating into the Report Workflow
The sendServiceReportEmail function, responsible for orchestrating the email dispatch, was updated to leverage these new capabilities. It now first attempts to generate the PDF buffer. If successful, it passes this buffer as an attachment to the emailService.send() call. Crucially, if the PDF generation fails for any reason, the system is designed to gracefully fall back to sending the email without the attachment, still including the link to the report to prevent any blockage in the workflow.
// In serviceReportHandler.js
const pdfService = require('./pdfService');
const emailService = require('./emailService');
async function sendServiceReportEmail(reportId, recipientEmail) {
let attachments = [];
let emailBody = 'Your service report is ready. Click here to view: [Report Link]';
try {
const pdfBuffer = await pdfService.buildReportPDFBuffer(reportId);
attachments.push({
filename: `ServiceReport-${reportId}.pdf`,
content: pdfBuffer,
contentType: 'application/pdf'
});
emailBody = 'Your service report is ready. The PDF is attached to this email. If you cannot open it, please use this link: [Report Link]';
} catch (pdfError) {
console.warn(`Failed to generate PDF for report ${reportId}. Sending email with link only.`, pdfError);
// Fallback: emailBody remains with just the link
}
await emailService.send(recipientEmail, `Service Report ${reportId}`, emailBody, attachments);
}
4. Frontend Feedback
To complete the user experience, we also updated the WizardSuccessScreen (likely a React component in our frontend) to reflect this change. The modal now explicitly informs the user that the PDF report has been attached to the email, aligning the system's feedback with its new functionality.
Results
This update significantly improves the user experience by reducing friction in accessing critical service reports. Users no longer need to navigate away from their inbox to retrieve a report, leading to more efficient workflows. The robust error handling ensures that even if PDF generation encounters an issue, the user still receives the essential report link.
Next Steps
Future enhancements could include offering options for different attachment formats (e.g., CSV summary) or integrating a preview functionality within the email for specific report types.
Generated with Gitvlg.com