Home > Software design >  How to Using Nodemailer
How to Using Nodemailer

Time:05-30

I want to ask how to using nodemailer with dynamic email and pass from database

export const mailTransporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: email_user,
    pass: email_pass,
  },
});

email_user and email_pass from file env, I want to email_user and email_pass from the database, so I think to create a function for getting value email and pass from the database, then save into variable and use in mailTransport. Guys any suggestion or opinion for it?

CodePudding user response:

Wrap your nodemailer.createTransport into a function before you export it, then from the function, you get the credential from DB before constructing the nodemailer.createTransport.

module.exports = createTransportWithCredential

function createTransportWithCredential(){
  return new Promise((resolve,reject)=>{
    //get credential from DB, you may need to use promise-then to handle async situation
    //example:
    getCredentialFromDB().then(credentials=>{       
      let transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
         user: credential.user,
         pass: credential.password,
        },
      });
      resolve(transporter)
    })
  })
}

From the other js file you can do:

const mailer = require("./nodemailer")
mailer.createTransportWithCredential().then(transporter=>{
  //use the transporter
})

CodePudding user response:

Depends on what type of database you have. If you're using mysql you can use the mysql2 package to make queries. It looks like this.

I recommend creating a simple package outside of your main project but this is not completely necessary.

npm init
npm install dotenv mysql2
require('dotenv').config({ path: "/home/ubuntu/.env" });

const mysql = require("mysql2/promise");

const connection = mysql.createPool({
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: "main",
    flags: "-FOUND_ROWS",
    charset: "utf8mb4_0900_ai_ci",
    multipleStatements: true,
    connectionLimit: 10,
    queueLimit: 0
});

module.exports = connection;

Edit the options as you like. This one creates a pool of 10 connections and connects to a database named main. It also allows for multiple statements within a single query. That might not be desirable so turn that off if you'd like. Finally, I'm requiring an environment file, but I am specifying a specific location rather than getting one automatically from within the project folder (since this is its own package that will be imported into the main project).

Next we import the database package into our main project. Just follow this page to install a local package Installing a local module using npm?

It should be something like this while inside your main project directory.

npm install ../database

if your database package is located next to your main project folder. Just replace ../database with whatever the path is to the separate database package.

Now inside our main project, it would look something like this. (I'm assuming you labelled your new package database but if not, just replace with whatever name you used.

require('dotenv').config({ path: "/home/ubuntu/.env" });
const connection = require("database");

const userID = "81cae194-52bd-42d3-9554-66385030c35b";
connection.query(`
    SELECT 
        EmailUsername, 
        EmailPassword 
    FROM 
        UserEmail 
    WHERE 
        UserID = ?
`, [userID])
.then(([results, fields]) => {
    let transporter = nodemailer.createTransport({
        host: process.env.EMAIL_HOST,
        port: process.env.EMAIL_PORT,
        secure: true, 
        auth: {
            user: results[0].EmailUsername,
            pass: results[0].EmailPassword
        },
    });

    // Put transporter.sendMail() here
})
.catch(error => console.log(error));

This is just a sample of what you could do and how you could do it. You need to use your own critical thinking to fit it into your own project and style.

There is no one way to do it and some of the choices I've made are personal decisions. You should be able to merge this with Jerry's answer. He goes more into how to create the nodemailer module. I am only showing you how to connect database data with nodemailer.

Please read up on https://www.npmjs.com/package/mysql2 especially the promise wrapper section. This solution also uses dotenv https://www.npmjs.com/package/dotenv and https://nodemailer.com/about/

  • Related