node.jsexpressmailgun

Not able to set the mailgun key and user name setup


I have Mailgun settings configuration in my database. All I want to the Mailgun Client key, username, and email should be fetched from the database before any mail goes to the client. But I cannot set the data. from: mailgun_email, this part also we fetched from the database. Please help how can I set the data. One more thing if I call the configuration file outside the email file it gives me an error mongoose error which is what I have understand that is the configuration file is called before the database has been set a buffering timeout error.

Error MongooseError: Operation configurations.findOne() buffering timed out after 10000ms

Email file

let mg;

const configuration = async () => {
    const res = await Configuration.findById({ _id: process.env.CONFIGURATION_ID });

    let key = res.mailgun_api_key;
    let username = res.mailgun_username;

    return mailgun.client({
        username,
        key,
    });
};

const successOnRegisterMail = (user_email, user_name) => {
    configuration();
    try {
        mg.messages
            .create("sandbox1f0bc2b687fc416cbd9bdf7a7d1bc24c.mailgun.org", {
                from: mailgun_email,
                to: [user_email],
                subject: "",
                text: "Congratulation you've been successfully registered.",
                html: `<p>Hello ${user_name}</p> <br /><br /> <p>Congratulation you've been successfully registered.</p><br /> Best Regards, <br /> Team Developers`,
            })
            .then((msg) => console.log(msg)) // log response data
            .catch((error) => console.log(error)); // log any error
    } catch (err) {
        console.log("Error from Mail: ", err);
    }
};

Solution

  • Okay after multiple try I figured out the answer.

    const configuration = async () => {
        const res = await Configuration.findById({ _id: process.env.CONFIGURATION_ID });
    
        const mg = mailgun.client({
            username: res.mailgun_username,
            key: res.mailgun_api_key,
        });
    
        if (res) {
            return {
                mg,
                email_id: res.email_id_for_mail_sent,
            };
        } else {
            return console.log("Error Unable To Fetched Data");
        }
    };
    

    Using this inside the mail

    const mailgunData = await configuration();
    
    mailgunData.mg.messages
                .create("sandbox1f0bc2b687fc416cbd9bdf7a7d1bc24c.mailgun.org", {
                    from: mailgunData.email_id,
                    to: [user_email],
                    subject: "",