starlight
starlight

Reputation: 785

How to send email in the background using nodemailer for NodeJS application?

I am building an Angular 4 and Node application. Once any user registers on the front-end, I am storing their data in the database, and then would like to send them a successful registration email using the nodemailer package.

Here's the Node js code:

    router.post('/', function(req, res, next) {
       SOME_DATABASE_FUNC() {
           if(FAILED_CASE) {
              return res.status(500).json({
                  title: 'An error occurred',
                  status: 500,
                  error: error
            });

           var mailOptions {...}

           transporter.sendMail(mailOptions, function (error, info) {
              if (error) {
                 console.log(error);
                 return res.status(500).json({
                 title: 'An error occurred',
                 status: 500,
                 error: error
               });
              }
              console.log('Message', info.messageId, info.response);
              return res.status(200).json({
                 message: 'Emailed successfully',
                 details: info
              });
          });
         }
       }
    });

This code works perfectly, but it takes few seconds to send the email, and the user has to wait to show the success response which doesn't seem to fit good. Instead I would like to send it in the background may be as an asynchronous function or like a cron job.

But I am not sure how to transform the code to send it as a job instead of sending and waiting after the database transaction. Please help me out with the issue.

Upvotes: 1

Views: 2118

Answers (3)

Harsh Mangalam
Harsh Mangalam

Reputation: 1299

We knew that nodejs request and response is stream and you can do stuff after sending response stream in this way response time will decrease and other stuff will continue asynchronously after sending response to client.

You can send response successfully to client and then you can call send mail function.

Upvotes: 0

charmi zala
charmi zala

Reputation: 113

send response outside block of transporter.sendMail. So it will not wait for process of email send to be completed.

transporter.sendMail(mailOptions, function (error, info) {
          if (error) {
             console.log(error);
             return res.status(500).json({
             title: 'An error occurred',
             status: 500,
             error: error
           });
          }
          console.log('Message', info.messageId, info.response);
      });
          return res.status(200).json({
             message: 'Emailed successfully',
             details: info
          });

Upvotes: 1

Rishabh
Rishabh

Reputation: 305

use Process.nextTick() for sending email

Upvotes: 0

Related Questions