New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details
Socket
Book a DemoSign in
Socket

mail_driver

Package Overview
Dependencies
Maintainers
1
Versions
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

mail_driver

A comprehensive Node.js package designed for sending emails, built upon the robust Nodemailer library. MailDriver simplifies email functionalities, offering capabilities for sending basic emails, emails with attachments, and templated emails. It also prov

latest
npmnpm
Version
1.0.0
Version published
Maintainers
1
Created
Source

MailDriver

A comprehensive Node.js package designed for sending emails, built upon the robust Nodemailer library. MailDriver simplifies email functionalities, offering capabilities for sending basic emails, emails with attachments, and templated emails. It also provides a clear path for integrating email sending with web forms.

Table of Contents

Installation

To install MailDriver, use npm:

npm install maildriver

Usage

Basic Email

To send a simple text or HTML email:

const MailDriver = require('maildriver');

const config = {
  host: 'smtp.your-email-provider.com',
  port: 587,
  secure: false, // Use true for port 465 (SSL/TLS), false for other ports
  auth: {
    user: 'your_email@example.com', // Your email address
    pass: 'your_password' // Your email password or app-specific password
  }
};

const mailer = new MailDriver(config);

async function sendBasicEmail() {
  try {
    await mailer.sendMail({
      from: '"Sender Name" <sender@example.com>',
      to: 'recipient@example.com',
      subject: 'Hello from MailDriver!',
      text: 'This is a test email sent using the MailDriver package.',
      html: '<b>Hello from MailDriver!</b> This is a <i>test</i> email.'
    });
    console.log('Basic email sent successfully!');
  } catch (error) {
    console.error('Failed to send basic email:', error.message);
  }
}

sendBasicEmail();

Email with Attachments

To include files in your email:

const MailDriver = require('maildriver');

// ... (config and mailer setup as above)

async function sendEmailWithAttachments() {
  try {
    await mailer.sendMailWithAttachments({
      from: '"Sender Name" <sender@example.com>',
      to: 'recipient@example.com',
      subject: 'Email with Attachments',
      text: 'Please find the attached files.',
    }, [
      {
        filename: 'document.pdf',
        path: '/path/to/your/document.pdf' // Path to a file on disk
      },
      {
        filename: 'image.png',
        content: 'base64_encoded_image_data', // Base64 encoded string
        contentType: 'image/png',
        cid: 'unique@nodemailer.com' // For embedding images in HTML
      }
    ]);
    console.log('Email with attachments sent successfully!');
  } catch (error) {
    console.error('Failed to send email with attachments:', error.message);
  }
}

sendEmailWithAttachments();

Templated Email

MailDriver supports simple string templating for HTML emails. For more complex templating, consider integrating with dedicated templating engines like Handlebars or EJS.

const MailDriver = require('maildriver');

// ... (config and mailer setup as above)

async function sendTemplatedEmail() {
  try {
    const template = '<h1>Welcome, {{name}}!</h1><p>Your order #{{orderId}} has been shipped.</p>';
    const replacements = {
      name: 'Jane Doe',
      orderId: '67890'
    };
    await mailer.sendMailWithTemplate({
      from: '"Sender Name" <sender@example.com>',
      to: 'recipient@example.com',
      subject: 'Templated Email',
    }, template, replacements);
    console.log('Templated email sent successfully!');
  } catch (error) {
    console.error('Failed to send templated email:', error.message);
  }
}

sendTemplatedEmail();

Integrating with Web Forms (Backend Example)

This section demonstrates how to set up a simple Node.js Express backend to receive form submissions and send emails using MailDriver. This is a common pattern for handling contact forms or other data submissions from frontend applications (React, Next.js, Vue.js, etc.).

Prerequisites

Ensure you have Node.js and npm installed. You'll also need to install express and body-parser:

npm install express body-parser

Backend Setup

Create a file named server.js (or similar) in your project directory with the following content:

const express = require('express');
const bodyParser = require('body-parser');
const MailDriver = require('./index'); // Adjust path if your MailDriver is elsewhere

const app = express();
const port = 3000;

// Middleware to parse JSON and URL-encoded data from requests
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// IMPORTANT: Configure your email settings here
const mailConfig = {
  host: 'smtp.your-email-provider.com', // e.g., 'smtp.gmail.com' for Gmail
  port: 587,
  secure: false, // true for 465 (SSL/TLS), false for other ports
  auth: {
    user: 'your_email@example.com', // Your actual email address
    pass: 'your_password' // Your actual email password or app-specific password
  }
};

const mailer = new MailDriver(mailConfig);

// Enable CORS for development (restrict in production for security)
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*'); // Allow requests from any origin
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  next();
});

