How to include this nodemailer function inside this controller function?

后端 未结 4 1314
-上瘾入骨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:02

    I would suggest creating a wrapper module around nodemailer, therefore you could reuse the sendEmail function multiple times.

    Make yourself a file called email-client.js or whatever you want. In this module, you can create a closure over smtpTransport and only export the sendEmail function.

    email-client

    const nodemailer = require("nodemailer");
    
    const smtpTransport = nodemailer.createTransport({
        service: "Gmail",
        port: 465,
        auth: {
            user: "YOUR_GMAIL_SERVER",
            pass: "YOUR_GMAIL_PASSWORD"
        }
    });
    
    async function sendMail({ to, subject, html }) {
        return smtpTransport.sendMail({ to, subject, html });
    }
    
    module.exports = {
        sendMail
    };
    

    Note: smtpTransport.sendMail returns a Promise, that we will deal with inside your controller.

    controller

    First, you could import the sendEmail function that's exported from email-client.js, then you can use this in your controller. Note ive changed the controller to be async & prefer mongoose Model.create (makes testing a little easier).

    const { sendEmail } = require("./email-client.js");
    
    exports.createListing = async (req, res) => {
        try {
            if (!req.body.content) {
                return res.status(400).send({
                    message: "Fields can not be empty"
                });
            }
    
            const listing = await Listing.create({
                title: req.body.title,
                city: req.body.city,
                street: req.body.street,
                businessname: req.body.businessname,
                description: req.body.description
            });
    
            await sendEmail({
                to: "blabla",
                subject: "blabla",
                html: `

    ${listing.title}

    ${listing.city}

    ${listing.street}

    ` }); return res.send("Success"); } catch (error) { return res.status(500).send({ message: error.message || "Some error occurred while creating the listing." }); } };

提交回复
热议问题