/config/mail.js
Purpose
This module is responsible for managing email registration workflows, including:
Creating a new user with a temporary password.
Saving the user's email to a mailing list.
Sending a registration email with the temporary password via Mailgun.
Prerequisites
This module relies on the following environment variables to function correctly:
MAILGUN_API_KEY
: Your Mailgun API key for authenticating email delivery.MAILGUN_DOMAIN
: The domain associated with your Mailgun account.
Dependencies
The module makes use of several packages and custom helper files:
nodemailer and nodemailer-mailgun-transport: For configuring and sending emails through Mailgun.
bcrypt: Used to hash the temporary password for secure storage.
mongoose: Handles database operations, specifically to save the user and email details.
Custom Helpers and Models:
generateTemporaryPassword
frompasswordHelper
: Generates a random temporary password for user registration.UserModel
andEmailList
models: Manage user and email list data in MongoDB.
Environment Setup
To configure the Mailgun transporter, you need to define the following in your .env
file:
Functions
transporter
A Mailgun transporter instance is created with nodemailer
using the API key and domain, allowing for secure, authenticated email transmission.
sendRegistrationEmail(email)
This asynchronous function performs the following steps:
Generate and Hash Password: Uses
generateTemporaryPassword
to create a temporary password and hashes it with bcrypt before saving it in the database.Create User Record: Creates a new user in MongoDB with the temporary password and an
email
identifier.Email List Management: Adds the email to a mailing list (using MongoDB’s upsert functionality to prevent duplicates).
Compose and Send Email: Sends a registration email containing the temporary password, instructing the user to update their password upon first login.
Parameters
email
(string): The recipient’s email address.
Sample Email Content
Subject: “Welcome to Our Service!”
Body:
HTML and plain text versions are included, with instructions for logging in and changing the password.
Notes
Customization: Update the
from
field inmailOptions
with your service's email address.Asynchronous Email Handling:
sendMail
runs asynchronously, with results logged to the console.
This file is intended to provide a general-purpose email registration solution, with flexibility for future enhancements or modifications.
This documentation outlines the setup, functionality, and use of /config/mail.js
.
Last updated