node simple-imap | get attachments using simple-imap | Cell 7 | Search

This code defines a reusable function sendEmail that sends emails via Gmail using Nodemailer, securely retrieving credentials and handling email sending asynchronously.

Run example

npm run import -- "send email"

send email

var nodemailer = require('nodemailer')
var importer = require('../Core');
var getCredentials = importer.import("decrypt passwords");

function sendEmail(to, text, subject, from) {
    var credentials = getCredentials('accounts.google.com');
    process.env.GOOGLE_USER = credentials.Email;
    process.env.GOOGLE_PASS = credentials.Passwd;

    // create reusable transporter object using the default SMTP transport
    let transporter = nodemailer.createTransport({
        host: 'smtp.gmail.com',
        port: 465,
        secure: true, // true for 465, false for other ports
        auth: {
            user: process.env.GOOGLE_USER, // generated ethereal user
            pass: process.env.GOOGLE_PASS  // generated ethereal password
        }
    });

    // setup email data with unicode symbols
    let mailOptions = {
        from: from, // sender address
        to: to, // list of receivers
        subject: subject, // Subject line
        text: text, // plain text body
        html: text // html body
    };

    // send mail with defined transport object
    return new Promise((resolve, reject) => {
        transporter.sendMail(mailOptions, (error, info) => {
            if (error) {
                return reject(error);
            }
            resolve(info.messageId);
        });
    });
}
module.exports = sendEmail;

What the code could have been:

const nodemailer = require('nodemailer');
const importer = require('../Core');
const getCredentials = importer.import('decrypt passwords');

/**
 * Sends an email using Gmail SMTP server.
 * @param {string} to - recipient email address
 * @param {string} text - email body
 * @param {string} subject - email subject
 * @param {string} from - sender email address
 * @returns {Promise} - email message ID
 */
async function sendEmail(to, text, subject, from) {
  try {
    // Load account credentials from environment
    const { Email, Passwd } = getCredentials('accounts.google.com');

    // Set email credentials from environment
    process.env.GOOGLE_USER = Email;
    process.env.GOOGLE_PASS = Passwd;

    // Create reusable transporter object
    const transporter = nodemailer.createTransport({
      host:'smtp.gmail.com',
      port: 465,
      secure: true, // true for 465, false for other ports
      auth: {
        user: process.env.GOOGLE_USER, // generated ethereal user
        pass: process.env.GOOGLE_PASS, // generated ethereal password
      },
    });

    // Setup email data with unicode symbols
    const mailOptions = {
      from: from, // sender address
      to: to, // list of receivers
      subject: subject, // Subject line
      text: text, // plain text body
      html: text, // html body
    };

    // Send mail with defined transport object
    const result = await new Promise((resolve, reject) => {
      transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
          reject(error);
        }
        resolve(info.messageId);
      });
    });

    return result;
  } catch (error) {
    // Log errors to facilitate debugging
    console.error('Error sending email:', error);
    throw error;
  }
}

module.exports = sendEmail;

This code defines a function sendEmail that sends emails using Nodemailer and Gmail.

Here's a breakdown:

  1. Dependencies:

  2. Credential Retrieval:

  3. Email Sending Function:

  4. Export:

In essence, this code provides a reusable function for sending emails through Gmail using Nodemailer, securely handling credentials and returning a promise for asynchronous email sending.