How to include this nodemailer function inside this controller function?

后端 未结 4 1309
-上瘾入骨i
-上瘾入骨i 2021-01-28 11:55

I am trying to create a form that will send data to the Mongo DB first then will send that data through the email by Nodemailer. Here are the 2 functions:

contro

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-28 12:15

    Export your sendMail method and import it in your controller.

    controller function

    let sendMail = require('your nodemailer file').sendMail;
    exports.createListing = (req, res) => {
        // Validate request
        if(!req.body.content) {
            return res.status(400).send({
                message: "Fields can not be empty"
            });
        }
    
        const listing = new Listing({
            title: req.body.title, 
            city: req.body.city,
            street: req.body.street,
            businessname: req.body.businessname,
            description: req.body.description
        });
    
        listing.save()
        .then(data => {
            sendMail({
            title: req.body.title, 
            city: req.body.city,
            street: req.body.street})
            res.send(data);
        }).catch(err => {
            res.status(500).send({
                message: err.message || "Some error occurred while creating the listing."
            });
        });
    };
    

    NodeMailer function

    var smtpTransport = nodemailer.createTransport({
            service: 'Gmail',
            port: 465,
            auth: {
              user: 'YOUR_GMAIL_SERVER',
              pass: 'YOUR_GMAIL_PASSWORD'
            }
          });
    
    
    
    module.exports.sendmail = (data)=>{
    return new Promise((resolve,reject)=>{
    
          var mailOptions = {
            to: data.email,
            subject: 'ENTER_YOUR_SUBJECT',
            html: `

    ${data.title}

    ${data.city}

    ${data.street}

    `, ... }; smtpTransport.sendMail(mailOptions, (error, response) => { if (error) { reject(error); } else { resolve('Success'); } smtpTransport.close(); }); }); };

提交回复
热议问题