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 ?
– Bruno
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...
– LeonardoEbert