safeer-pdf-generator
Version:
Framework-agnostic PDF generation library with chunking, merging, S3 upload, and email delivery
297 lines (260 loc) • 8.67 kB
JavaScript
/**
* Enhanced Email Configuration Examples
* This file demonstrates the improved email functionality in @safeersoft/@safeersoft/pdf-reporter v1.0.3+
*/
const { generatePdf, testEmailConnection, validateEmailConfig, applySmartEmailDefaults } = require('@safeersoft/@safeersoft/pdf-reporter');
// Example 1: Test email connection before generating PDF
async function testEmailBeforeGeneration() {
const emailConfig = {
to: 'recipient@example.com',
smtp: {
host: 'smtp.gmail.com',
// Note: port and secure will be auto-configured for Gmail
auth: {
user: 'your-email@gmail.com',
pass: 'your-app-password' // Use App Password for Gmail
}
}
};
console.log('Testing email connection...');
const testResult = await testEmailConnection(emailConfig);
if (testResult.success) {
console.log('✅ Email connection successful!');
console.log('Details:', testResult.details);
// Now generate and send PDF
await generatePdfWithEmail(emailConfig);
} else {
console.error('❌ Email connection failed:', testResult.error);
console.log('Connection details:', testResult.details);
}
}
// Example 2: Smart email defaults - automatic configuration based on provider
async function demonstrateSmartDefaults() {
const configs = [
{
to: 'test@example.com',
smtp: {
host: 'smtp.gmail.com',
// Port and secure will be auto-configured
auth: { user: 'user@gmail.com', pass: 'app-password' }
}
},
{
to: 'test@example.com',
smtp: {
host: 'smtp.outlook.com',
// Port and secure will be auto-configured
auth: { user: 'user@outlook.com', pass: 'password' }
}
},
{
to: 'test@example.com',
smtp: {
host: 'smtp.sendgrid.net',
// Port and secure will be auto-configured
auth: { user: 'apikey', pass: 'your-sendgrid-api-key' }
}
}
];
for (const config of configs) {
console.log('\nBefore smart defaults:', config.smtp);
try {
// Apply smart defaults
applySmartEmailDefaults(config);
console.log('After smart defaults:', config.smtp);
// Test the connection
const result = await testEmailConnection(config);
console.log(`Connection test: ${result.success ? '✅' : '❌'}`);
if (!result.success) {
console.log('Error:', result.error);
}
} catch (error) {
console.error('Configuration error:', error.message);
}
}
}
// Example 3: Enhanced error handling
async function demonstrateErrorHandling() {
const badConfigs = [
{
name: 'Wrong port for SSL',
config: {
to: 'test@example.com',
smtp: {
host: 'smtp.gmail.com',
port: 465,
secure: false, // This will trigger validation error
auth: { user: 'user', pass: 'pass' }
}
}
},
{
name: 'SSL on wrong port',
config: {
to: 'test@example.com',
smtp: {
host: 'smtp.gmail.com',
port: 25,
secure: true, // This will trigger validation error
auth: { user: 'user', pass: 'pass' }
}
}
}
];
for (const { name, config } of badConfigs) {
console.log(`\nTesting: ${name}`);
try {
validateEmailConfig(config);
console.log('✅ Configuration valid');
} catch (error) {
console.log('❌ Configuration error:', error.message);
}
}
}
// Example 4: Auto-correction demonstration
async function demonstrateAutoCorrection() {
const configs = [
{
to: 'test@example.com',
smtp: {
host: 'smtp.gmail.com',
port: 465,
// secure is undefined - will be auto-corrected to true
auth: { user: 'user', pass: 'pass' }
}
},
{
to: 'test@example.com',
smtp: {
host: 'smtp.gmail.com',
port: 587,
// secure is undefined - will be auto-corrected to false
auth: { user: 'user', pass: 'pass' }
}
}
];
for (const config of configs) {
console.log('\nBefore auto-correction:', JSON.stringify(config.smtp, null, 2));
try {
validateEmailConfig(config);
console.log('After auto-correction:', JSON.stringify(config.smtp, null, 2));
} catch (error) {
console.error('Error:', error.message);
}
}
}
// Example 5: Generate PDF with enhanced email configuration
async function generatePdfWithEmail(emailConfig) {
const options = {
title: 'Enhanced Email Test Report',
data: [
{ id: 1, name: 'John Doe', email: 'john@example.com', status: 'Active' },
{ id: 2, name: 'Jane Smith', email: 'jane@example.com', status: 'Pending' },
{ id: 3, name: 'Bob Johnson', email: 'bob@example.com', status: 'Inactive' }
],
columns: [
{ key: 'id', title: 'ID', width: 50 },
{ key: 'name', title: 'Name', width: 150 },
{ key: 'email', title: 'Email', width: 200 },
{ key: 'status', title: 'Status', width: 100 }
],
email: {
...emailConfig,
subject: 'Your Enhanced PDF Report is Ready!',
template: (context) => `
<h2>Hello!</h2>
<p>Your report "${context.title}" has been generated with enhanced email features.</p>
<p>Generated at: ${context.generatedAt}</p>
<p>File size: ${context.fileSizeMB} MB</p>
<p>This email was sent using the improved SMTP configuration validation.</p>
`
}
};
try {
console.log('Generating PDF with enhanced email configuration...');
const result = await generatePdf(options);
if (result.email?.sent) {
console.log('✅ PDF generated and email sent successfully!');
console.log('Email message ID:', result.email.messageId);
} else {
console.log('❌ PDF generated but email failed:', result.email?.error);
}
return result;
} catch (error) {
console.error('PDF generation failed:', error.message);
throw error;
}
}
// Example 6: Complete workflow with validation and testing
async function completeEmailWorkflow() {
console.log('=== Complete Enhanced Email Workflow ===\n');
// Step 1: Create configuration with smart defaults
const emailConfig = {
to: 'recipient@example.com',
from: 'reports@yourcompany.com',
smtp: {
host: 'smtp.gmail.com',
// Smart defaults will be applied automatically
auth: {
user: 'your-email@gmail.com',
pass: 'your-app-password'
}
}
};
try {
// Step 2: Apply smart defaults
console.log('1. Applying smart email defaults...');
applySmartEmailDefaults(emailConfig);
console.log('Smart defaults applied:', emailConfig.smtp);
// Step 3: Validate configuration
console.log('\n2. Validating email configuration...');
validateEmailConfig(emailConfig);
console.log('✅ Configuration is valid');
// Step 4: Test connection
console.log('\n3. Testing email connection...');
const connectionTest = await testEmailConnection(emailConfig);
if (!connectionTest.success) {
throw new Error(`Connection test failed: ${connectionTest.error}`);
}
console.log('✅ Connection test successful');
console.log('Provider details:', connectionTest.details);
// Step 5: Generate and send PDF
console.log('\n4. Generating PDF with email...');
const result = await generatePdfWithEmail(emailConfig);
console.log('\n✅ Complete workflow successful!');
console.log(`PDF: ${result.pageCount} pages, ${(result.sizeBytes / 1024 / 1024).toFixed(2)}MB`);
console.log(`Email: ${result.email?.sent ? 'Sent' : 'Failed'}`);
} catch (error) {
console.error('\n❌ Workflow failed:', error.message);
}
}
// Run examples
async function runExamples() {
console.log('🚀 Enhanced Email Configuration Examples\n');
try {
await demonstrateSmartDefaults();
console.log('\n' + '='.repeat(50) + '\n');
await demonstrateErrorHandling();
console.log('\n' + '='.repeat(50) + '\n');
await demonstrateAutoCorrection();
console.log('\n' + '='.repeat(50) + '\n');
// Uncomment to test with real email configuration
// await completeEmailWorkflow();
} catch (error) {
console.error('Example failed:', error);
}
}
// Export functions for individual testing
module.exports = {
testEmailBeforeGeneration,
demonstrateSmartDefaults,
demonstrateErrorHandling,
demonstrateAutoCorrection,
generatePdfWithEmail,
completeEmailWorkflow,
runExamples
};
// Run if called directly
if (require.main === module) {
runExamples();
}