// POST endpoint to handle form submissions
app.post('/submit-form', async (req, res) => {
  const formData = req.body;
  console.log('Form data received:', formData);

  // Construct the email content from form data
  const emailContent = `
    New Form Submission:
    --------------------
    Name: ${formData.name || 'N/A'}
    Email: ${formData.email || 'N/A'}
    Message: ${formData.message || 'N/A'}
    --------------------
  `;

  try {
    // IMPORTANT: Change 'your_receiving_email@example.com' to your actual email
    await mailer.sendMail({
      from: '"Form Submitter" <no-reply@example.com>',
      to: 'your_receiving_email@example.com', // Email address to receive submissions
      subject: 'New Form Submission from Website',
      text: emailContent,
      html: `<p><strong>New Form Submission:</strong></p>
             <ul>
               <li><strong>Name:</strong> ${formData.name || 'N/A'}</li>
               <li><strong>Email:</strong> ${formData.email || 'N/A'}</li>
               <li><strong>Message:</strong> ${formData.message || 'N/A'}</li>
             </ul>`
    });
    res.status(200).send('Form submitted and email sent successfully!');
  } catch (error) {
    console.error('Failed to send email:', error);
    res.status(500).send('Failed to submit form and send email.');
  }
});

// Start the server
app.listen(port, () => {
  console.log(`Server listening at http://localhost:${port}`);
});

Running the Backend Server

To easily run your backend server, add a start script to your package.json:

{
  "name": "mail_driver",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.20.2",
    "express": "^4.19.2",
    "nodemailer": "^6.9.13"
  }
}

Then, you can start the server by running:

npm start

The server will be accessible at http://localhost:3000.

Frontend Integration (Example HTML)

Here's a basic HTML form example that sends data to the Express backend. You can adapt this logic to your preferred frontend framework (React, Next.js, Vue.js, Angular, etc.).

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Contact Form</title>
</head>
<body>
    <h1>Contact Us</h1>
    <form id="contactForm">
        <label for="name">Name:</label><br>
        <input type="text" id="name" name="name" required><br><br>

        <label for="email">Email:</label><br>
        <input type="email" id="email" name="email" required><br><br>

        <label for="message">Message:</label><br>
        <textarea id="message" name="message" rows="5" required></textarea><br><br>

        <button type="submit">Submit</button>
    </form>

    <p id="responseMessage"></p>

    <script>
        document.getElementById('contactForm').addEventListener('submit', async function(event) {
            event.preventDefault();

            const formData = {
                name: document.getElementById('name').value,
                email: document.getElementById('email').value,
                message: document.getElementById('message').value
            };

            try {
                const response = await fetch('http://localhost:3000/submit-form', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(formData)
                });

                const result = await response.text();
                document.getElementById('responseMessage').textContent = result;
                if (response.ok) {
                    document.getElementById('responseMessage').style.color = 'green';
                    document.getElementById('contactForm').reset(); // Clear the form on success
                } else {
                    document.getElementById('responseMessage').style.color = 'red';
                }
            } catch (error) {
                console.error('Error:', error);
                document.getElementById('responseMessage').textContent = 'An error occurred while submitting the form.';
                document.getElementById('responseMessage').style.color = 'red';
            }
        });
    </script>
</body>
</html>

API Reference

new MailDriver(config)

Creates a new MailDriver instance.

  • config: A Nodemailer transporter configuration object. This object defines how emails will be sent (e.g., SMTP server details, authentication).

sendMail(mailOptions)

Sends a basic email with text or HTML content.

  • mailOptions: A Nodemailer mail options object. Key properties include:
    • from: Sender email address (e.g., "Sender Name" <sender@example.com>).
    • to: Recipient email address(es) (comma-separated for multiple).
    • subject: The subject line of the email.
    • text: Plain text body of the email.
    • html: HTML body of the email.

sendMailWithAttachments(mailOptions, attachments)

Sends an email that includes one or more file attachments.

  • mailOptions: A Nodemailer mail options object (same as sendMail).
  • attachments: An array of Nodemailer attachment objects. Each object can specify filename, path (for local files), content (for string/buffer content), contentType, and cid (for embedded images).

sendMailWithTemplate(mailOptions, template, replacements)

Sends an email using a simple string-based HTML template with placeholders.

  • mailOptions: A Nodemailer mail options object (same as sendMail).
  • template: A string containing the HTML template. Placeholders should be in the format {{key}}.
  • replacements: An object where keys correspond to the placeholder names in the template and values are their replacements.

Configuration

MailDriver uses Nodemailer for email transport. The config object passed to the MailDriver constructor should follow Nodemailer's transporter configuration options.

Common configuration options include:

  • host: SMTP server hostname (e.g., smtp.gmail.com, smtp.mailtrap.io).
  • port: SMTP server port (e.g., 587 for TLS, 465 for SSL).
  • secure: true if using SSL/TLS (usually with port 465), false otherwise.
  • auth: An object containing user (your email address) and pass (your email password or app-specific password).

Example for Gmail (requires App Password if 2FA is enabled):

const config = {
  host: 'smtp.gmail.com',
  port: 465,
  secure: true, // Use SSL
  auth: {
    user: 'your_gmail_address@gmail.com',
    pass: 'your_app_password' // Generate an App Password in Google Account settings
  }
};

Example for Mailtrap (for testing):

const config = {
  host: 'smtp.mailtrap.io',
  port: 2525,
  secure: false,
  auth: {
    user: 'YOUR_MAILTRAP_USERNAME',
    pass: 'YOUR_MAILTRAP_PASSWORD'
  }
};

Contributing

Contributions are welcome! Feel free to open issues for bug reports or feature requests, and submit pull requests for improvements.

License

This project is licensed under the ISC License.

FAQs

Package last updated on 10 Sep 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts