0

I'm having trouble with this function:

const nodemailer = require("nodemailer");
const AWS = require("aws-sdk");
require("dotenv").config();

exports.sendMail = async (obj) => {
    let sendResult = null;
    const transporter = nodemailer.createTransport({
        SES: new AWS.SES({
            apiVersion: "2010-12-01",
            accessKeyId: process.env.AWS_ACCESS_KEY_ID,
            secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
            region: process.env.AWS_REGION,
        }),
    });

    transporter.sendMail(
        {
            from: process.env.MAIL_SENDER_ADDRESS,
            to: obj.receiver,
            subject: "Mail send success!",
            text: "Hello World"
        },
        (err, info) => {
            if (err) {
                sendResult = false;
                console.log(err);
            } else {
                sendResult = true;
                console.log("sendEmail: " + JSON.stringify(info.envelope));
                console.log(info.messageId);
            }
        }
    );

    return sendResult;
};

I want to make the function 'sendResult' return true after 'transporter.sendMail()' sends mail, but the function 'sendMail' always returns null.

Is there any solution?

Thanks in advance.

Gary Lee
  • 3
  • 2
  • Also definitely check here (which is imo a better dupe): https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron cc @Jamiec –  Oct 06 '21 at 16:12
  • @ChrisG indeed it is, I have added it to the dupe targets – Jamiec Oct 06 '21 at 16:16
  • As another pointer - You have marked your `sendMail` method `async` but you dont do any async work within it. That is part of the solution to your problem. You need to `await` something to make the `async` make sense. – Jamiec Oct 06 '21 at 16:17
  • @Jamiec I removed async and await in the function, but the problem still exists. – Gary Lee Oct 07 '21 at 07:52
  • @GaryLee yes, that wasnt the root of the problem (the linked duplicates explain how to fix that). – Jamiec Oct 07 '21 at 08:06
  • I put 'transporter.sendMail()' into try and catch, then the problem was solved. Thanks for your answers. – Gary Lee Oct 07 '21 at 09:11

0 Answers0