Send email after upload is complete?

Asked

Viewed 69 times

0

I have the following function for sending emails using the nodemailer and a Hapijs server:

let data = request.payload;
    if (data.file) {
        let name = data.file.hapi.filename;
        let caminho = __dirname + "/uploads/" + name;
        let file = fs.createWriteStream(caminho);

        file.on('error', function (err) {
            console.error(err)
        });

        data.file.pipe(file);

        data.file.on('end', function (err) {
            mailOptios.attachments.push({
                filename: name,
                path: caminho //push nos anexos quando o upload está concluido
            });
            reply('Upload Concluído');
        });
    }


    let destinatario = '[email protected]';
    let ass = 'teste com anexo';
    let email = 'Teste com anexo';
    let mailOptios = {
        from: usuario, //usuário está definido mais acima no código
        to: destinatario, //não incluí usuário aqui por questões de privacidade
        subject: ass,
        text: email,
        attachments: [
        ]
    };

    console.log(mailOptios);
    transporter.sendMail(mailOptios, function (err, info) {
        if (err){
            console.log(err)
        } else {
            console.log('Enviado! ' + info.response);
            return reply.response('Enviou')
        }
    })

However, the process is taking place asynchronously and the email is being sent before the complete upload of the attachment.

How to make this function synchronous or ensure the attachment is ready before sending the email?

  • You cannot play the "Transporter.sendmail(...);" function after "reply('Upload Completed');", simply ?

  • After small tests and adaptations worked perfectly, please add an answer so I can accept it and possibly help other people who might have this doubt...

1 answer

1


You have to put all this code here:

let destinatario = '[email protected]';
let ass = 'teste com anexo';
let email = 'Teste com anexo';
let mailOptios = {
    from: usuario, //usuário está definido mais acima no código
    to: destinatario, //não incluí usuário aqui por questões de privacidade
    subject: ass,
    text: email,
    attachments: [
    ]
};

console.log(mailOptios);
transporter.sendMail(mailOptios, function (err, info) {
    if (err){
        console.log(err)
    } else {
        console.log('Enviado! ' + info.response);
        return reply.response('Enviou')
    }
})

Within the data.file.on('end'), this because the on is an event, so he is sending a message saying that the upload has ended. I advise you to turn this all into a function sendMail and send the required parameters within the event end

Browser other questions tagged

You are not signed in. Login or sign up in order to post.