Sending compressed report before sending in email



  • I want to compress reports before sending them as attachment in the email.
    I am able to send the attachment in email by using following code, but facing issue while trying to compress them before sending. Please help.

     function afterRender(req, res, done) {
    var mailer = require('nodemailer');
    var fs= require('fs');
    var zlib = require('zlib');
    
    var compress = zlib.createGzip();
    var newFileName='a.gz';
    
    /*
    var writeStream = fs.createWriteStream("JournalDEV.png");
    writeStream.write(res.content);
    writeStream.end();
    */
    const streamifier = require('streamifier');
    
    var writestream = fs.createWriteStream(newFileName);
    var vv2 = streamifier.createReadStream(res.content.buffer).pipe(writestream);
    
    const transporter = mailer.createTransport({
    service: 'emailservice',
    auth: {
        user: 'sender@email.com',
        pass: 'SuperSecurePassword#' // naturally, replace both with your real credentials or an application-specific password
    }
    });
    const mailOptions = {
    from: 'sender@email.com',
    to: 'receiver@email.com',
    subject: 'Sending Chrome Image reports from jsReport',
    text: "See the attached report",
        html: "<b>See the attached report</b>",
        attachments: [
        {  
           content: vv2 
        }],
    };
    transporter.sendMail(mailOptions, function(error, info){
        transporter.close();
        if(error){
            console.log(error);
            return done(error);
        }
        else {
             console.log('Email sent: ' + info.response);
        }
        return done();
    });    
    

    }

    As it can be seen in screenshot, I tried to implement it using zlib, fs, streamifier, tried various combinations to achieve it, but still facing issue in compression. Any suggestion??


  • administrators

    Hi!

    i think there are some things wrong in your code, first the res.content is already a buffer so you don't need to access something like res.content.buffer, and then the other issue is that your vv2 variable ends up being a writable stream, and the attachment in the email expects a readable stream. the following should work for you

    const streamifier = require('streamifier');
    var vv2 = streamifier.createReadStream(res.content).pipe(compress);
    
    // ...the later in your nodemailer code..
    attachments: [
        {  
           filename: newFileName,
           content: vv2 
        }]
    


  • Hi Boris,

    Thanks for quick response, I am very new to js.
    I modified the code as per your suggestion, but still getting issue while trying to extract. The error is:
    Cannot open the file as archive, is not archive



  • It worked, thanks a lot Boris :)


Log in to reply
 

Looks like your connection to jsreport forum was lost, please wait while we try to reconnect.