Speed up Nodemailer send Emails

Viewed 28

I've got a NodeJS code something like this: (Netlify)

const sendEmail = require('./sendmail')
async function checkout() {
    try {
        await someFunction()
    } catch(e) {}
    try {
        await someOtherFunction()
    } catch(e) {}
    try {
        await sendEmail.sendCustomer(subject, body, to)  // await or not?
        await sendEmail.sendOurself(subject, body, to)   // await or not?
    }
    finally {
        return {
            statusCode: 200
        }
    }
}

And the function to send Emails:

const nodemailer = require('nodemailer')
async function sendEmail(subject, body, to) {

    const transporter = nodemailer.createTransport({
        host: HOST,
        port: PORT,
        secure: SECURE,
        auth: { user: AUTH.user, pass: AUTH.pass,}
    });

    const mailOptions = {
        from: AUTH.user,
        to: to,
        subject: subject,
        html: body,
    };

    return await transporter.sendMail(mailOptions)
};

exports.sendEmail = sendEmail

Problem is, the function to send emails, takes forever. sometimes 5 seconds, sometimes up to 12 seconds for both Emails.

How could I speed this up? As you can see, I don't really care about the response from nodemailer. So I tried to removed the await in the last try-block and made the function sendEmail synchronous. But then, the emails doesn't get sent. I think it's because the function stops running when I return 200. How could I speed up this process?

1 Answers

I've ended up with Promise.all instead of awaiting.

Related