Я хочу отправлять почту через SendGrid на определенный идентификатор, который я получаю из запроса sequelize, но письма не могут быть отправлены на полученную почту из таблицы - PullRequest
0 голосов
/ 15 января 2020
Leave.create({
        leaveType: leaveType,
        fromDate: fromDate,
        toDate: toDate,
        emailId: emailId,
        reason: reason,
        reportTo: reportTo,
        userId: userId
    })
    LeaveReq.create({
        empName: userId,
        appliedFrom: fromDate,
        apliedTo: toDate,
        leaveType: leaveType,
        status: req.body.status,
        reqTo: reportTo
    })
    .then(result =>{
        transporter.sendMail({
            to: EmpList.findOne({attributes:['profEmail'],where:{firstName: reportTo}}),
            from: 'CTHRM@coretechies.com,',
            subject: 'You recieved a user request',
            html: `<p>please check your app to take action on this request</p>
            `
          });
        res.status(201).json({message: 'leave updated', userId: result.id, status: '1'})
    })
    .catch(err =>{
        if(!err.statusCode){
            err.statusCode = 500;
        }
        next(err);
    });

я получаю эту ошибку

node:9440) UnhandledPromiseRejectionWarning: Error: Missing destination email
    at Request._callback (D:\ct-work\cthrm_api\node_modules\sendgrid\lib\sendgrid.js:88:25)
    at Request.self.callback (D:\ct-work\cthrm_api\node_modules\request\request.js:185:22)
    at Request.emit (events.js:210:5)
    at Request.<anonymous> (D:\ct-work\cthrm_api\node_modules\request\request.js:1161:10)
    at Request.emit (events.js:210:5)
    at IncomingMessage.<anonymous> (D:\ct-work\cthrm_api\node_modules\request\request.js:1083:12)
    at Object.onceWrapper (events.js:299:28)
    at IncomingMessage.emit (events.js:215:7)
    at endReadableNT (_stream_readable.js:1200:12)
    at processTicksAndRejections (internal/process/task_queues.js:80:21)
(node:9440) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function

без блока catch или отклоняя обещание, которое не было обработано с помощью .catch (). (идентификатор отклонения: 1) (узел: 9440) [DEP0018] Предупреждение об устаревании: отклонения необработанного обещания устарели. В будущем отклонения обещания, которые не обрабатываются, завершат процесс Node.js с ненулевым кодом завершения.

предложит какой-либо метод для отправки почты через запрос sql в 'to' раздел

1 Ответ

1 голос
/ 15 января 2020

У вас есть две проблемы в этом коде:

1) Для свойства sendMail поддерживаются типы string | string[].

Т.е. вы можете отправить "a@domain, b@domain" или ["a@domain", "b@domain"] ,

Возвращаемое значение

EmpList.findOne({attributes:['profEmail'],where:{firstName: reportTo}});

равно promise<pending>, поскольку вы не ожидаете результата. Вы фактически назначаете to на: Promise<pending>, который не является: string | string[].

Если вы будете использовать функцию async, вы можете сделать:

const emp = await EmpList.findOne({attributes:['profEmail'],where:{firstName: reportTo}})

transporter.sendMail({
    to: emp,
    from: 'CTHRM@coretechies.com,',
    subject: 'You recieved a user request',
    html: `<p>please check your app to take action on this request</p>`
});
res.status(201).json({message: 'leave updated', userId: result.id, status: '1'})

и затем присвойте res to свойству sendMail

2) sendMail также возвращает обещание, так что вы должны дождаться результата обещания и поймать ошибку, если она была выдана:

transporter.sendMail({
        to: EmpList.findOne({attributes:['profEmail'],where:{firstName: reportTo}}),
        from: 'CTHRM@coretechies.com,',
        subject: 'You recieved a user request',
        html: `<p>please check your app to take action on this request</p>`
})
.then((data) => conosle.log(data))
.catch((e) => console.error(e);

Вот почему вы получаете:

(узел: 9440) UnhandledPromiseRejectionWarning: необработанное отклонение обещания. Эта ошибка возникла либо из-за того, что внутри асинхронной функции возникла ошибка без блока catch, либо из-за отклонения обещания, которое не было обработано с помощью .catch (). (идентификатор отклонения: 1) (узел: 9440) [DEP0018] Предупреждение об устаревании: отклонения необработанного обещания устарели. В будущем отклонения обещаний, которые не обрабатываются, завершат процесс Node.js с ненулевым кодом завершения.

EDIT :

Полный пример с функцией асин c. предположим, что весь этот код написан под функцией, предположим, что эта функция называется create.

async function create(req, res, next) {
    try {
        let leaveRes = await Leave.create({
            leaveType: leaveType,
            fromDate: fromDate,
            toDate: toDate,
            emailId: emailId,
            reason: reason,
            reportTo: reportTo,
            userId: userId
        });
        let leaveReqRes = await LeaveReq.create({
            empName: userId,
            appliedFrom: fromDate,
            apliedTo: toDate,
            leaveType: leaveType,
            status: req.body.status,
            reqTo: reportTo
        });

        const emp = await findEmp({firstName: reportTo});
        await sendMailToEmp(emp);
        // If you made it to here, everything succeeded.
        res.status(201).json({message: 'leave updated', userId: result.id, status: '1'});

    } catch(e) {
        console.error('Problem in executing create', e);
        throw e; // or next (e) depends on how it is built.
    }
}

function findEmp(filter) {
    return EmpList.findOne({
        attributes:['profEmail'],
        where: filter
    });
}

function sendEmailToEmp(emp) {
    try {
        transporter.sendMail({
            to: emp,
            from: 'CTHRM@coretechies.com,',
            subject: 'You recieved a user request',
            html: `<p>please check your app to take action on this request</p>`
        });
    } catch(e) {
        console.error('Problem in sending mail', e);
    }
}
...