#📦 Dependencies
#🧑💻 Code
#Step 1: Implement Nodemailer Configurations
In this step, we need to create a configuration file for Nodemailer. We will use the nodemailer.createTransport() method to create a transporter object. The transporter object will require a host, port, secure, and auth object as its parameters. The secure property is a boolean that indicates whether the connection to the email provider should be secure. The auth object should contain the user and password properties. The user property is the email address of the sender, and the password property is the password for the email address. The password should be stored in an environment variable.
import nodemailer from "nodemailer";
const transporter = nodemailer.createTransport({ host: // Mail Host from Env Variable, port: // Mail Port - It have to be Number - Env Variable, secure: false, auth: { user: // Mail User - Env Variable, pass: // Mail Password - Env Variable, },});
export { transporter };#Step 2: Implement Necessary Types for the Mail Options and Transporter
In this step, we will create a file that will contain all the necessary types for the mail transporter and the mail options. The mail transporter will be an object that will have a sendMail method. The mail options will be an object that will contain the from, to, subject, text, and html properties. The from and to properties will be strings, the subject property will be a string, the text property will be an optional string, and the html property will be an optional string.
interface MailOptions { from: string; to: string; subject: string; text?: string; html?: string;}
export { MailOptions };#Step 3: Implement the main mail service using the created transporter and mail options type
In this step, we will create a function that will use the transporter and the mail options type to send an email. The function will take the mail options as an argument and return a promise that resolves to the result of the transporter.sendMail() method. This function will be the main entry point for sending emails in our application.
import { transporter } from "./mail.config";import { MailOptions } from "./mail.type";
const sendMail = async (mailOptions: MailOptions) => { return await transporter.sendMail(mailOptions);};
export default { sendMail };#Step 4: Implement main entry point for Mail Module - This is the Awesome and Best Part!
This is the main entry point for the mail module. We will export the sendMail function from the mail service. This function will accept the mail options as an argument and return a promise that resolves to the result of the transporter.sendMail() method. This function will be the main entry point for sending emails in our application.
import mailService from "./mail.service";
export default { service: mailService,};